apibara 2.0.0-beta.9 → 2.1.0-beta.10

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 (90) hide show
  1. package/dist/chunks/add.mjs +49 -0
  2. package/dist/chunks/build.mjs +3 -3
  3. package/dist/chunks/dev.mjs +41 -19
  4. package/dist/chunks/init.mjs +37 -0
  5. package/dist/chunks/prepare.mjs +0 -2
  6. package/dist/chunks/start.mjs +56 -0
  7. package/dist/cli/index.mjs +5 -1
  8. package/dist/config/index.d.mts +1 -1
  9. package/dist/config/index.d.ts +1 -1
  10. package/dist/core/index.mjs +127 -134
  11. package/dist/create/index.d.mts +18 -0
  12. package/dist/create/index.d.ts +18 -0
  13. package/dist/create/index.mjs +1025 -0
  14. package/dist/rolldown/index.d.mts +7 -0
  15. package/dist/rolldown/index.d.ts +7 -0
  16. package/dist/rolldown/index.mjs +90 -0
  17. package/dist/runtime/dev.d.ts +3 -0
  18. package/dist/runtime/dev.mjs +58 -0
  19. package/dist/runtime/index.d.ts +2 -0
  20. package/dist/runtime/index.mjs +2 -0
  21. package/dist/runtime/internal/app.d.ts +2 -0
  22. package/dist/runtime/internal/app.mjs +64 -0
  23. package/dist/runtime/internal/logger.d.ts +14 -0
  24. package/dist/runtime/internal/logger.mjs +45 -0
  25. package/dist/runtime/start.d.ts +3 -0
  26. package/dist/runtime/start.mjs +46 -0
  27. package/dist/types/index.d.mts +35 -29
  28. package/dist/types/index.d.ts +35 -29
  29. package/package.json +40 -22
  30. package/runtime-meta.d.ts +2 -0
  31. package/runtime-meta.mjs +7 -0
  32. package/src/cli/commands/add.ts +50 -0
  33. package/src/cli/commands/build.ts +5 -3
  34. package/src/cli/commands/dev.ts +50 -19
  35. package/src/cli/commands/init.ts +36 -0
  36. package/src/cli/commands/prepare.ts +0 -2
  37. package/src/cli/commands/start.ts +61 -0
  38. package/src/cli/index.ts +3 -0
  39. package/src/config/index.ts +5 -4
  40. package/src/core/apibara.ts +4 -2
  41. package/src/core/build/build.ts +15 -5
  42. package/src/core/build/dev.ts +44 -22
  43. package/src/core/build/error.ts +9 -15
  44. package/src/core/build/prepare.ts +5 -2
  45. package/src/core/build/prod.ts +24 -15
  46. package/src/core/build/types.ts +12 -95
  47. package/src/core/config/defaults.ts +4 -4
  48. package/src/core/config/loader.ts +1 -0
  49. package/src/core/config/resolvers/runtime-config.resolver.ts +1 -1
  50. package/src/core/config/update.ts +3 -4
  51. package/src/core/path.ts +11 -0
  52. package/src/core/scan.ts +40 -0
  53. package/src/create/add.ts +239 -0
  54. package/src/create/colors.ts +15 -0
  55. package/src/create/constants.ts +97 -0
  56. package/src/create/index.ts +2 -0
  57. package/src/create/init.ts +178 -0
  58. package/src/create/templates.ts +501 -0
  59. package/src/create/types.ts +34 -0
  60. package/src/create/utils.ts +422 -0
  61. package/src/rolldown/config.ts +83 -0
  62. package/src/rolldown/index.ts +2 -0
  63. package/src/rolldown/plugins/config.ts +13 -0
  64. package/src/rolldown/plugins/indexers.ts +17 -0
  65. package/src/runtime/dev.ts +67 -0
  66. package/src/runtime/index.ts +2 -0
  67. package/src/runtime/internal/app.ts +86 -0
  68. package/src/runtime/internal/logger.ts +70 -0
  69. package/src/runtime/start.ts +53 -0
  70. package/src/types/apibara.ts +8 -0
  71. package/src/types/config.ts +37 -31
  72. package/src/types/hooks.ts +8 -4
  73. package/src/types/index.ts +1 -1
  74. package/src/types/rolldown.ts +5 -0
  75. package/src/types/virtual/config.d.ts +3 -0
  76. package/src/types/virtual/indexers.d.ts +13 -0
  77. package/dist/internal/citty/index.d.mts +0 -1
  78. package/dist/internal/citty/index.d.ts +0 -1
  79. package/dist/internal/citty/index.mjs +0 -1
  80. package/dist/internal/consola/index.d.mts +0 -2
  81. package/dist/internal/consola/index.d.ts +0 -2
  82. package/dist/internal/consola/index.mjs +0 -1
  83. package/dist/rollup/index.d.mts +0 -5
  84. package/dist/rollup/index.d.ts +0 -5
  85. package/dist/rollup/index.mjs +0 -187
  86. package/src/internal/citty/index.ts +0 -1
  87. package/src/internal/consola/index.ts +0 -1
  88. package/src/rollup/config.ts +0 -209
  89. package/src/rollup/index.ts +0 -1
  90. package/src/types/rollup.ts +0 -8
