@tanstack/cli 0.0.7 → 0.48.2

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 (83) hide show
  1. package/dist/bin.js +7 -0
  2. package/dist/cli.js +481 -0
  3. package/dist/command-line.js +174 -0
  4. package/dist/dev-watch.js +290 -0
  5. package/dist/file-syncer.js +148 -0
  6. package/dist/index.js +1 -0
  7. package/dist/mcp/api.js +31 -0
  8. package/dist/mcp/tools.js +250 -0
  9. package/dist/mcp/types.js +37 -0
  10. package/dist/mcp.js +121 -0
  11. package/dist/options.js +162 -0
  12. package/dist/types/bin.d.ts +2 -0
  13. package/dist/types/cli.d.ts +16 -0
  14. package/dist/types/command-line.d.ts +10 -0
  15. package/dist/types/dev-watch.d.ts +27 -0
  16. package/dist/types/file-syncer.d.ts +18 -0
  17. package/dist/types/index.d.ts +1 -0
  18. package/dist/types/mcp/api.d.ts +4 -0
  19. package/dist/types/mcp/tools.d.ts +2 -0
  20. package/dist/types/mcp/types.d.ts +217 -0
  21. package/dist/types/mcp.d.ts +6 -0
  22. package/dist/types/options.d.ts +8 -0
  23. package/dist/types/types.d.ts +25 -0
  24. package/dist/types/ui-environment.d.ts +2 -0
  25. package/dist/types/ui-prompts.d.ts +12 -0
  26. package/dist/types/utils.d.ts +8 -0
  27. package/dist/types.js +1 -0
  28. package/dist/ui-environment.js +52 -0
  29. package/dist/ui-prompts.js +244 -0
  30. package/dist/utils.js +30 -0
  31. package/package.json +46 -46
  32. package/src/bin.ts +6 -93
  33. package/src/cli.ts +692 -0
  34. package/src/command-line.ts +236 -0
  35. package/src/dev-watch.ts +430 -0
  36. package/src/file-syncer.ts +205 -0
  37. package/src/index.ts +1 -85
  38. package/src/mcp.ts +190 -0
  39. package/src/options.ts +260 -0
  40. package/src/types.ts +27 -0
  41. package/src/ui-environment.ts +74 -0
  42. package/src/ui-prompts.ts +322 -0
  43. package/src/utils.ts +38 -0
  44. package/tests/command-line.test.ts +304 -0
  45. package/tests/index.test.ts +9 -0
  46. package/tests/mcp.test.ts +225 -0
  47. package/tests/options.test.ts +304 -0
  48. package/tests/setupVitest.ts +6 -0
  49. package/tests/ui-environment.test.ts +97 -0
  50. package/tests/ui-prompts.test.ts +238 -0
  51. package/tsconfig.json +17 -0
  52. package/vitest.config.js +7 -0
  53. package/dist/bin.cjs +0 -761
  54. package/dist/bin.d.cts +0 -1
  55. package/dist/bin.d.mts +0 -1
  56. package/dist/bin.mjs +0 -760
  57. package/dist/index.cjs +0 -36
  58. package/dist/index.d.cts +0 -1172
  59. package/dist/index.d.mts +0 -1172
  60. package/dist/index.mjs +0 -3
  61. package/dist/template-CkAkdP8n.mjs +0 -2545
  62. package/dist/template-Cup47s9h.cjs +0 -2783
  63. package/src/api/fetch.test.ts +0 -114
  64. package/src/api/fetch.ts +0 -249
  65. package/src/cache/index.ts +0 -89
  66. package/src/commands/create.ts +0 -463
  67. package/src/commands/mcp.test.ts +0 -152
  68. package/src/commands/mcp.ts +0 -203
  69. package/src/engine/compile-with-addons.test.ts +0 -302
  70. package/src/engine/compile.test.ts +0 -404
  71. package/src/engine/compile.ts +0 -551
  72. package/src/engine/config-file.test.ts +0 -118
  73. package/src/engine/config-file.ts +0 -61
  74. package/src/engine/custom-addons/integration.ts +0 -323
  75. package/src/engine/custom-addons/shared.test.ts +0 -98
  76. package/src/engine/custom-addons/shared.ts +0 -281
  77. package/src/engine/custom-addons/template.test.ts +0 -288
  78. package/src/engine/custom-addons/template.ts +0 -124
  79. package/src/engine/template.test.ts +0 -256
  80. package/src/engine/template.ts +0 -269
  81. package/src/engine/types.ts +0 -336
  82. package/src/parse-gitignore.d.ts +0 -5
  83. package/src/templates/base.ts +0 -891
