birdclaw 0.8.3 → 0.8.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (284) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/README.md +10 -8
  3. package/bin/birdclaw.mjs +4 -66
  4. package/dist/cli/birdclaw.js +28165 -0
  5. package/dist/client/assets/AvatarChip-DLoqM5xD.js +1 -0
  6. package/dist/client/assets/ProfilePreview-BejAuYsJ.js +1 -0
  7. package/dist/client/assets/SavedTimelineView-BIS7HKpp.js +1 -0
  8. package/dist/client/assets/SmartTimestamp-BR0-9se2.js +1 -0
  9. package/dist/client/assets/TimelineRouteFrame-CyGPj0eM.js +1 -0
  10. package/dist/client/assets/blocks-7UDKQp8H.js +1 -0
  11. package/dist/client/assets/bookmarks-CbBkMvXk.js +1 -0
  12. package/dist/client/assets/chunk-C0phanGV.js +1 -0
  13. package/dist/client/assets/circle-check-C_Vq3ElD.js +1 -0
  14. package/dist/client/assets/client-stream-contracts-ys3XhWG4.js +5 -0
  15. package/dist/client/assets/createLucideIcon-JV8isFFR.js +1 -0
  16. package/dist/client/assets/data-sources-Cm2bpNvg.js +1 -0
  17. package/dist/client/assets/discuss-DTjaOugw.js +1 -0
  18. package/dist/client/assets/dms-CGd6Eogq.js +1 -0
  19. package/dist/client/assets/inbox-BHlGuOy2.js +1 -0
  20. package/dist/client/assets/index-CEIG7S6s.js +31 -0
  21. package/dist/client/assets/index-bpFrQ5yG.css +1 -0
  22. package/dist/client/assets/likes-cLrcAQem.js +1 -0
  23. package/dist/client/assets/links-CM9QO1LC.js +1 -0
  24. package/dist/client/assets/mapbox-BxTlqXt9.js +2 -0
  25. package/dist/client/assets/mapbox-gl-dgf_hX3a.js +3215 -0
  26. package/dist/client/assets/mentions-CxKCgzIf.js +1 -0
  27. package/dist/client/assets/network-map-B5a3whqj.js +2 -0
  28. package/dist/client/assets/profile-analyze-CRtNEwlb.js +1 -0
  29. package/dist/client/assets/profile-hydration-client-YEtJsNTv.js +1 -0
  30. package/dist/client/assets/profiles._handle-C82_HoKX.js +1 -0
  31. package/dist/client/assets/query-client-fYu2rzRC.js +17 -0
  32. package/dist/client/assets/rate-limits-ScaEwdVK.js +1 -0
  33. package/dist/client/assets/react-dom-DHl6Ug7F.js +1 -0
  34. package/dist/client/assets/react-nBylq1U5.js +1 -0
  35. package/dist/client/assets/repeat-2-xCwHM9hD.js +1 -0
  36. package/dist/client/assets/routes-q7ZaW4En.js +1 -0
  37. package/dist/client/assets/schemas-I9r6F6ya.js +64 -0
  38. package/dist/client/assets/search-Dq5kYsxA.js +1 -0
  39. package/dist/client/assets/sparkles-CQVlvHsZ.js +1 -0
  40. package/dist/client/assets/styles-B8s3tt3r.css +2 -0
  41. package/dist/client/assets/today-CeG1O7Py.js +1 -0
  42. package/dist/client/assets/triangle-alert-CBL7s2pf.js +1 -0
  43. package/dist/client/assets/useTimelineRouteData-1HsqgvUi.js +1 -0
  44. package/dist/client/assets/users-CHbKlqUr.js +1 -0
  45. package/dist/server/assets/AvatarChip-zUDAEmjL.js +105 -0
  46. package/dist/server/assets/FeedState-ntW0Q2GB.js +214 -0
  47. package/dist/server/assets/ProfileAnalysisStream-BFvhVdhn.js +198 -0
  48. package/dist/server/assets/ProfilePreview-C6gAor_j.js +752 -0
  49. package/dist/server/assets/SavedTimelineView-BG1jnBp1.js +64 -0
  50. package/dist/server/assets/SmartTimestamp-DfwE1NGf.js +45 -0
  51. package/dist/server/assets/SyncNowButton-BOn_IBXS.js +76 -0
  52. package/dist/server/assets/TimelineRouteFrame-CU7ilM7U.js +85 -0
  53. package/dist/server/assets/TweetRichText-DhCVv1-6.js +74 -0
  54. package/dist/server/assets/_tanstack-start-manifest_v-C-ZRnG_n.js +148 -0
  55. package/dist/server/assets/account-selection-CTdFGWRk.js +44 -0
  56. package/dist/server/assets/blocks-C1mgGTB3.js +299 -0
  57. package/dist/server/assets/blocks-DSgQghqP.js +17 -0
  58. package/dist/server/assets/bookmarks-BJN8tykY.js +14 -0
  59. package/dist/server/assets/client-stream-contracts-C2xbWVjm.js +769 -0
  60. package/dist/server/assets/data-sources-BnA1Q94p.js +180 -0
  61. package/dist/server/assets/discuss-CJ1dau1j.js +15 -0
  62. package/dist/server/assets/discuss-QTo08NCN.js +338 -0
  63. package/dist/server/assets/dms-BuLj4bp8.js +368 -0
  64. package/dist/server/assets/dms-DAyQrVM2.js +240 -0
  65. package/dist/server/assets/empty-plugin-adapters-DzrEkdBF.js +5 -0
  66. package/dist/server/assets/inbox-CkGOaW1q.js +214 -0
  67. package/dist/server/assets/inbox-DpWd1EzC.js +146 -0
  68. package/dist/server/assets/likes-DBOAtsJU.js +14 -0
  69. package/dist/server/assets/links-DAhSjynu.js +240 -0
  70. package/dist/server/assets/links-DmH5lxHO.js +468 -0
  71. package/dist/server/assets/mentions-BH2MzKtB.js +26 -0
  72. package/dist/server/assets/network-map-D3CzRcC4.js +224 -0
  73. package/dist/server/assets/network-map-D5DoLOwR.js +582 -0
  74. package/dist/server/assets/profile-analyze-BP65PED0.js +90 -0
  75. package/dist/server/assets/profile-analyze-C1NoM0tV.js +9 -0
  76. package/dist/server/assets/profile-hydration-client-GJ4kwJS8.js +133 -0
  77. package/dist/server/assets/profiles._handle-DjwlN_ac.js +184 -0
  78. package/dist/server/assets/profiles._handle-DsLNj2Ca.js +12 -0
  79. package/dist/server/assets/query-client-BdauHBgd.js +923 -0
  80. package/dist/server/assets/rate-limits-VAr2qzYD.js +262 -0
  81. package/dist/server/assets/route-search-BUlQ5lGM.js +117 -0
  82. package/dist/server/assets/router-DqkwSPiM.js +17026 -0
  83. package/dist/server/assets/routes-A9c9ZhwN.js +26 -0
  84. package/dist/server/assets/start-FaDOTmto.js +4 -0
  85. package/dist/server/assets/today-B5hVM57Z.js +17 -0
  86. package/dist/server/assets/today-fvGiZ7ud.js +303 -0
  87. package/dist/server/assets/ui-qbmcMSSX.js +137 -0
  88. package/{src/components/useDebouncedValue.ts → dist/server/assets/useDebouncedValue-DOnA6Xcy.js} +4 -4
  89. package/dist/server/assets/useTimelineRouteData-27cxynxa.js +1101 -0
  90. package/dist/server/server.js +5520 -0
  91. package/package.json +26 -34
  92. package/playwright.config.ts +0 -35
  93. package/scripts/browser-perf.mjs +0 -427
  94. package/scripts/build-docs-site.mjs +0 -967
  95. package/scripts/docs-site-assets.mjs +0 -311
  96. package/scripts/run-vitest.mjs +0 -21
  97. package/scripts/sanitize-node-options.mjs +0 -23
  98. package/scripts/start-test-server.mjs +0 -42
  99. package/src/cli/command-context.ts +0 -17
  100. package/src/cli/register-analysis.ts +0 -500
  101. package/src/cli/register-compose.ts +0 -40
  102. package/src/cli/register-graph.ts +0 -132
  103. package/src/cli/register-inbox.ts +0 -41
  104. package/src/cli/register-storage.ts +0 -106
  105. package/src/cli-moderation.ts +0 -210
  106. package/src/cli.ts +0 -1616
  107. package/src/components/AccountSwitcher.tsx +0 -178
  108. package/src/components/AppNav.tsx +0 -118
  109. package/src/components/AvatarChip.tsx +0 -58
  110. package/src/components/AvatarPreload.ts +0 -149
  111. package/src/components/BrandMark.tsx +0 -67
  112. package/src/components/ConversationThread.tsx +0 -131
  113. package/src/components/DmWorkspace.tsx +0 -286
  114. package/src/components/EmbeddedTweetCard.tsx +0 -55
  115. package/src/components/FeedState.tsx +0 -147
  116. package/src/components/FloatingPreview.tsx +0 -382
  117. package/src/components/InboxCard.tsx +0 -152
  118. package/src/components/LinkPreviewCard.tsx +0 -292
  119. package/src/components/MarkdownCitations.tsx +0 -680
  120. package/src/components/MarkdownViewer.tsx +0 -111
  121. package/src/components/ProfileAnalysisClient.ts +0 -191
  122. package/src/components/ProfileAnalysisStream.tsx +0 -259
  123. package/src/components/ProfilePreview.tsx +0 -131
  124. package/src/components/SavedTimelineView.tsx +0 -155
  125. package/src/components/SmartTimestamp.tsx +0 -72
  126. package/src/components/SyncNowButton.tsx +0 -140
  127. package/src/components/ThemeSlider.tsx +0 -80
  128. package/src/components/TimelineCard.tsx +0 -533
  129. package/src/components/TimelineRouteFrame.tsx +0 -186
  130. package/src/components/TweetArticleCard.tsx +0 -66
  131. package/src/components/TweetMediaGrid.tsx +0 -185
  132. package/src/components/TweetRichText.tsx +0 -159
  133. package/src/components/account-selection.ts +0 -64
  134. package/src/components/links-controller.ts +0 -162
  135. package/src/components/links-model.ts +0 -198
  136. package/src/components/network-map-controller.ts +0 -84
  137. package/src/components/network-map-model.ts +0 -255
  138. package/src/components/useTimelineRouteData.ts +0 -193
  139. package/src/lib/account-sync-job.ts +0 -666
  140. package/src/lib/actions-transport.ts +0 -300
  141. package/src/lib/analysis-runtime.ts +0 -238
  142. package/src/lib/api-client.ts +0 -220
  143. package/src/lib/api-contracts.ts +0 -328
  144. package/src/lib/archive-finder.ts +0 -185
  145. package/src/lib/archive-import-plan.ts +0 -102
  146. package/src/lib/archive-import.ts +0 -2695
  147. package/src/lib/authored-live.ts +0 -1027
  148. package/src/lib/avatar-cache.ts +0 -349
  149. package/src/lib/backup.ts +0 -2652
  150. package/src/lib/bird-actions.ts +0 -294
  151. package/src/lib/bird-command.ts +0 -130
  152. package/src/lib/bird.ts +0 -1140
  153. package/src/lib/blocklist.ts +0 -136
  154. package/src/lib/blocks-write.ts +0 -171
  155. package/src/lib/blocks.ts +0 -387
  156. package/src/lib/bookmark-sync-job.ts +0 -536
  157. package/src/lib/config.ts +0 -224
  158. package/src/lib/conversation-surface.ts +0 -205
  159. package/src/lib/data-sources.ts +0 -219
  160. package/src/lib/database-metrics.ts +0 -88
  161. package/src/lib/database-migrations.ts +0 -34
  162. package/src/lib/database-schema.ts +0 -312
  163. package/src/lib/database-writer.ts +0 -69
  164. package/src/lib/db.ts +0 -889
  165. package/src/lib/dm-read-model.ts +0 -533
  166. package/src/lib/dms-live.ts +0 -870
  167. package/src/lib/effect-runtime.ts +0 -45
  168. package/src/lib/follow-graph.ts +0 -1087
  169. package/src/lib/geocoding.ts +0 -296
  170. package/src/lib/http-effect.ts +0 -222
  171. package/src/lib/identity-search-index.ts +0 -369
  172. package/src/lib/import-repository.ts +0 -138
  173. package/src/lib/inbox.ts +0 -242
  174. package/src/lib/link-index.ts +0 -641
  175. package/src/lib/link-insights.ts +0 -860
  176. package/src/lib/link-preview-metadata.ts +0 -754
  177. package/src/lib/live-sync-engine.ts +0 -209
  178. package/src/lib/live-transport-gateway.ts +0 -128
  179. package/src/lib/location.ts +0 -137
  180. package/src/lib/media-fetch.ts +0 -860
  181. package/src/lib/media-includes.ts +0 -165
  182. package/src/lib/mention-threads-live.ts +0 -830
  183. package/src/lib/mentions-export.ts +0 -147
  184. package/src/lib/mentions-live.ts +0 -1114
  185. package/src/lib/moderation-target.ts +0 -227
  186. package/src/lib/moderation-write.ts +0 -131
  187. package/src/lib/mutes-write.ts +0 -171
  188. package/src/lib/mutes.ts +0 -84
  189. package/src/lib/ndjson-stream.ts +0 -106
  190. package/src/lib/network-map.ts +0 -382
  191. package/src/lib/openai-response-runtime.ts +0 -251
  192. package/src/lib/openai.ts +0 -117
  193. package/src/lib/paginated-sync.ts +0 -93
  194. package/src/lib/period-digest.ts +0 -1364
  195. package/src/lib/present.ts +0 -118
  196. package/src/lib/profile-affiliation-hydration.ts +0 -228
  197. package/src/lib/profile-affiliations.ts +0 -262
  198. package/src/lib/profile-analysis.ts +0 -1198
  199. package/src/lib/profile-bio-entities.ts +0 -318
  200. package/src/lib/profile-history.ts +0 -164
  201. package/src/lib/profile-hydration.ts +0 -180
  202. package/src/lib/profile-replies.ts +0 -77
  203. package/src/lib/profile-resolver.ts +0 -650
  204. package/src/lib/queries.ts +0 -6
  205. package/src/lib/query-actions.ts +0 -437
  206. package/src/lib/query-client.tsx +0 -47
  207. package/src/lib/query-read-model-shared.ts +0 -52
  208. package/src/lib/query-read-models.ts +0 -5
  209. package/src/lib/query-resource.ts +0 -41
  210. package/src/lib/query-status.ts +0 -164
  211. package/src/lib/research.ts +0 -652
  212. package/src/lib/runtime-services.ts +0 -20
  213. package/src/lib/search-discussion.ts +0 -812
  214. package/src/lib/seed.ts +0 -613
  215. package/src/lib/server-runtime-services.ts +0 -30
  216. package/src/lib/sqlite.ts +0 -183
  217. package/src/lib/streaming-ingestion.ts +0 -240
  218. package/src/lib/sync-cache.ts +0 -70
  219. package/src/lib/sync-plan.ts +0 -175
  220. package/src/lib/theme-transition.ts +0 -113
  221. package/src/lib/theme.tsx +0 -165
  222. package/src/lib/timeline-collections-live.ts +0 -407
  223. package/src/lib/timeline-live.ts +0 -302
  224. package/src/lib/timeline-read-model.ts +0 -1191
  225. package/src/lib/tweet-account-edges.ts +0 -48
  226. package/src/lib/tweet-lookup.ts +0 -46
  227. package/src/lib/tweet-render.ts +0 -430
  228. package/src/lib/tweet-repository.ts +0 -156
  229. package/src/lib/tweet-search-live.ts +0 -462
  230. package/src/lib/types.ts +0 -723
  231. package/src/lib/ui.ts +0 -529
  232. package/src/lib/url-expansion-store.ts +0 -110
  233. package/src/lib/url-expansion.ts +0 -343
  234. package/src/lib/url-safety.ts +0 -220
  235. package/src/lib/web-sync.ts +0 -533
  236. package/src/lib/whois.ts +0 -1080
  237. package/src/lib/x-profile.ts +0 -365
  238. package/src/lib/x-web.ts +0 -199
  239. package/src/lib/xurl-rate-limits.ts +0 -267
  240. package/src/lib/xurl.ts +0 -1677
  241. package/src/routeTree.gen.ts +0 -723
  242. package/src/router.tsx +0 -20
  243. package/src/routes/__root.tsx +0 -82
  244. package/src/routes/api/action.tsx +0 -147
  245. package/src/routes/api/avatar.tsx +0 -50
  246. package/src/routes/api/blocks.tsx +0 -35
  247. package/src/routes/api/conversation.tsx +0 -45
  248. package/src/routes/api/data-sources.tsx +0 -24
  249. package/src/routes/api/inbox.tsx +0 -43
  250. package/src/routes/api/link-insights.tsx +0 -85
  251. package/src/routes/api/link-preview.tsx +0 -47
  252. package/src/routes/api/network-map.tsx +0 -55
  253. package/src/routes/api/period-digest.tsx +0 -101
  254. package/src/routes/api/profile-analysis.tsx +0 -97
  255. package/src/routes/api/profile-hydrate.tsx +0 -54
  256. package/src/routes/api/query.tsx +0 -121
  257. package/src/routes/api/search-discussion.tsx +0 -113
  258. package/src/routes/api/status.tsx +0 -30
  259. package/src/routes/api/sync.tsx +0 -108
  260. package/src/routes/api/xurl-rate-limits.tsx +0 -24
  261. package/src/routes/blocks.tsx +0 -343
  262. package/src/routes/bookmarks.tsx +0 -18
  263. package/src/routes/data-sources.tsx +0 -249
  264. package/src/routes/discuss.tsx +0 -419
  265. package/src/routes/dms.tsx +0 -415
  266. package/src/routes/inbox.tsx +0 -232
  267. package/src/routes/index.tsx +0 -32
  268. package/src/routes/likes.tsx +0 -18
  269. package/src/routes/links.tsx +0 -631
  270. package/src/routes/mentions.tsx +0 -32
  271. package/src/routes/network-map.tsx +0 -732
  272. package/src/routes/profile-analyze.tsx +0 -112
  273. package/src/routes/profiles.$handle.tsx +0 -228
  274. package/src/routes/rate-limits.tsx +0 -305
  275. package/src/routes/today.tsx +0 -511
  276. package/src/styles.css +0 -257
  277. package/tsconfig.json +0 -29
  278. package/vite.config.ts +0 -29
  279. /package/{public → dist/client}/birdclaw-mark.png +0 -0
  280. /package/{public → dist/client}/favicon.ico +0 -0
  281. /package/{public → dist/client}/logo192.png +0 -0
  282. /package/{public → dist/client}/logo512.png +0 -0
  283. /package/{public → dist/client}/manifest.json +0 -0
  284. /package/{public → dist/client}/robots.txt +0 -0