@@ -0,0 +1,422 @@
1
+ import fs from "node:fs";
2
+ import path, { basename } from "node:path";
3
+ import * as prettier from "prettier";
4
+ import prompts from "prompts";
5
+ import { blue, cyan, red, yellow } from "./colors";
6
+ import { dnaUrls, networks } from "./constants";
7
+ import type { Chain, Language, Network, PkgInfo } from "./types";
8
+
9
+ export function isEmpty(path: string) {
10
+ const files = fs.readdirSync(path);
11
+ return files.length === 0 || (files.length === 1 && files[0] === ".git");
12
+ }
13
+ export function emptyDir(dir: string) {
14
+ if (!fs.existsSync(dir)) {
15
+ return;
16
+ }
17
+ for (const file of fs.readdirSync(dir)) {
18
+ if (file === ".git") {
19
+ continue;
20
+ }
21
+ fs.rmSync(path.resolve(dir, file), { recursive: true, force: true });
22
+ }
23
+ }
24
+
25
+ export function validateLanguage(language?: string, throwError = false) {
26
+ if (!language) {
27
+ return false;
28
+ }
29
+
30
+ if (
31
+ language === "typescript" ||
32
+ language === "ts" ||
33
+ language === "javascript" ||
34
+ language === "js"
35
+ ) {
36
+ return true;
37
+ }
38
+
39
+ if (throwError) {
40
+ throw new Error(
41
+ `Invalid language ${cyan("(--language | -l)")}: ${red(language)}. Options: ${blue("typescript, ts")} or ${yellow("javascript, js")} | default: ${cyan("typescript")}`,
42
+ );
43
+ }
44
+
45
+ return false;
46
+ }
47
+
48
+ export function getLanguageFromAlias(alias: string): Language {
49
+ if (alias === "ts" || alias === "typescript") {
50
+ return "typescript";
51
+ }
52
+ if (alias === "js" || alias === "javascript") {
53
+ return "javascript";
54
+ }
55
+
56
+ throw new Error(
57
+ `Invalid language ${cyan("(--language | -l)")}: ${red(alias)}. Options: ${blue("typescript, ts")} or ${yellow("javascript, js")}`,
58
+ );
59
+ }
60
+
61
+ export function validateIndexerId(indexerId?: string, throwError = false) {
62
+ if (!indexerId) {
63
+ return false;
64
+ }
65
+ if (!/^[a-z0-9-]+$/.test(indexerId)) {
66
+ if (throwError) {
67
+ throw new Error(
68
+ `Invalid indexer ID ${cyan("(--indexer-id)")}: ${red(indexerId)}. Indexer ID must contain only lowercase letters, numbers, and hyphens.`,
69
+ );
70
+ }
71
+ return false;
72
+ }
73
+ return true;
74
+ }
75
+
76
+ export function validateChain(chain?: string, throwError = false) {
77
+ if (!chain) {
78
+ return false;
79
+ }
80
+ if (chain) {
81
+ if (chain === "starknet" || chain === "ethereum" || chain === "beaconchain")
82
+ return true;
83
+ if (throwError) {
84
+ throw new Error(
85
+ `Invalid chain ${cyan("(--chain)")}: ${red(chain)}. Chain must be one of ${blue("starknet, ethereum, beaconchain")}.`,
86
+ );
87
+ }
88
+ return false;
89
+ }
90
+ return true;
91
+ }
92
+
93
+ export function validateNetwork(
94
+ chain?: string,
95
+ network?: string,
96
+ throwError = false,
97
+ ) {
98
+ if (!network) {
99
+ return false;
100
+ }
101
+
102
+ if (network === "other") {
103
+ return true;
104
+ }
105
+
106
+ if (chain) {
107
+ if (chain === "starknet") {
108
+ if (network === "mainnet" || network === "sepolia") {
109
+ return true;
110
+ }
111
+ if (throwError) {
112
+ throw new Error(
113
+ `Invalid network ${cyan("(--network)")}: ${red(network)}. For chain ${blue("starknet")}, network must be one of ${blue("mainnet, sepolia, other")}.`,
114
+ );
115
+ }
116
+ return false;
117
+ }
118
+ if (chain === "ethereum") {
119
+ if (network === "mainnet" || network === "goerli") {
120
+ return true;
121
+ }
122
+ if (throwError) {
123
+ throw new Error(
124
+ `Invalid network ${cyan("(--network)")}: ${red(network)}. For chain ${blue("ethereum")}, network must be one of ${blue("mainnet, goerli, other")}.`,
125
+ );
126
+ }
127
+ return false;
128
+ }
129
+ if (chain === "beaconchain") {
130
+ if (network === "mainnet") {
131
+ return true;
132
+ }
133
+ if (throwError) {
134
+ throw new Error(
135
+ `Invalid network ${cyan("(--network)")}: ${red(network)}. For chain ${blue("beaconchain")}, network must be ${blue("mainnet, other")}.`,
136
+ );
137
+ }
138
+ return false;
139
+ }
140
+ }
141
+
142
+ if (networks.find((n) => n.name === network)) {
143
+ return true;
144
+ }
145
+
146
+ if (throwError) {
147
+ throw new Error(
148
+ `Invalid network ${cyan("(--network)")}: ${red(network)}. Network must be one of ${blue("mainnet, sepolia, goerli, other")}.`,
149
+ );
150
+ }
151
+ return false;
152
+ }
153
+
154
+ export function validateStorage(storage?: string, throwError = false) {
155
+ if (!storage) {
156
+ return false;
157
+ }
158
+ if (storage === "postgres" || storage === "none") {
159
+ return true;
160
+ }
161
+ if (throwError) {
162
+ throw new Error(
163
+ `Invalid storage ${cyan("(--storage)")}: ${red(storage)}. Storage must be one of ${blue("postgres, none")}.`,
164
+ );
165
+ }
166
+ return false;
167
+ }
168
+
169
+ export function validateDnaUrl(dnaUrl?: string, throwError = false) {
170
+ if (!dnaUrl) {
171
+ return false;
172
+ }
173
+ if (!dnaUrl.startsWith("https://") && !dnaUrl.startsWith("http://")) {
174
+ if (throwError) {
175
+ throw new Error(
176
+ `Invalid DNA URL ${cyan("(--dna-url)")}: ${red(dnaUrl)}. DNA URL must start with ${blue("https:// or http://")}.`,
177
+ );
178
+ }
179
+ return false;
180
+ }
181
+ return true;
182
+ }
183
+
184
+ export function hasApibaraConfig(cwd: string): boolean {
185
+ const configPathJS = path.join(cwd, "apibara.config.js");
186
+ const configPathTS = path.join(cwd, "apibara.config.ts");
187
+
188
+ return fs.existsSync(configPathJS) || fs.existsSync(configPathTS);
189
+ }
190
+
191
+ export function getApibaraConfigLanguage(cwd: string): Language {
192
+ const configPathJS = path.join(cwd, "apibara.config.js");
193
+ const configPathTS = path.join(cwd, "apibara.config.ts");
194
+
195
+ if (fs.existsSync(configPathJS)) {
196
+ return "javascript";
197
+ }
198
+ if (fs.existsSync(configPathTS)) {
199
+ return "typescript";
200
+ }
201
+
202
+ throw new Error(red("✖") + " No apibara.config found");
203
+ }
204
+
205
+ export function getDnaUrl(chain: Chain, network: Network) {
206
+ if (chain === "ethereum") {
207
+ if (network === "mainnet") {
208
+ return dnaUrls.ethereum;
209
+ }
210
+ if (network === "sepolia") {
211
+ return dnaUrls.ethereumSepolia;
212
+ }
213
+ }
214
+
215
+ if (chain === "beaconchain") {
216
+ if (network === "mainnet") {
217
+ return dnaUrls.beaconchain;
218
+ }
219
+ }
220
+
221
+ if (chain === "starknet") {
222
+ if (network === "mainnet") {
223
+ return dnaUrls.starknet;
224
+ }
225
+ if (network === "sepolia") {
226
+ return dnaUrls.starknetSepolia;
227
+ }
228
+ }
229
+
230
+ throw new Error(red("✖") + " Invalid chain or network");
231
+ }
232
+
233
+ /**
234
+ * Converts a kebab-case string to camelCase.
235
+ *
236
+ * Examples:
237
+ * - "hello-world" → "helloWorld"
238
+ * - "my-long-variable-name" → "myLongVariableName"
239
+ * - "MY-CAPS" → "myCaps"
240
+ * - "-leading-dash" → "leadingDash"
241
+ * - "trailing-dash-" → "trailingDash"
242
+ * - "double--dash" → "doubleDash"
243
+ * - "hello---world" → "helloWorld"
244
+ * - "mixed_dash-and_underscore" → "mixedDashAndUnderscore"
245
+ *
246
+ * @param str The kebab-case string to convert
247
+ * @returns The camelCase version of the string
248
+ */
249
+ export function convertKebabToCamelCase(_str: string): string {
250
+ let str = _str;
251
+
252
+ // Handle empty or invalid input
253
+ if (!str || typeof str !== "string") {
254
+ return "";
255
+ }
256
+
257
+ // Check if already camelCase
258
+ if (/^[a-z][a-zA-Z0-9]*$/.test(str)) {
259
+ return str;
260
+ }
261
+
262
+ // Trim leading/trailing dashes and spaces
263
+ str = str.trim().replace(/^-+|-+$/g, "");
264
+
265
+ // Handle empty string after trim
266
+ if (!str) {
267
+ return "";
268
+ }
269
+
270
+ return (
271
+ str
272
+ // Replace multiple consecutive dashes/underscores with a single dash
273
+ .replace(/[-_]+/g, "-")
274
+ // Split on dash
275
+ .split("-")
276
+ // Filter out empty strings (from consecutive dashes)
277
+ .filter(Boolean)
278
+ // Convert each word
279
+ .map((word, index) => {
280
+ // Convert word to lowercase
281
+ const _word = word.toLowerCase();
282
+
283
+ // Capitalize first letter if not the first word
284
+ if (index > 0) {
285
+ return _word.charAt(0).toUpperCase() + _word.slice(1);
286
+ }
287
+
288
+ return _word;
289
+ })
290
+ .join("")
291
+ );
292
+ }
293
+
294
+ export async function checkFileExists(
295
+ path: string,
296
+ options?: {
297
+ askPrompt?: boolean;
298
+ fileName?: string;
299
+ allowIgnore?: boolean;
300
+ },
301
+ ): Promise<{
302
+ exists: boolean;
303
+ overwrite: boolean;
304
+ }> {
305
+ const { askPrompt = false, fileName, allowIgnore = false } = options ?? {};
306
+
307
+ if (!fs.existsSync(path)) {
308
+ return {
309
+ exists: false,
310
+ overwrite: false,
311
+ };
312
+ }
313
+
314
+ if (askPrompt) {
315
+ const { overwrite } = await prompts({
316
+ type: "select",
317
+ name: "overwrite",
318
+ message: `${fileName ?? basename(path)} already exists. Please choose how to proceed:`,
319
+ initial: 0,
320
+ choices: [
321
+ ...(allowIgnore
322
+ ? [
323
+ {
324
+ title: "Keep original file",
325
+ value: "ignore",
326
+ },
327
+ ]
328
+ : []),
329
+ {
330
+ title: "Cancel operation",
331
+ value: "no",
332
+ },
333
+ {
334
+ title: "Overwrite file",
335
+ value: "yes",
336
+ },
337
+ ],
338
+ });
339
+
340
+ if (overwrite === "no") {
341
+ cancelOperation();
342
+ }
343
+
344
+ if (overwrite === "ignore") {
345
+ return {
346
+ exists: true,
347
+ overwrite: false,
348
+ };
349
+ }
350
+
351
+ return {
352
+ exists: true,
353
+ overwrite: true,
354
+ };
355
+ }
356
+
357
+ return {
358
+ exists: true,
359
+ overwrite: false,
360
+ };
361
+ }
362
+
363
+ export function cancelOperation(message?: string) {
364
+ throw new Error(red("✖") + (message ?? " Operation cancelled"));
365
+ }
366
+
367
+ export function getPackageManager(): PkgInfo {
368
+ const userAgent = process.env.npm_config_user_agent;
369
+ const pkgInfo = pkgFromUserAgent(userAgent);
370
+ if (pkgInfo) {
371
+ return pkgInfo;
372
+ }
373
+ return {
374
+ name: "npm",
375
+ };
376
+ }
377
+
378
+ /**
379
+
380
+ https://github.com/vitejs/vite/blob/07091a1e804e5934208ef0b6324a04317dd0d815/packages/create-vite/src/index.ts#L585
381
+
382
+ MIT License
383
+
384
+ Copyright (c) 2019-present, VoidZero Inc. and Vite contributors
385
+
386
+ Permission is hereby granted, free of charge, to any person obtaining a copy
387
+ of this software and associated documentation files (the "Software"), to deal
388
+ in the Software without restriction, including without limitation the rights
389
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
390
+ copies of the Software, and to permit persons to whom the Software is
391
+ furnished to do so, subject to the following conditions:
392
+
393
+ The above copyright notice and this permission notice shall be included in all
394
+ copies or substantial portions of the Software.
395
+
396
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
397
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
398
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
399
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
400
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
401
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
402
+ SOFTWARE.
403
+
404
+ */
405
+ function pkgFromUserAgent(userAgent: string | undefined): PkgInfo | undefined {
406
+ if (!userAgent) return undefined;
407
+ const pkgSpec = userAgent.split(" ")[0];
408
+ const pkgSpecArr = pkgSpec.split("/");
409
+ return {
410
+ name: pkgSpecArr[0],
411
+ version: pkgSpecArr[1],
412
+ };
413
+ }
414
+
415
+ export async function formatFile(path: string) {
416
+ const file = fs.readFileSync(path, "utf8");
417
+ const formatted = await prettier.format(file, {
418
+ filepath: path,
419
+ tabWidth: 2,
420
+ });
421
+ fs.writeFileSync(path, formatted);
422
+ }
@@ -0,0 +1,83 @@
1
+ import { existsSync } from "node:fs";
2
+ import { builtinModules } from "node:module";
3
+ import type { Apibara } from "apibara/types";
4
+ import defu from "defu";
5
+ import { join } from "pathe";
6
+ import type {
7
+ ConfigExport,
8
+ RolldownOptions,
9
+ RolldownPluginOption,
10
+ } from "rolldown";
11
+ import { appConfig } from "./plugins/config";
12
+ import { indexers } from "./plugins/indexers";
13
+
14
+ const runtimeDependencies = [
15
+ "better-sqlite3",
16
+ "@electric-sql/pglite",
17
+ "pg",
18
+ // https://socket.io/docs/v4/server-installation/#additional-packages
19
+ "utf-8-validate",
20
+ "bufferutil",
21
+ "node-fetch",
22
+ ];
23
+
24
+ export function getRolldownConfig(apibara: Apibara): RolldownOptions {
25
+ const extensions: string[] = [
26
+ ".ts",
27
+ ".mjs",
28
+ ".js",
29
+ ".json",
30
+ ".node",
31
+ ".tsx",
32
+ ".jsx",
33
+ ];
34
+
35
+ const tsConfigExists = existsSync(
36
+ join(apibara.options.rootDir, "tsconfig.json"),
37
+ );
38
+
39
+ const rolldownConfig: RolldownOptions & {
40
+ plugins: RolldownPluginOption[];
41
+ } = defu(
42
+ // biome-ignore lint/suspicious/noExplicitAny: apibara.options.rolldownConfig is typed
43
+ apibara.options.rolldownConfig as any,
44
+ <ConfigExport>{
45
+ platform: "node",
46
+ input: apibara.options.entry,
47
+ output: {
48
+ dir: join(apibara.options.outputDir || "./.apibara/build"),
49
+ format: "esm",
50
+ entryFileNames: "[name].mjs",
51
+ chunkFileNames: "chunks/[name]-[hash].mjs",
52
+ sourcemap: true,
53
+ },
54
+ plugins: [],
55
+ onwarn(warning, rolldownWarn) {
56
+ if (
57
+ !["CIRCULAR_DEPENDENCY", "EVAL", "THIS_IS_UNDEFINED"].includes(
58
+ warning.code || "",
59
+ ) &&
60
+ !warning.message.includes("Unsupported source map comment") &&
61
+ !warning.message.includes("@__PURE__") &&
62
+ !warning.message.includes("/*#__PURE__*/")
63
+ ) {
64
+ rolldownWarn(warning);
65
+ }
66
+ },
67
+ resolve: {
68
+ extensions,
69
+ preferBuiltins: !!apibara.options.node,
70
+ mainFields: ["main"],
71
+ exportConditions: apibara.options.exportConditions,
72
+ tsconfigFilename: tsConfigExists ? "tsconfig.json" : undefined,
73
+ },
74
+ treeshake: true,
75
+ external: [...builtinModules, ...runtimeDependencies],
76
+ },
77
+ );
78
+
79
+ rolldownConfig.plugins?.push(indexers(apibara));
80
+ rolldownConfig.plugins?.push(appConfig(apibara));
81
+
82
+ return rolldownConfig;
83
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./config";
2
+ export type { Plugin } from "rolldown";
@@ -0,0 +1,13 @@
1
+ import virtual from "@rollup/plugin-virtual";
2
+ import type { Apibara } from "apibara/types";
3
+ import type { RolldownPluginOption } from "rolldown";
4
+
5
+ export function appConfig(apibara: Apibara) {
6
+ return virtual({
7
+ "#apibara-internal-virtual/config": `
8
+ import * as projectConfig from '${apibara.options._c12.configFile}';
9
+
10
+ export const config = projectConfig.default;
11
+ `,
12
+ }) as RolldownPluginOption;
13
+ }
@@ -0,0 +1,17 @@
1
+ import virtual from "@rollup/plugin-virtual";
2
+ import type { Apibara } from "apibara/types";
3
+ import { hash } from "ohash";
4
+ import type { RolldownPluginOption } from "rolldown";
5
+
6
+ export function indexers(apibara: Apibara) {
7
+ const indexers = [...new Set(apibara.indexers)];
8
+ return virtual({
9
+ "#apibara-internal-virtual/indexers": `
10
+ ${indexers.map((i) => `import * as _${hash(i)} from '${i.indexer}';`).join("\n")}
11
+
12
+ export const indexers = [
13
+ ${indexers.map((i) => `{ name: "${i.name}", indexer: _${hash(i)} }`).join(",\n")}
14
+ ];
15
+ `,
16
+ }) as RolldownPluginOption;
17
+ }
@@ -0,0 +1,67 @@
1
+ import { runWithReconnect } from "@apibara/indexer";
2
+ import { createClient } from "@apibara/protocol";
3
+ import { defineCommand, runMain } from "citty";
4
+ import { availableIndexers, createIndexer } from "./internal/app";
5
+
6
+ const startCommand = defineCommand({
7
+ meta: {
8
+ name: "start",
9
+ description: "Start the indexer",
10
+ },
11
+ args: {
12
+ indexers: {
13
+ type: "string",
14
+ description: "Which indexers to run",
15
+ },
16
+ preset: {
17
+ type: "string",
18
+ description: "Preset to use",
19
+ },
20
+ },
21
+ async run({ args }) {
22
+ const { indexers: indexersArgs, preset } = args;
23
+
24
+ let selectedIndexers = availableIndexers;
25
+ if (indexersArgs) {
26
+ selectedIndexers = indexersArgs.split(",");
27
+ }
28
+
29
+ for (const indexer of selectedIndexers) {
30
+ if (!availableIndexers.includes(indexer)) {
31
+ throw new Error(
32
+ `Specified indexer "${indexer}" but it was not defined`,
33
+ );
34
+ }
35
+ }
36
+
37
+ await Promise.all(
38
+ selectedIndexers.map(async (indexer) => {
39
+ const indexerInstance = createIndexer(indexer, preset);
40
+ if (!indexerInstance) {
41
+ return;
42
+ }
43
+
44
+ const client = createClient(
45
+ indexerInstance.streamConfig,
46
+ indexerInstance.options.streamUrl,
47
+ );
48
+
49
+ await runWithReconnect(client, indexerInstance);
50
+ }),
51
+ );
52
+ },
53
+ });
54
+
55
+ export const mainCli = defineCommand({
56
+ meta: {
57
+ name: "indexer-dev-runner",
58
+ description: "Run indexer in dev mode",
59
+ },
60
+ subCommands: {
61
+ start: () => startCommand,
62
+ },
63
+ });
64
+
65
+ runMain(mainCli);
66
+
67
+ export default {};
@@ -0,0 +1,2 @@
1
+ export { createIndexer } from "./internal/app";
2
+ export { createLogger } from "./internal/logger";
@@ -0,0 +1,86 @@
1
+ import { createIndexer as _createIndexer } from "@apibara/indexer";
2
+ import {
3
+ type InternalContext,
4
+ internalContext,
5
+ } from "@apibara/indexer/internal/plugins";
6
+ import {
7
+ type ConsolaReporter,
8
+ inMemoryPersistence,
9
+ logger,
10
+ } from "@apibara/indexer/plugins";
11
+ import consola from "consola";
12
+ import { config } from "#apibara-internal-virtual/config";
13
+ import { indexers } from "#apibara-internal-virtual/indexers";
14
+ import { createLogger } from "./logger";
15
+
16
+ export const availableIndexers = indexers.map((i) => i.name);
17
+
18
+ export function createIndexer(indexerName: string, preset?: string) {
19
+ let runtimeConfig: Record<string, unknown> = { ...config.runtimeConfig };
20
+
21
+ if (preset) {
22
+ if (config.presets === undefined) {
23
+ throw new Error(
24
+ `Specified preset "${preset}" but no presets were defined`,
25
+ );
26
+ }
27
+
28
+ if (config.presets[preset] === undefined) {
29
+ throw new Error(`Specified preset "${preset}" but it was not defined`);
30
+ }
31
+
32
+ const presetValue = config.presets[preset] as {
33
+ runtimeConfig: Record<string, unknown>;
34
+ };
35
+ runtimeConfig = { ...runtimeConfig, ...presetValue.runtimeConfig };
36
+ }
37
+
38
+ const indexerDefinition = indexers.find((i) => i.name === indexerName);
39
+
40
+ if (indexerDefinition === undefined) {
41
+ throw new Error(
42
+ `Specified indexer "${indexerName}" but it was not defined`,
43
+ );
44
+ }
45
+
46
+ const indexerModule = indexerDefinition.indexer?.default;
47
+ if (indexerModule === undefined) {
48
+ consola.warn(
49
+ `Specified indexer "${indexerName}" but it does not export a default. Ignoring.`,
50
+ );
51
+ return;
52
+ }
53
+
54
+ const definition =
55
+ typeof indexerModule === "function"
56
+ ? indexerModule(runtimeConfig)
57
+ : indexerModule;
58
+
59
+ let reporter: ConsolaReporter = createLogger({
60
+ indexer: indexerName,
61
+ preset,
62
+ indexers: availableIndexers,
63
+ });
64
+
65
+ if (config.logger) {
66
+ reporter = config.logger({
67
+ indexer: indexerName,
68
+ preset,
69
+ indexers: availableIndexers,
70
+ });
71
+ }
72
+
73
+ // Put the in-memory persistence plugin first so that it can be overridden by any user-defined
74
+ // persistence plugin.
75
+ definition.plugins = [
76
+ internalContext({
77
+ indexerName,
78
+ availableIndexers,
79
+ } as InternalContext),
80
+ logger({ logger: reporter }),
81
+ inMemoryPersistence(),
82
+ ...(definition.plugins ?? []),
83
+ ];
84
+
85
+ return _createIndexer(definition);
86
+ }