package/dist/bin.cjs DELETED
@@ -1,761 +0,0 @@
1
- #!/usr/bin/env node
2
- const require_template = require('./template-Cup47s9h.cjs');
3
- let node_fs = require("node:fs");
4
- let node_path = require("node:path");
5
- let zod = require("zod");
6
- let commander = require("commander");
7
- let _clack_prompts = require("@clack/prompts");
8
- let chalk = require("chalk");
9
- chalk = require_template.__toESM(chalk);
10
- let _modelcontextprotocol_sdk_server_mcp_js = require("@modelcontextprotocol/sdk/server/mcp.js");
11
- let _modelcontextprotocol_sdk_server_stdio_js = require("@modelcontextprotocol/sdk/server/stdio.js");
12
- let _modelcontextprotocol_sdk_server_sse_js = require("@modelcontextprotocol/sdk/server/sse.js");
13
- let express = require("express");
14
- express = require_template.__toESM(express);
15
-
16
- //#region src/commands/create.ts
17
- const PACKAGE_MANAGERS = [
18
- "pnpm",
19
- "npm",
20
- "yarn",
21
- "bun",
22
- "deno"
23
- ];
24
- function detectPackageManager() {
25
- const userAgent = process.env.npm_config_user_agent;
26
- if (userAgent) {
27
- if (userAgent.includes("pnpm")) return "pnpm";
28
- if (userAgent.includes("yarn")) return "yarn";
29
- if (userAgent.includes("bun")) return "bun";
30
- if (userAgent.includes("deno")) return "deno";
31
- }
32
- return "npm";
33
- }
34
- function validateProjectName(name) {
35
- if (!name) return {
36
- valid: false,
37
- error: "Project name is required"
38
- };
39
- if (!/^[a-z0-9-_]+$/.test(name)) return {
40
- valid: false,
41
- error: "Project name can only contain lowercase letters, numbers, hyphens, and underscores"
42
- };
43
- return { valid: true };
44
- }
45
- function groupIntegrationsByCategory(integrations) {
46
- const groups = {};
47
- for (const integration of integrations) {
48
- const category = integration.category ?? "other";
49
- groups[category] ??= [];
50
- groups[category].push(integration);
51
- }
52
- return groups;
53
- }
54
- const CATEGORY_LABELS = {
55
- tanstack: "TanStack",
56
- database: "Database",
57
- orm: "ORM",
58
- auth: "Authentication",
59
- deploy: "Deployment",
60
- tooling: "Tooling",
61
- monitoring: "Monitoring",
62
- api: "API",
63
- i18n: "Internationalization",
64
- cms: "CMS",
65
- other: "Other"
66
- };
67
- const CATEGORY_ORDER = [
68
- "tanstack",
69
- "database",
70
- "orm",
71
- "auth",
72
- "deploy",
73
- "api",
74
- "monitoring",
75
- "tooling",
76
- "i18n",
77
- "cms",
78
- "other"
79
- ];
80
- async function runCreate(projectName, options) {
81
- (0, _clack_prompts.intro)(chalk.default.bgCyan(chalk.default.black(" TanStack Start ")));
82
- const s = (0, _clack_prompts.spinner)();
83
- const integrationsPath = options.integrationsPath;
84
- s.start("Fetching available integrations...");
85
- let manifest;
86
- try {
87
- manifest = await require_template.fetchManifest(integrationsPath);
88
- s.stop("Integrations loaded");
89
- } catch (error$1) {
90
- s.stop("Failed to fetch integrations");
91
- _clack_prompts.log.error("Could not fetch integration manifest. Check your internet connection.");
92
- process.exit(1);
93
- }
94
- let name = projectName;
95
- if (!name && !options.yes) {
96
- const nameInput = await (0, _clack_prompts.text)({
97
- message: "Project name:",
98
- placeholder: "my-tanstack-app",
99
- defaultValue: "my-tanstack-app",
100
- validate: (value) => {
101
- const result = validateProjectName(value);
102
- return result.valid ? void 0 : result.error;
103
- }
104
- });
105
- if ((0, _clack_prompts.isCancel)(nameInput)) {
106
- (0, _clack_prompts.cancel)("Operation cancelled.");
107
- process.exit(0);
108
- }
109
- name = nameInput;
110
- }
111
- name = name ?? "my-tanstack-app";
112
- const { valid, error } = validateProjectName(name);
113
- if (!valid) {
114
- _clack_prompts.log.error(error ?? "Invalid project name");
115
- process.exit(1);
116
- }
117
- const targetDir = options.targetDir ? (0, node_path.resolve)(options.targetDir) : (0, node_path.resolve)(process.cwd(), name);
118
- if ((0, node_fs.existsSync)(targetDir)) {
119
- if (!options.yes) {
120
- const overwrite = await (0, _clack_prompts.confirm)({
121
- message: `Directory ${chalk.default.cyan(name)} already exists. Overwrite?`,
122
- initialValue: false
123
- });
124
- if ((0, _clack_prompts.isCancel)(overwrite) || !overwrite) {
125
- (0, _clack_prompts.cancel)("Operation cancelled.");
126
- process.exit(0);
127
- }
128
- }
129
- }
130
- let packageManager = options.packageManager ?? detectPackageManager();
131
- if (!options.packageManager && !options.yes) {
132
- const pmChoice = await (0, _clack_prompts.select)({
133
- message: "Package manager:",
134
- options: PACKAGE_MANAGERS.map((pm) => ({
135
- value: pm,
136
- label: pm
137
- })),
138
- initialValue: packageManager
139
- });
140
- if ((0, _clack_prompts.isCancel)(pmChoice)) {
141
- (0, _clack_prompts.cancel)("Operation cancelled.");
142
- process.exit(0);
143
- }
144
- packageManager = pmChoice;
145
- }
146
- let tailwind = options.tailwind ?? true;
147
- if (options.tailwind === void 0 && !options.yes) {
148
- const twChoice = await (0, _clack_prompts.confirm)({
149
- message: "Include Tailwind CSS?",
150
- initialValue: true
151
- });
152
- if ((0, _clack_prompts.isCancel)(twChoice)) {
153
- (0, _clack_prompts.cancel)("Operation cancelled.");
154
- process.exit(0);
155
- }
156
- tailwind = twChoice;
157
- }
158
- let selectedIntegrationIds = [];
159
- if (options.integrations) selectedIntegrationIds = options.integrations.split(",").map((s$1) => s$1.trim());
160
- else if (!options.yes) {
161
- const grouped = groupIntegrationsByCategory(manifest.integrations.filter((a) => a.type === "integration" && a.modes.includes("file-router")));
162
- const categoryOptions = CATEGORY_ORDER.filter((cat) => grouped[cat]?.length).map((cat) => ({
163
- value: cat,
164
- label: CATEGORY_LABELS[cat] ?? cat,
165
- hint: `${grouped[cat].length} integrations`
166
- }));
167
- (0, _clack_prompts.note)("Use arrow keys to navigate, space to select/deselect, enter to confirm.", "Integration Selection");
168
- const selectedCategories = await (0, _clack_prompts.multiselect)({
169
- message: "Which categories would you like to explore?",
170
- options: categoryOptions,
171
- required: false
172
- });
173
- if ((0, _clack_prompts.isCancel)(selectedCategories)) {
174
- (0, _clack_prompts.cancel)("Operation cancelled.");
175
- process.exit(0);
176
- }
177
- for (const category of selectedCategories) {
178
- const categoryIntegrations = grouped[category];
179
- if (!categoryIntegrations?.length) continue;
180
- const integrationChoices = await (0, _clack_prompts.multiselect)({
181
- message: `Select ${CATEGORY_LABELS[category]} integrations:`,
182
- options: categoryIntegrations.map((integration) => ({
183
- value: integration.id,
184
- label: integration.name,
185
- hint: integration.description
186
- })),
187
- required: false
188
- });
189
- if ((0, _clack_prompts.isCancel)(integrationChoices)) {
190
- (0, _clack_prompts.cancel)("Operation cancelled.");
191
- process.exit(0);
192
- }
193
- selectedIntegrationIds.push(...integrationChoices);
194
- }
195
- }
196
- const integrationMap = new Map(manifest.integrations.map((a) => [a.id, a]));
197
- const resolvedIds = new Set(selectedIntegrationIds);
198
- for (const id of selectedIntegrationIds) {
199
- const integration = integrationMap.get(id);
200
- if (integration?.dependsOn) for (const dep of integration.dependsOn) resolvedIds.add(dep);
201
- }
202
- if (resolvedIds.size > 0) (0, _clack_prompts.note)(Array.from(resolvedIds).map((id) => {
203
- const integration = integrationMap.get(id);
204
- return ` ${!selectedIntegrationIds.includes(id) && resolvedIds.has(id) ? chalk.default.dim("(auto)") : chalk.default.green("+")} ${integration?.name ?? id}`;
205
- }).join("\n"), "Selected Integrations");
206
- if (!options.yes) {
207
- const proceed = await (0, _clack_prompts.confirm)({
208
- message: "Create project?",
209
- initialValue: true
210
- });
211
- if ((0, _clack_prompts.isCancel)(proceed) || !proceed) {
212
- (0, _clack_prompts.cancel)("Operation cancelled.");
213
- process.exit(0);
214
- }
215
- }
216
- s.start("Preparing project...");
217
- let customTemplate;
218
- if (options.template) try {
219
- customTemplate = await require_template.loadTemplate(options.template);
220
- for (const integrationId of customTemplate.integrations) resolvedIds.add(integrationId);
221
- tailwind = customTemplate.tailwind;
222
- } catch (error$1) {
223
- s.stop("Failed to load template");
224
- _clack_prompts.log.error(error$1 instanceof Error ? error$1.message : "Could not load template from URL.");
225
- process.exit(1);
226
- }
227
- let chosenIntegrations = [];
228
- if (resolvedIds.size > 0) try {
229
- chosenIntegrations = await require_template.fetchIntegrations(Array.from(resolvedIds), integrationsPath);
230
- } catch (error$1) {
231
- s.stop("Failed to fetch integration details");
232
- _clack_prompts.log.error("Could not fetch integration definitions.");
233
- process.exit(1);
234
- }
235
- const compileOptions = {
236
- projectName: name,
237
- framework: customTemplate?.framework ?? "react",
238
- mode: customTemplate?.mode ?? "file-router",
239
- typescript: customTemplate?.typescript ?? true,
240
- tailwind,
241
- packageManager,
242
- chosenIntegrations,
243
- integrationOptions: customTemplate?.integrationOptions ?? {},
244
- customTemplate
245
- };
246
- const output = require_template.compile(compileOptions);
247
- s.stop("Project prepared");
248
- s.start("Writing files...");
249
- (0, node_fs.mkdirSync)(targetDir, { recursive: true });
250
- for (const [filePath, content] of Object.entries(output.files)) {
251
- const fullPath = (0, node_path.resolve)(targetDir, filePath);
252
- (0, node_fs.mkdirSync)((0, node_path.resolve)(fullPath, ".."), { recursive: true });
253
- (0, node_fs.writeFileSync)(fullPath, content, "utf-8");
254
- }
255
- await require_template.writeConfigFile(targetDir, compileOptions);
256
- s.stop("Files written");
257
- if (options.git !== false) {
258
- s.start("Initializing git repository...");
259
- try {
260
- const { execSync } = await import("node:child_process");
261
- execSync("git init", {
262
- cwd: targetDir,
263
- stdio: "ignore"
264
- });
265
- s.stop("Git initialized");
266
- } catch {
267
- s.stop("Git initialization skipped");
268
- }
269
- }
270
- if (options.install !== false) {
271
- s.start(`Installing dependencies with ${packageManager}...`);
272
- const startTime = Date.now();
273
- const interval = setInterval(() => {
274
- const elapsed = Math.floor((Date.now() - startTime) / 1e3);
275
- s.message(`Installing dependencies with ${packageManager}... (${elapsed}s)`);
276
- }, 1e3);
277
- try {
278
- const { execSync } = await import("node:child_process");
279
- execSync(packageManager === "yarn" ? "yarn" : `${packageManager} install`, {
280
- cwd: targetDir,
281
- stdio: "ignore"
282
- });
283
- clearInterval(interval);
284
- const total = Math.floor((Date.now() - startTime) / 1e3);
285
- s.stop(`Dependencies installed (${total}s)`);
286
- } catch {
287
- clearInterval(interval);
288
- s.stop("Dependency installation failed");
289
- _clack_prompts.log.warning(`Run "${packageManager} install" manually to install dependencies.`);
290
- }
291
- }
292
- const relativePath = (0, node_path.resolve)(process.cwd()) === targetDir ? "." : name;
293
- (0, _clack_prompts.outro)(chalk.default.green("Project created successfully!"));
294
- console.log();
295
- console.log("Next steps:");
296
- console.log();
297
- if (relativePath !== ".") console.log(` ${chalk.default.cyan("cd")} ${relativePath}`);
298
- if (options.install === false) console.log(` ${chalk.default.cyan(packageManager)} install`);
299
- console.log(` ${chalk.default.cyan(packageManager)} ${packageManager === "npm" ? "run " : ""}dev`);
300
- console.log();
301
- if (output.envVars.length > 0) {
302
- console.log(chalk.default.yellow("Environment variables needed:"));
303
- console.log();
304
- for (const envVar of output.envVars) console.log(` ${chalk.default.cyan(envVar.name)} - ${envVar.description}`);
305
- console.log();
306
- console.log(` Add these to your ${chalk.default.cyan(".env.local")} file.`);
307
- console.log();
308
- }
309
- for (const warning of output.warnings) _clack_prompts.log.warning(warning);
310
- }
311
-
312
- //#endregion
313
- //#region src/mcp/types.ts
314
- const LibrarySchema = zod.z.object({
315
- id: zod.z.string(),
316
- name: zod.z.string(),
317
- tagline: zod.z.string(),
318
- description: zod.z.string().optional(),
319
- frameworks: zod.z.array(zod.z.string()),
320
- latestVersion: zod.z.string(),
321
- latestBranch: zod.z.string().optional(),
322
- availableVersions: zod.z.array(zod.z.string()),
323
- repo: zod.z.string(),
324
- docsRoot: zod.z.string().optional(),
325
- defaultDocs: zod.z.string().optional(),
326
- docsUrl: zod.z.string().optional(),
327
- githubUrl: zod.z.string().optional()
328
- });
329
- const LibrariesResponseSchema = zod.z.object({
330
- libraries: zod.z.array(LibrarySchema),
331
- groups: zod.z.record(zod.z.array(zod.z.string())),
332
- groupNames: zod.z.record(zod.z.string())
333
- });
334
- const PartnerSchema = zod.z.object({
335
- id: zod.z.string(),
336
- name: zod.z.string(),
337
- tagline: zod.z.string().optional(),
338
- description: zod.z.string(),
339
- category: zod.z.string(),
340
- categoryLabel: zod.z.string(),
341
- libraries: zod.z.array(zod.z.string()),
342
- url: zod.z.string()
343
- });
344
- const PartnersResponseSchema = zod.z.object({
345
- partners: zod.z.array(PartnerSchema),
346
- categories: zod.z.array(zod.z.string()),
347
- categoryLabels: zod.z.record(zod.z.string())
348
- });
349
-
350
- //#endregion
351
- //#region src/mcp/api.ts
352
- const TANSTACK_API_BASE = "https://tanstack.com/api/data";
353
- async function fetchLibraries() {
354
- const response = await fetch(`${TANSTACK_API_BASE}/libraries`);
355
- if (!response.ok) throw new Error(`Failed to fetch libraries: ${response.statusText}`);
356
- const data = await response.json();
357
- return LibrariesResponseSchema.parse(data);
358
- }
359
- async function fetchPartners() {
360
- const response = await fetch(`${TANSTACK_API_BASE}/partners`);
361
- if (!response.ok) throw new Error(`Failed to fetch partners: ${response.statusText}`);
362
- const data = await response.json();
363
- return PartnersResponseSchema.parse(data);
364
- }
365
- async function fetchDocContent(repo, branch, filePath) {
366
- const url = `https://raw.githubusercontent.com/${repo}/${branch}/${filePath}`;
367
- const response = await fetch(url, { headers: { "User-Agent": "tanstack-cli" } });
368
- if (!response.ok) {
369
- if (response.status === 404) return null;
370
- throw new Error(`Failed to fetch doc: ${response.statusText}`);
371
- }
372
- return response.text();
373
- }
374
-
375
- //#endregion
376
- //#region src/mcp/tools.ts
377
- const ALGOLIA_APP_ID = "FQ0DQ6MA3C";
378
- const ALGOLIA_API_KEY = "10c34d6a5c89f6048cf644d601e65172";
379
- const ALGOLIA_INDEX = "tanstack-test";
380
- const GROUP_KEYS = [
381
- "state",
382
- "headlessUI",
383
- "performance",
384
- "tooling"
385
- ];
386
- function jsonResult(data) {
387
- return { content: [{
388
- type: "text",
389
- text: JSON.stringify(data, null, 2)
390
- }] };
391
- }
392
- function errorResult(error) {
393
- return {
394
- content: [{
395
- type: "text",
396
- text: `Error: ${error}`
397
- }],
398
- isError: true
399
- };
400
- }
401
- function registerDocTools(server) {
402
- server.tool("tanstack_list_libraries", "List TanStack libraries with metadata, frameworks, and docs URLs.", { group: zod.z.enum(GROUP_KEYS).optional().describe("Filter libraries by group. Options: state, headlessUI, performance, tooling") }, async ({ group }) => {
403
- try {
404
- const data = await fetchLibraries();
405
- let libraries = data.libraries;
406
- if (group && data.groups[group]) {
407
- const groupIds = data.groups[group];
408
- libraries = libraries.filter((lib) => groupIds.includes(lib.id));
409
- }
410
- return jsonResult({
411
- group: group ? data.groupNames[group] || group : "All Libraries",
412
- count: libraries.length,
413
- libraries: libraries.map((lib) => ({
414
- id: lib.id,
415
- name: lib.name,
416
- tagline: lib.tagline,
417
- description: lib.description,
418
- frameworks: lib.frameworks,
419
- latestVersion: lib.latestVersion,
420
- docsUrl: lib.docsUrl,
421
- githubUrl: lib.githubUrl
422
- }))
423
- });
424
- } catch (error) {
425
- return errorResult(String(error));
426
- }
427
- });
428
- server.tool("tanstack_doc", "Fetch a TanStack documentation page by library and path.", {
429
- library: zod.z.string().describe("Library ID (e.g., query, router, table, form)"),
430
- path: zod.z.string().describe("Documentation path (e.g., framework/react/overview)"),
431
- version: zod.z.string().optional().describe("Version (e.g., v5, v1). Defaults to latest")
432
- }, async ({ library: libraryId, path, version = "latest" }) => {
433
- try {
434
- const library = (await fetchLibraries()).libraries.find((l) => l.id === libraryId);
435
- if (!library) return errorResult(`Library "${libraryId}" not found. Use tanstack_list_libraries to see available libraries.`);
436
- if (version !== "latest" && !library.availableVersions.includes(version)) return errorResult(`Version "${version}" not found for ${library.name}. Available: ${library.availableVersions.join(", ")}`);
437
- const branch = version === "latest" || version === library.latestVersion ? library.latestBranch || "main" : version;
438
- const filePath = `${library.docsRoot || "docs"}/${path}.md`;
439
- const content = await fetchDocContent(library.repo, branch, filePath);
440
- if (!content) return errorResult(`Document not found: ${library.name} / ${path} (version: ${version})`);
441
- const frontmatterMatch = content.match(/^---\n([\s\S]*?)\n---/);
442
- let title = path.split("/").pop() || "Untitled";
443
- let docContent = content;
444
- if (frontmatterMatch && frontmatterMatch[1]) {
445
- const titleMatch = frontmatterMatch[1].match(/title:\s*['"]?([^'"\n]+)['"]?/);
446
- if (titleMatch && titleMatch[1]) title = titleMatch[1];
447
- docContent = content.slice(frontmatterMatch[0].length).trim();
448
- }
449
- return jsonResult({
450
- title,
451
- content: docContent,
452
- url: `https://tanstack.com/${libraryId}/${version}/docs/${path}`,
453
- library: library.name,
454
- version: version === "latest" ? library.latestVersion : version
455
- });
456
- } catch (error) {
457
- return errorResult(String(error));
458
- }
459
- });
460
- server.tool("tanstack_search_docs", "Search TanStack documentation. Returns matching pages with snippets.", {
461
- query: zod.z.string().describe("Search query"),
462
- library: zod.z.string().optional().describe("Filter to specific library (e.g., query, router)"),
463
- framework: zod.z.string().optional().describe("Filter to specific framework (e.g., react, vue, solid)"),
464
- limit: zod.z.number().min(1).max(50).optional().describe("Maximum number of results (default: 10, max: 50)")
465
- }, async ({ query, library, framework, limit = 10 }) => {
466
- try {
467
- const ALL_LIBRARIES = [
468
- "config",
469
- "form",
470
- "optimistic",
471
- "pacer",
472
- "query",
473
- "ranger",
474
- "react-charts",
475
- "router",
476
- "start",
477
- "store",
478
- "table",
479
- "virtual",
480
- "db",
481
- "devtools"
482
- ];
483
- const ALL_FRAMEWORKS = [
484
- "react",
485
- "vue",
486
- "solid",
487
- "svelte",
488
- "angular"
489
- ];
490
- const filterParts = ["version:latest"];
491
- if (library) {
492
- const exclusions = ALL_LIBRARIES.filter((l) => l !== library).map((l) => `NOT library:${l}`).join(" AND ");
493
- if (exclusions) filterParts.push(`(${exclusions})`);
494
- }
495
- if (framework) {
496
- const exclusions = ALL_FRAMEWORKS.filter((f) => f !== framework).map((f) => `NOT framework:${f}`).join(" AND ");
497
- if (exclusions) filterParts.push(`(${exclusions})`);
498
- }
499
- const searchParams = { requests: [{
500
- indexName: ALGOLIA_INDEX,
501
- query,
502
- hitsPerPage: Math.min(limit, 50),
503
- filters: filterParts.join(" AND "),
504
- attributesToRetrieve: [
505
- "hierarchy",
506
- "url",
507
- "content",
508
- "library"
509
- ],
510
- attributesToSnippet: ["content:80"]
511
- }] };
512
- const response = await fetch(`https://${ALGOLIA_APP_ID}-dsn.algolia.net/1/indexes/*/queries`, {
513
- method: "POST",
514
- headers: {
515
- "Content-Type": "application/json",
516
- "X-Algolia-Application-Id": ALGOLIA_APP_ID,
517
- "X-Algolia-API-Key": ALGOLIA_API_KEY
518
- },
519
- body: JSON.stringify(searchParams)
520
- });
521
- if (!response.ok) return errorResult(`Algolia search failed: ${response.statusText}`);
522
- const searchResult = (await response.json()).results[0];
523
- if (!searchResult) return jsonResult({
524
- query,
525
- totalHits: 0,
526
- results: []
527
- });
528
- const results = searchResult.hits.map((hit) => {
529
- const breadcrumb = Object.values(hit.hierarchy).filter((v) => Boolean(v));
530
- return {
531
- title: hit.hierarchy.lvl1 || hit.hierarchy.lvl0 || "Untitled",
532
- url: hit.url,
533
- snippet: hit._snippetResult?.content?.value || hit.content || "",
534
- library: hit.library || "unknown",
535
- breadcrumb
536
- };
537
- });
538
- return jsonResult({
539
- query,
540
- totalHits: searchResult.nbHits || results.length,
541
- results
542
- });
543
- } catch (error) {
544
- return errorResult(String(error));
545
- }
546
- });
547
- server.tool("tanstack_ecosystem", "Ecosystem partner recommendations. Filter by category (database, auth, deployment, monitoring, cms, api, data-grid) or library.", {
548
- category: zod.z.string().optional().describe("Filter by category: database, auth, deployment, monitoring, cms, api, data-grid, code-review, learning"),
549
- library: zod.z.string().optional().describe("Filter by TanStack library (e.g., start, router, query, table)")
550
- }, async ({ category, library }) => {
551
- try {
552
- const data = await fetchPartners();
553
- const categoryAliases = {
554
- db: "database",
555
- postgres: "database",
556
- sql: "database",
557
- login: "auth",
558
- authentication: "auth",
559
- hosting: "deployment",
560
- deploy: "deployment",
561
- serverless: "deployment",
562
- errors: "monitoring",
563
- logging: "monitoring",
564
- content: "cms",
565
- "api-keys": "api",
566
- grid: "data-grid",
567
- review: "code-review",
568
- courses: "learning"
569
- };
570
- let resolvedCategory;
571
- if (category) {
572
- const normalized = category.toLowerCase().trim();
573
- resolvedCategory = categoryAliases[normalized] || normalized;
574
- if (!data.categories.includes(resolvedCategory)) resolvedCategory = void 0;
575
- }
576
- const lib = library?.toLowerCase().trim();
577
- const partners = data.partners.filter((p) => !resolvedCategory || p.category === resolvedCategory).filter((p) => !lib || p.libraries.some((l) => l === lib)).map((p) => ({
578
- id: p.id,
579
- name: p.name,
580
- tagline: p.tagline,
581
- description: p.description,
582
- category: p.category,
583
- categoryLabel: p.categoryLabel,
584
- url: p.url,
585
- libraries: p.libraries
586
- }));
587
- return jsonResult({
588
- query: {
589
- category,
590
- categoryResolved: resolvedCategory,
591
- library
592
- },
593
- count: partners.length,
594
- partners
595
- });
596
- } catch (error) {
597
- return errorResult(String(error));
598
- }
599
- });
600
- }
601
-
602
- //#endregion
603
- //#region src/commands/mcp.ts
604
- function createServer() {
605
- const server = new _modelcontextprotocol_sdk_server_mcp_js.McpServer({
606
- name: "TanStack CLI",
607
- version: "0.0.1"
608
- });
609
- server.tool("listTanStackIntegrations", "List available integrations for creating TanStack applications", {}, async () => {
610
- try {
611
- const integrations = (await require_template.fetchManifest()).integrations.filter((a) => a.modes.includes("file-router")).map((integration) => ({
612
- id: integration.id,
613
- name: integration.name,
614
- description: integration.description,
615
- category: integration.category,
616
- dependsOn: integration.dependsOn,
617
- exclusive: integration.exclusive,
618
- hasOptions: integration.hasOptions
619
- }));
620
- return { content: [{
621
- type: "text",
622
- text: JSON.stringify(integrations, null, 2)
623
- }] };
624
- } catch (error) {
625
- return { content: [{
626
- type: "text",
627
- text: `Error fetching integrations: ${error}`
628
- }] };
629
- }
630
- });
631
- registerDocTools(server);
632
- server.tool("createTanStackApplication", "Create a new TanStack Start application", {
633
- projectName: zod.z.string().describe("The name of the project (will be the directory name)"),
634
- targetDir: zod.z.string().describe("Absolute path where the project should be created"),
635
- integrations: zod.z.array(zod.z.string()).optional().describe("Array of integration IDs to include. Use listTanStackIntegrations to see available options."),
636
- integrationOptions: zod.z.record(zod.z.record(zod.z.unknown())).optional().describe("Configuration for integrations. Format: {\"integrationId\": {\"optionName\": \"value\"}}"),
637
- tailwind: zod.z.boolean().optional().describe("Include Tailwind CSS (default: true)"),
638
- packageManager: zod.z.enum([
639
- "npm",
640
- "pnpm",
641
- "yarn",
642
- "bun",
643
- "deno"
644
- ]).optional().describe("Package manager to use (default: pnpm)")
645
- }, async ({ projectName, targetDir, integrations, integrationOptions, tailwind, packageManager }) => {
646
- try {
647
- const { mkdirSync: mkdirSync$1, writeFileSync: writeFileSync$1 } = await import("node:fs");
648
- const { resolve: resolve$2 } = await import("node:path");
649
- const { execSync } = await import("node:child_process");
650
- let chosenIntegrations = [];
651
- if (integrations?.length) chosenIntegrations = await require_template.fetchIntegrations(integrations);
652
- const output = require_template.compile({
653
- projectName,
654
- framework: "react",
655
- mode: "file-router",
656
- typescript: true,
657
- tailwind: tailwind ?? true,
658
- packageManager: packageManager ?? "pnpm",
659
- chosenIntegrations,
660
- integrationOptions: integrationOptions ?? {}
661
- });
662
- mkdirSync$1(targetDir, { recursive: true });
663
- for (const [filePath, content] of Object.entries(output.files)) {
664
- const fullPath = resolve$2(targetDir, filePath);
665
- mkdirSync$1(resolve$2(fullPath, ".."), { recursive: true });
666
- writeFileSync$1(fullPath, content, "utf-8");
667
- }
668
- try {
669
- execSync("git init", {
670
- cwd: targetDir,
671
- stdio: "ignore"
672
- });
673
- } catch {}
674
- const envVarList = output.envVars.length > 0 ? `\n\nRequired environment variables:\n${output.envVars.map((e) => `- ${e.name}: ${e.description}`).join("\n")}` : "";
675
- const warnings = output.warnings.length > 0 ? `\n\nWarnings:\n${output.warnings.map((w) => `- ${w}`).join("\n")}` : "";
676
- return { content: [{
677
- type: "text",
678
- text: `Project "${projectName}" created successfully at ${targetDir}
679
-
680
- Files created: ${Object.keys(output.files).length}
681
- Integrations included: ${chosenIntegrations.map((a) => a.name).join(", ") || "none"}${envVarList}${warnings}
682
-
683
- Next steps:
684
- 1. cd ${targetDir}
685
- 2. ${packageManager ?? "pnpm"} install
686
- 3. ${packageManager ?? "pnpm"} dev`
687
- }] };
688
- } catch (error) {
689
- return { content: [{
690
- type: "text",
691
- text: `Error creating application: ${error}`
692
- }] };
693
- }
694
- });
695
- return server;
696
- }
697
- async function runMcp(options) {
698
- const server = createServer();
699
- if (options.sse) {
700
- const app = (0, express.default)();
701
- let transport = null;
702
- app.get("/sse", (_req, res) => {
703
- transport = new _modelcontextprotocol_sdk_server_sse_js.SSEServerTransport("/messages", res);
704
- server.connect(transport);
705
- });
706
- app.post("/messages", (req, res) => {
707
- if (transport) transport.handlePostMessage(req, res);
708
- });
709
- const port = parseInt(options.port ?? "8080", 10);
710
- app.listen(port, () => {
711
- console.log(`MCP server running at http://localhost:${port}/sse`);
712
- });
713
- } else {
714
- const transport = new _modelcontextprotocol_sdk_server_stdio_js.StdioServerTransport();
715
- await server.connect(transport);
716
- }
717
- }
718
-
719
- //#endregion
720
- //#region src/bin.ts
721
- const program = new commander.Command();
722
- program.name("tanstack").description("TanStack CLI for scaffolding and tooling").version("0.0.1");
723
- program.command("create").argument("[project-name]", "name of the project").option("--template <template>", "URL to a custom template JSON file").option("--package-manager <pm>", "package manager (npm, pnpm, yarn, bun)").option("--integrations <integrations>", "comma-separated list of integration IDs").option("--no-install", "skip installing dependencies").option("--no-git", "skip initializing git repository").option("--no-tailwind", "skip tailwind CSS").option("-y, --yes", "skip prompts and use defaults").option("--target-dir <path>", "target directory for the project").option("--integrations-path <path>", "local path to integrations directory (for development)").description("Create a new TanStack Start project").action(runCreate);
724
- program.command("mcp").option("--sse", "run in SSE mode (for HTTP transport)").option("--port <port>", "port for SSE server", "8080").description("Start the MCP server for AI agents").action(runMcp);
725
- const integrationCommand = program.command("integration");
726
- integrationCommand.command("init").option("--integrations-path <path>", "local path to integrations directory (for development)").description("Initialize an integration from the current project").action(async (options) => {
727
- try {
728
- await require_template.initIntegration((0, node_path.resolve)(process.cwd()), options.integrationsPath);
729
- } catch (error) {
730
- console.error(error instanceof Error ? error.message : "An error occurred");
731
- process.exit(1);
732
- }
733
- });
734
- integrationCommand.command("compile").option("--integrations-path <path>", "local path to integrations directory (for development)").description("Compile/update the integration from the current project").action(async (options) => {
735
- try {
736
- await require_template.compileIntegration((0, node_path.resolve)(process.cwd()), options.integrationsPath);
737
- } catch (error) {
738
- console.error(error instanceof Error ? error.message : "An error occurred");
739
- process.exit(1);
740
- }
741
- });
742
- const templateCommand = program.command("template");
743
- templateCommand.command("init").description("Initialize a custom template from the current project").action(async () => {
744
- try {
745
- await require_template.initTemplate((0, node_path.resolve)(process.cwd()));
746
- } catch (error) {
747
- console.error(error instanceof Error ? error.message : "An error occurred");
748
- process.exit(1);
749
- }
750
- });
751
- templateCommand.command("compile").description("Compile/update the custom template from the current project").action(async () => {
752
- try {
753
- await require_template.compileTemplate((0, node_path.resolve)(process.cwd()));
754
- } catch (error) {
755
- console.error(error instanceof Error ? error.message : "An error occurred");
756
- process.exit(1);
757
- }
758
- });
759
- program.parse();
760
-
761
- //#endregion