package/src/lib/sqlite.ts DELETED
@@ -1,183 +0,0 @@
1
- import { DatabaseSync, type StatementSync } from "node:sqlite";
2
-
3
- export type Database = NativeSqliteDatabase;
4
-
5
- type DatabaseOptions = {
6
- readonly?: boolean;
7
- fileMustExist?: boolean;
8
- timeout?: number;
9
- onStatement?: (sql: string, durationMs: number) => void;
10
- };
11
-
12
- type PragmaOptions = {
13
- simple?: boolean;
14
- };
15
-
16
- type RunResult = {
17
- changes: number;
18
- lastInsertRowid: number;
19
- };
20
-
21
- export const SQLITE_BUSY_TIMEOUT_MS = 30_000;
22
-
23
- function bindArgs(parameters: unknown[]) {
24
- if (parameters.length === 1 && Array.isArray(parameters[0])) {
25
- return parameters[0];
26
- }
27
- return parameters;
28
- }
29
-
30
- function normalizeValue(value: unknown): unknown {
31
- if (value instanceof Uint8Array && !Buffer.isBuffer(value)) {
32
- return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
33
- }
34
- return value;
35
- }
36
-
37
- function normalizeRow(row: unknown): unknown {
38
- if (
39
- !row ||
40
- typeof row !== "object" ||
41
- Array.isArray(row) ||
42
- Buffer.isBuffer(row)
43
- ) {
44
- return normalizeValue(row);
45
- }
46
- return Object.fromEntries(
47
- Object.entries(row as Record<string, unknown>).map(([key, value]) => [
48
- key,
49
- normalizeValue(value),
50
- ]),
51
- );
52
- }
53
-
54
- class NativeSqliteStatement {
55
- readonly reader: boolean;
56
-
57
- constructor(
58
- private readonly statement: StatementSync,
59
- private readonly sql: string,
60
- private readonly onStatement?: (sql: string, durationMs: number) => void,
61
- ) {
62
- this.reader = statement.columns().length > 0;
63
- }
64
-
65
- private track<T>(operation: () => T) {
66
- const startedAt = performance.now();
67
- try {
68
- return operation();
69
- } finally {
70
- this.onStatement?.(this.sql, performance.now() - startedAt);
71
- }
72
- }
73
-
74
- all(...parameters: unknown[]): unknown[] {
75
- return this.track(() =>
76
- this.statement.all(...bindArgs(parameters)).map(normalizeRow),
77
- );
78
- }
79
-
80
- get(...parameters: unknown[]): unknown {
81
- return this.track(() =>
82
- normalizeRow(this.statement.get(...bindArgs(parameters))),
83
- );
84
- }
85
-
86
- run(...parameters: unknown[]): RunResult {
87
- return this.track(() => {
88
- const result = this.statement.run(...bindArgs(parameters));
89
- return {
90
- changes: Number(result.changes),
91
- lastInsertRowid: Number(result.lastInsertRowid),
92
- };
93
- });
94
- }
95
-
96
- iterate(...parameters: unknown[]): IterableIterator<unknown> {
97
- const rows = this.statement.iterate(...bindArgs(parameters));
98
- const startedAt = performance.now();
99
- const onStatement = this.onStatement;
100
- const sql = this.sql;
101
- return (function* () {
102
- try {
103
- for (const row of rows) {
104
- yield normalizeRow(row);
105
- }
106
- } finally {
107
- onStatement?.(sql, performance.now() - startedAt);
108
- }
109
- })();
110
- }
111
- }
112
-
113
- export class NativeSqliteDatabase {
114
- readonly writeIdentity: string | object;
115
- private transactionDepth = 0;
116
- private readonly db: DatabaseSync;
117
-
118
- constructor(
119
- path: string,
120
- private readonly options: DatabaseOptions = {},
121
- ) {
122
- this.writeIdentity = path === ":memory:" ? this : path;
123
- this.db = new DatabaseSync(path, {
124
- readOnly: options.readonly,
125
- timeout: options.timeout ?? SQLITE_BUSY_TIMEOUT_MS,
126
- });
127
- }
128
-
129
- close(): void {
130
- if (!this.db.isOpen) {
131
- return;
132
- }
133
- this.db.close();
134
- }
135
-
136
- exec(sql: string): void {
137
- this.db.exec(sql);
138
- }
139
-
140
- pragma(sql: string, options: PragmaOptions = {}): unknown {
141
- const rows = this.prepare(`pragma ${sql}`).all() as Array<
142
- Record<string, unknown>
143
- >;
144
- if (!options.simple) {
145
- return rows;
146
- }
147
- const first = rows[0];
148
- return first ? Object.values(first)[0] : undefined;
149
- }
150
-
151
- prepare(sql: string): NativeSqliteStatement {
152
- return new NativeSqliteStatement(
153
- this.db.prepare(sql),
154
- sql,
155
- this.options.onStatement,
156
- );
157
- }
158
-
159
- transaction<TArgs extends unknown[], TResult>(
160
- fn: (...args: TArgs) => TResult,
161
- ): (...args: TArgs) => TResult {
162
- return (...args: TArgs) => {
163
- const nested = this.db.isTransaction;
164
- const savepoint = `__birdclaw_tx_${++this.transactionDepth}`;
165
- this.exec(nested ? `savepoint ${savepoint}` : "begin immediate");
166
- try {
167
- const result = fn(...args);
168
- this.exec(nested ? `release ${savepoint}` : "commit");
169
- return result;
170
- } catch (error) {
171
- if (nested) {
172
- this.exec(`rollback to ${savepoint}`);
173
- this.exec(`release ${savepoint}`);
174
- } else {
175
- this.exec("rollback");
176
- }
177
- throw error;
178
- }
179
- };
180
- }
181
- }
182
-
183
- export default NativeSqliteDatabase;
@@ -1,240 +0,0 @@
1
- import { createReadStream } from "node:fs";
2
- import { createInterface } from "node:readline";
3
- import { Effect } from "effect";
4
-
5
- export interface IngestionCheckpoint {
6
- processed: number;
7
- }
8
-
9
- export interface IngestionSource<T> {
10
- id: string;
11
- stream: () => AsyncIterable<T>;
12
- }
13
-
14
- export interface IngestionSourceCheckpoint extends IngestionCheckpoint {
15
- sourceId: string;
16
- sourceIndex: number;
17
- sourceProcessed: number;
18
- sources: number;
19
- }
20
-
21
- export async function* streamJsonLines(
22
- filePath: string,
23
- ): AsyncGenerator<{ lineNumber: number; value: Record<string, unknown> }> {
24
- const input = createReadStream(filePath, { encoding: "utf8" });
25
- const lines = createInterface({ input, crlfDelay: Infinity });
26
- let lineNumber = 0;
27
- for await (const line of lines) {
28
- lineNumber += 1;
29
- if (!line.trim()) continue;
30
- yield {
31
- lineNumber,
32
- value: JSON.parse(line) as Record<string, unknown>,
33
- };
34
- }
35
- }
36
-
37
- export async function* streamAssignedJsonArray(
38
- source: AsyncIterable<Buffer | string>,
39
- ): AsyncGenerator<Record<string, unknown>> {
40
- let started = false;
41
- let item = "";
42
- let depth = 0;
43
- let inString = false;
44
- let escaped = false;
45
-
46
- const flush = () => {
47
- const value = item.trim();
48
- item = "";
49
- return value ? (JSON.parse(value) as Record<string, unknown>) : undefined;
50
- };
51
-
52
- for await (const chunk of source) {
53
- for (const character of String(chunk)) {
54
- if (!started) {
55
- if (character === "[") started = true;
56
- continue;
57
- }
58
-
59
- if (inString) {
60
- item += character;
61
- if (escaped) {
62
- escaped = false;
63
- } else if (character === "\\") {
64
- escaped = true;
65
- } else if (character === '"') {
66
- inString = false;
67
- }
68
- continue;
69
- }
70
-
71
- if (character === '"') {
72
- inString = true;
73
- item += character;
74
- continue;
75
- }
76
- if (character === "{" || character === "[") {
77
- depth += 1;
78
- item += character;
79
- continue;
80
- }
81
- if (character === "}" || (character === "]" && depth > 0)) {
82
- depth -= 1;
83
- item += character;
84
- continue;
85
- }
86
- if (character === "]" && depth === 0) {
87
- const value = flush();
88
- if (value) yield value;
89
- return;
90
- }
91
- if (character === "," && depth === 0) {
92
- const value = flush();
93
- if (value) yield value;
94
- continue;
95
- }
96
- if (item.length > 0 || !/\s/.test(character)) {
97
- item += character;
98
- }
99
- }
100
- }
101
-
102
- if (!started) return;
103
- const value = flush();
104
- if (value) yield value;
105
- }
106
-
107
- export function ingestStreamInBatchesEffect<T>({
108
- batchSize = 250,
109
- onCheckpoint,
110
- processBatch,
111
- resumeAfter = 0,
112
- source,
113
- }: {
114
- batchSize?: number;
115
- onCheckpoint?: (checkpoint: IngestionCheckpoint) => void | Promise<void>;
116
- processBatch: (
117
- batch: T[],
118
- checkpoint: IngestionCheckpoint,
119
- ) => void | Promise<void>;
120
- resumeAfter?: number;
121
- source: () => AsyncIterable<T>;
122
- }): Effect.Effect<IngestionCheckpoint, unknown> {
123
- return Effect.tryPromise({
124
- try: async () => {
125
- const normalizedBatchSize = Math.max(1, Math.trunc(batchSize));
126
- const normalizedResumeAfter = Math.max(0, Math.trunc(resumeAfter));
127
- let visited = 0;
128
- let processed = normalizedResumeAfter;
129
- let batch: T[] = [];
130
-
131
- const flush = async () => {
132
- if (batch.length === 0) return;
133
- processed += batch.length;
134
- const checkpoint = { processed };
135
- await processBatch(batch, checkpoint);
136
- await onCheckpoint?.(checkpoint);
137
- batch = [];
138
- };
139
-
140
- for await (const item of source()) {
141
- visited += 1;
142
- if (visited <= normalizedResumeAfter) continue;
143
- batch.push(item);
144
- if (batch.length >= normalizedBatchSize) {
145
- await flush();
146
- }
147
- }
148
- await flush();
149
- return { processed };
150
- },
151
- catch: (error) =>
152
- error instanceof Error ? error : new Error(String(error)),
153
- });
154
- }
155
-
156
- export function ingestSourcesInBatchesEffect<T>({
157
- batchSize,
158
- onCheckpoint,
159
- onSourceComplete,
160
- processBatch,
161
- sources,
162
- }: {
163
- batchSize?: number;
164
- onCheckpoint?: (
165
- checkpoint: IngestionSourceCheckpoint,
166
- ) => void | Promise<void>;
167
- onSourceComplete?: (
168
- checkpoint: IngestionSourceCheckpoint,
169
- ) => void | Promise<void>;
170
- processBatch: (
171
- batch: T[],
172
- checkpoint: IngestionSourceCheckpoint,
173
- ) => void | Promise<void>;
174
- sources: IngestionSource<T>[];
175
- }): Effect.Effect<IngestionCheckpoint, unknown> {
176
- return Effect.gen(function* () {
177
- let processed = 0;
178
-
179
- for (const [sourceIndex, source] of sources.entries()) {
180
- const sourceResult = yield* ingestStreamInBatchesEffect({
181
- batchSize,
182
- source: source.stream,
183
- processBatch: (batch, checkpoint) =>
184
- processBatch(batch, {
185
- ...checkpoint,
186
- processed: processed + checkpoint.processed,
187
- sourceId: source.id,
188
- sourceIndex,
189
- sourceProcessed: checkpoint.processed,
190
- sources: sources.length,
191
- }),
192
- onCheckpoint: onCheckpoint
193
- ? (checkpoint) =>
194
- onCheckpoint({
195
- ...checkpoint,
196
- processed: processed + checkpoint.processed,
197
- sourceId: source.id,
198
- sourceIndex,
199
- sourceProcessed: checkpoint.processed,
200
- sources: sources.length,
201
- })
202
- : undefined,
203
- });
204
- processed += sourceResult.processed;
205
- yield* Effect.tryPromise({
206
- try: () =>
207
- Promise.resolve(
208
- onSourceComplete?.({
209
- processed,
210
- sourceId: source.id,
211
- sourceIndex,
212
- sourceProcessed: sourceResult.processed,
213
- sources: sources.length,
214
- }),
215
- ),
216
- catch: (error) =>
217
- error instanceof Error ? error : new Error(String(error)),
218
- });
219
- }
220
-
221
- return { processed };
222
- });
223
- }
224
-
225
- export function collectIngestionSourcesEffect<T>(
226
- sources: IngestionSource<T>[],
227
- options: { batchSize?: number } = {},
228
- ): Effect.Effect<T[], unknown> {
229
- return Effect.gen(function* () {
230
- const rows: T[] = [];
231
- yield* ingestSourcesInBatchesEffect({
232
- ...options,
233
- sources,
234
- processBatch: (batch) => {
235
- rows.push(...batch);
236
- },
237
- });
238
- return rows;
239
- });
240
- }
@@ -1,70 +0,0 @@
1
- import { getNativeDb } from "./db";
2
- import {
3
- defaultServerRuntimeServices,
4
- type ServerRuntimeServices,
5
- } from "./server-runtime-services";
6
-
7
- export interface SyncCacheEntry<T> {
8
- value: T;
9
- updatedAt: string;
10
- }
11
-
12
- function readSyncCacheRow(cacheKey: string, db = getNativeDb()) {
13
- return db
14
- .prepare(
15
- `
16
- select value_json, updated_at
17
- from sync_cache
18
- where cache_key = ?
19
- `,
20
- )
21
- .get(cacheKey) as
22
- | {
23
- value_json: string;
24
- updated_at: string;
25
- }
26
- | undefined;
27
- }
28
-
29
- export function readSyncCache<T>(
30
- cacheKey: string,
31
- db = getNativeDb(),
32
- ): SyncCacheEntry<T> | null {
33
- const row = readSyncCacheRow(cacheKey, db);
34
- if (!row) {
35
- return null;
36
- }
37
-
38
- try {
39
- return {
40
- value: JSON.parse(row.value_json) as T,
41
- updatedAt: row.updated_at,
42
- };
43
- } catch {
44
- return null;
45
- }
46
- }
47
-
48
- export function writeSyncCache(
49
- cacheKey: string,
50
- value: unknown,
51
- db = getNativeDb(),
52
- runtime: ServerRuntimeServices = defaultServerRuntimeServices,
53
- ) {
54
- const updatedAt = runtime.now().toISOString();
55
- db.prepare(
56
- `
57
- insert into sync_cache (cache_key, value_json, updated_at)
58
- values (?, ?, ?)
59
- on conflict(cache_key) do update set
60
- value_json = excluded.value_json,
61
- updated_at = excluded.updated_at
62
- `,
63
- ).run(cacheKey, JSON.stringify(value), updatedAt);
64
-
65
- return updatedAt;
66
- }
67
-
68
- export function deleteSyncCache(cacheKey: string, db = getNativeDb()) {
69
- db.prepare("delete from sync_cache where cache_key = ?").run(cacheKey);
70
- }
@@ -1,175 +0,0 @@
1
- import { Effect } from "effect";
2
-
3
- export type PaginationStopReason =
4
- | "boundary"
5
- | "exhausted"
6
- | "item-limit"
7
- | "page-limit"
8
- | "repeated-cursor";
9
-
10
- export interface PaginationPageContext<Page> {
11
- cursor?: string;
12
- fetched: number;
13
- page: Page;
14
- pageIndex: number;
15
- pageNumber: number;
16
- stopReason?: PaginationStopReason;
17
- done: boolean;
18
- }
19
-
20
- export type SyncPlanStopReason = PaginationStopReason | "error";
21
-
22
- export interface SyncPlanPageContext<Page> extends Omit<
23
- PaginationPageContext<Page>,
24
- "stopReason"
25
- > {
26
- nextCursor?: string;
27
- stopReason?: SyncPlanStopReason;
28
- }
29
-
30
- export interface SyncPlanResult<Page, ErrorType> {
31
- complete: boolean;
32
- fetched: number;
33
- nextCursor?: string;
34
- pages: Page[];
35
- stopReason: SyncPlanStopReason;
36
- error?: ErrorType;
37
- }
38
-
39
- function normalizeCursor(value: string | null | undefined) {
40
- const normalized = value?.trim();
41
- return normalized || undefined;
42
- }
43
-
44
- export function runSyncPlanEffect<Page, FetchError, PageError = never>({
45
- fetchPage,
46
- getItemCount,
47
- getNextCursor,
48
- initialCursor,
49
- maxItems,
50
- maxPages,
51
- onPage,
52
- pageDelayMs,
53
- persistPage,
54
- shouldStop,
55
- allowPartialFailure = false,
56
- }: {
57
- fetchPage: (context: {
58
- cursor?: string;
59
- fetched: number;
60
- pageIndex: number;
61
- }) => Effect.Effect<Page, FetchError>;
62
- getItemCount?: (page: Page) => number;
63
- getNextCursor: (page: Page) => string | null | undefined;
64
- initialCursor?: string;
65
- maxItems?: number;
66
- maxPages?: number;
67
- onPage?: (context: SyncPlanPageContext<Page>) => void;
68
- pageDelayMs?: number;
69
- persistPage?: (
70
- context: SyncPlanPageContext<Page>,
71
- ) => Effect.Effect<void, PageError>;
72
- shouldStop?: (
73
- context: Omit<SyncPlanPageContext<Page>, "done" | "nextCursor">,
74
- ) => boolean;
75
- allowPartialFailure?: boolean;
76
- }): Effect.Effect<SyncPlanResult<Page, FetchError>, FetchError | PageError> {
77
- return Effect.gen(function* () {
78
- const pages: Page[] = [];
79
- const seenCursors = new Set<string>();
80
- let cursor = normalizeCursor(initialCursor);
81
- let fetched = 0;
82
- const pageLimit =
83
- maxPages === undefined ? Number.POSITIVE_INFINITY : Math.max(1, maxPages);
84
- const itemLimit =
85
- maxItems === undefined ? Number.POSITIVE_INFINITY : Math.max(1, maxItems);
86
-
87
- if (cursor) seenCursors.add(cursor);
88
-
89
- while (pages.length < pageLimit) {
90
- const pageIndex = pages.length;
91
- const outcome = yield* fetchPage({ cursor, fetched, pageIndex }).pipe(
92
- Effect.map((page) => ({ ok: true as const, page })),
93
- Effect.catchAll((error) =>
94
- Effect.succeed({ ok: false as const, error }),
95
- ),
96
- );
97
- if (!outcome.ok) {
98
- if (!allowPartialFailure || pages.length === 0) {
99
- return yield* Effect.fail(outcome.error);
100
- }
101
- return {
102
- complete: false,
103
- fetched,
104
- ...(cursor ? { nextCursor: cursor } : {}),
105
- pages,
106
- stopReason: "error",
107
- error: outcome.error,
108
- };
109
- }
110
-
111
- const page = outcome.page;
112
- pages.push(page);
113
- fetched += Math.max(0, getItemCount?.(page) ?? 0);
114
- const nextCursor = normalizeCursor(getNextCursor(page));
115
- const baseContext = {
116
- cursor,
117
- fetched,
118
- page,
119
- pageIndex,
120
- pageNumber: pageIndex + 1,
121
- };
122
- let stopReason: PaginationStopReason | undefined;
123
-
124
- if (!nextCursor) {
125
- stopReason = "exhausted";
126
- } else if (shouldStop?.(baseContext)) {
127
- stopReason = "boundary";
128
- } else if (fetched >= itemLimit) {
129
- stopReason = "item-limit";
130
- } else if (pages.length >= pageLimit) {
131
- stopReason = "page-limit";
132
- } else if (seenCursors.has(nextCursor)) {
133
- stopReason = "repeated-cursor";
134
- }
135
-
136
- const context: SyncPlanPageContext<Page> = {
137
- ...baseContext,
138
- ...(nextCursor ? { nextCursor } : {}),
139
- done: Boolean(stopReason),
140
- ...(stopReason ? { stopReason } : {}),
141
- };
142
- if (persistPage) {
143
- yield* persistPage(context);
144
- }
145
- onPage?.(context);
146
-
147
- if (stopReason) {
148
- return {
149
- complete:
150
- stopReason === "exhausted" ||
151
- stopReason === "boundary" ||
152
- stopReason === "item-limit",
153
- fetched,
154
- ...(nextCursor ? { nextCursor } : {}),
155
- pages,
156
- stopReason,
157
- };
158
- }
159
-
160
- cursor = nextCursor;
161
- seenCursors.add(nextCursor!);
162
- if (typeof pageDelayMs === "number" && pageDelayMs > 0) {
163
- yield* Effect.sleep(pageDelayMs);
164
- }
165
- }
166
-
167
- return {
168
- complete: false,
169
- fetched,
170
- ...(cursor ? { nextCursor: cursor } : {}),
171
- pages,
172
- stopReason: "page-limit",
173
- };
174
- });
175
- }