@supatype/cli 0.1.0-alpha.6

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 (200) hide show
  1. package/.turbo/turbo-build.log +4 -0
  2. package/.turbo/turbo-test.log +7 -0
  3. package/.turbo/turbo-typecheck.log +4 -0
  4. package/bin/dev-entry.ts +2 -0
  5. package/bin/supatype.js +5 -0
  6. package/dist/app/framework.d.ts +44 -0
  7. package/dist/app/framework.d.ts.map +1 -0
  8. package/dist/app/framework.js +200 -0
  9. package/dist/app/framework.js.map +1 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.d.ts.map +1 -0
  12. package/dist/cli.js +55 -0
  13. package/dist/cli.js.map +1 -0
  14. package/dist/commands/admin.d.ts +4 -0
  15. package/dist/commands/admin.d.ts.map +1 -0
  16. package/dist/commands/admin.js +270 -0
  17. package/dist/commands/admin.js.map +1 -0
  18. package/dist/commands/app.d.ts +3 -0
  19. package/dist/commands/app.d.ts.map +1 -0
  20. package/dist/commands/app.js +235 -0
  21. package/dist/commands/app.js.map +1 -0
  22. package/dist/commands/cloud.d.ts +3 -0
  23. package/dist/commands/cloud.d.ts.map +1 -0
  24. package/dist/commands/cloud.js +256 -0
  25. package/dist/commands/cloud.js.map +1 -0
  26. package/dist/commands/db.d.ts +8 -0
  27. package/dist/commands/db.d.ts.map +1 -0
  28. package/dist/commands/db.js +123 -0
  29. package/dist/commands/db.js.map +1 -0
  30. package/dist/commands/deploy-types.d.ts +14 -0
  31. package/dist/commands/deploy-types.d.ts.map +1 -0
  32. package/dist/commands/deploy-types.js +38 -0
  33. package/dist/commands/deploy-types.js.map +1 -0
  34. package/dist/commands/deploy.d.ts +14 -0
  35. package/dist/commands/deploy.d.ts.map +1 -0
  36. package/dist/commands/deploy.js +295 -0
  37. package/dist/commands/deploy.js.map +1 -0
  38. package/dist/commands/dev.d.ts +3 -0
  39. package/dist/commands/dev.d.ts.map +1 -0
  40. package/dist/commands/dev.js +428 -0
  41. package/dist/commands/dev.js.map +1 -0
  42. package/dist/commands/diff.d.ts +3 -0
  43. package/dist/commands/diff.d.ts.map +1 -0
  44. package/dist/commands/diff.js +39 -0
  45. package/dist/commands/diff.js.map +1 -0
  46. package/dist/commands/engine.d.ts +9 -0
  47. package/dist/commands/engine.d.ts.map +1 -0
  48. package/dist/commands/engine.js +99 -0
  49. package/dist/commands/engine.js.map +1 -0
  50. package/dist/commands/functions.d.ts +3 -0
  51. package/dist/commands/functions.d.ts.map +1 -0
  52. package/dist/commands/functions.js +762 -0
  53. package/dist/commands/functions.js.map +1 -0
  54. package/dist/commands/generate.d.ts +3 -0
  55. package/dist/commands/generate.d.ts.map +1 -0
  56. package/dist/commands/generate.js +28 -0
  57. package/dist/commands/generate.js.map +1 -0
  58. package/dist/commands/init.d.ts +7 -0
  59. package/dist/commands/init.d.ts.map +1 -0
  60. package/dist/commands/init.js +515 -0
  61. package/dist/commands/init.js.map +1 -0
  62. package/dist/commands/keys.d.ts +4 -0
  63. package/dist/commands/keys.d.ts.map +1 -0
  64. package/dist/commands/keys.js +57 -0
  65. package/dist/commands/keys.js.map +1 -0
  66. package/dist/commands/logs.d.ts +6 -0
  67. package/dist/commands/logs.d.ts.map +1 -0
  68. package/dist/commands/logs.js +52 -0
  69. package/dist/commands/logs.js.map +1 -0
  70. package/dist/commands/migrate.d.ts +3 -0
  71. package/dist/commands/migrate.d.ts.map +1 -0
  72. package/dist/commands/migrate.js +71 -0
  73. package/dist/commands/migrate.js.map +1 -0
  74. package/dist/commands/plugins.d.ts +3 -0
  75. package/dist/commands/plugins.d.ts.map +1 -0
  76. package/dist/commands/plugins.js +431 -0
  77. package/dist/commands/plugins.js.map +1 -0
  78. package/dist/commands/pull.d.ts +3 -0
  79. package/dist/commands/pull.d.ts.map +1 -0
  80. package/dist/commands/pull.js +73 -0
  81. package/dist/commands/pull.js.map +1 -0
  82. package/dist/commands/push.d.ts +3 -0
  83. package/dist/commands/push.d.ts.map +1 -0
  84. package/dist/commands/push.js +87 -0
  85. package/dist/commands/push.js.map +1 -0
  86. package/dist/commands/seed.d.ts +3 -0
  87. package/dist/commands/seed.d.ts.map +1 -0
  88. package/dist/commands/seed.js +22 -0
  89. package/dist/commands/seed.js.map +1 -0
  90. package/dist/commands/self-host.d.ts +3 -0
  91. package/dist/commands/self-host.d.ts.map +1 -0
  92. package/dist/commands/self-host.js +796 -0
  93. package/dist/commands/self-host.js.map +1 -0
  94. package/dist/commands/status.d.ts +6 -0
  95. package/dist/commands/status.d.ts.map +1 -0
  96. package/dist/commands/status.js +69 -0
  97. package/dist/commands/status.js.map +1 -0
  98. package/dist/config.d.ts +106 -0
  99. package/dist/config.d.ts.map +1 -0
  100. package/dist/config.js +66 -0
  101. package/dist/config.js.map +1 -0
  102. package/dist/engine/cache.d.ts +37 -0
  103. package/dist/engine/cache.d.ts.map +1 -0
  104. package/dist/engine/cache.js +121 -0
  105. package/dist/engine/cache.js.map +1 -0
  106. package/dist/engine/download.d.ts +19 -0
  107. package/dist/engine/download.d.ts.map +1 -0
  108. package/dist/engine/download.js +108 -0
  109. package/dist/engine/download.js.map +1 -0
  110. package/dist/engine/platform.d.ts +24 -0
  111. package/dist/engine/platform.d.ts.map +1 -0
  112. package/dist/engine/platform.js +50 -0
  113. package/dist/engine/platform.js.map +1 -0
  114. package/dist/engine/resolve.d.ts +37 -0
  115. package/dist/engine/resolve.d.ts.map +1 -0
  116. package/dist/engine/resolve.js +133 -0
  117. package/dist/engine/resolve.js.map +1 -0
  118. package/dist/engine/update-notify.d.ts +11 -0
  119. package/dist/engine/update-notify.d.ts.map +1 -0
  120. package/dist/engine/update-notify.js +43 -0
  121. package/dist/engine/update-notify.js.map +1 -0
  122. package/dist/engine/verify.d.ts +50 -0
  123. package/dist/engine/verify.d.ts.map +1 -0
  124. package/dist/engine/verify.js +161 -0
  125. package/dist/engine/verify.js.map +1 -0
  126. package/dist/engine-version.d.ts +35 -0
  127. package/dist/engine-version.d.ts.map +1 -0
  128. package/dist/engine-version.js +35 -0
  129. package/dist/engine-version.js.map +1 -0
  130. package/dist/engine.d.ts +34 -0
  131. package/dist/engine.d.ts.map +1 -0
  132. package/dist/engine.js +76 -0
  133. package/dist/engine.js.map +1 -0
  134. package/dist/index.d.ts +12 -0
  135. package/dist/index.d.ts.map +1 -0
  136. package/dist/index.js +10 -0
  137. package/dist/index.js.map +1 -0
  138. package/dist/jwt.d.ts +3 -0
  139. package/dist/jwt.d.ts.map +1 -0
  140. package/dist/jwt.js +13 -0
  141. package/dist/jwt.js.map +1 -0
  142. package/dist/pull-utils.d.ts +16 -0
  143. package/dist/pull-utils.d.ts.map +1 -0
  144. package/dist/pull-utils.js +65 -0
  145. package/dist/pull-utils.js.map +1 -0
  146. package/dist/scripts/postinstall.d.ts +12 -0
  147. package/dist/scripts/postinstall.d.ts.map +1 -0
  148. package/dist/scripts/postinstall.js +31 -0
  149. package/dist/scripts/postinstall.js.map +1 -0
  150. package/dist/tsx-runner.d.ts +18 -0
  151. package/dist/tsx-runner.d.ts.map +1 -0
  152. package/dist/tsx-runner.js +62 -0
  153. package/dist/tsx-runner.js.map +1 -0
  154. package/package.json +36 -0
  155. package/src/app/framework.ts +249 -0
  156. package/src/cli.ts +58 -0
  157. package/src/commands/admin.ts +371 -0
  158. package/src/commands/app.ts +261 -0
  159. package/src/commands/cloud.ts +326 -0
  160. package/src/commands/db.ts +145 -0
  161. package/src/commands/deploy-types.ts +49 -0
  162. package/src/commands/deploy.ts +366 -0
  163. package/src/commands/dev.ts +477 -0
  164. package/src/commands/diff.ts +61 -0
  165. package/src/commands/engine.ts +133 -0
  166. package/src/commands/functions.ts +919 -0
  167. package/src/commands/generate.ts +31 -0
  168. package/src/commands/init.ts +532 -0
  169. package/src/commands/keys.ts +66 -0
  170. package/src/commands/logs.ts +58 -0
  171. package/src/commands/migrate.ts +83 -0
  172. package/src/commands/plugins.ts +508 -0
  173. package/src/commands/pull.ts +96 -0
  174. package/src/commands/push.ts +119 -0
  175. package/src/commands/seed.ts +26 -0
  176. package/src/commands/self-host.ts +932 -0
  177. package/src/commands/status.ts +83 -0
  178. package/src/config.ts +190 -0
  179. package/src/engine/cache.ts +135 -0
  180. package/src/engine/download.ts +143 -0
  181. package/src/engine/platform.ts +66 -0
  182. package/src/engine/resolve.ts +197 -0
  183. package/src/engine/update-notify.ts +50 -0
  184. package/src/engine/verify.ts +206 -0
  185. package/src/engine-version.ts +39 -0
  186. package/src/engine.ts +99 -0
  187. package/src/index.ts +19 -0
  188. package/src/jwt.ts +14 -0
  189. package/src/pull-utils.ts +57 -0
  190. package/src/scripts/postinstall.ts +40 -0
  191. package/src/tsx-runner.ts +79 -0
  192. package/tests/cli-help.test.ts +107 -0
  193. package/tests/config.test.ts +117 -0
  194. package/tests/engine-distribution.test.ts +418 -0
  195. package/tests/init.test.ts +184 -0
  196. package/tests/keys.test.ts +160 -0
  197. package/tests/pull-utils.test.ts +115 -0
  198. package/tests/tsx-runner.test.ts +66 -0
  199. package/tsconfig.json +10 -0
  200. package/tsconfig.tsbuildinfo +1 -0
@@ -0,0 +1,83 @@
1
+ import type { Command } from "commander"
2
+ import { createInterface } from "node:readline"
3
+ import { loadConfig } from "../config.js"
4
+ import { ensureEngine, invokeEngine } from "../engine.js"
5
+
6
+ export function registerMigrate(program: Command): void {
7
+ // migrate — apply all pending migrations
8
+ program
9
+ .command("migrate")
10
+ .description("Apply pending migrations from the migration history")
11
+ .option("--connection <url>", "Database connection URL (overrides config)")
12
+ .action(async (opts: { connection?: string }) => {
13
+ const config = loadConfig()
14
+ const connection = opts.connection ?? config.connection
15
+
16
+ await ensureEngine()
17
+ const result = invokeEngine(["migrate", "--pending", "--connection", connection])
18
+ if (result.exitCode !== 0) {
19
+ console.error(result.stderr || result.stdout)
20
+ process.exit(1)
21
+ }
22
+ console.log(result.stdout || "Migrations applied.")
23
+ })
24
+
25
+ // rollback — undo the last applied migration
26
+ program
27
+ .command("rollback")
28
+ .description("Roll back the last applied migration")
29
+ .option("--connection <url>", "Database connection URL (overrides config)")
30
+ .action(async (opts: { connection?: string }) => {
31
+ const config = loadConfig()
32
+ const connection = opts.connection ?? config.connection
33
+
34
+ await ensureEngine()
35
+ const result = invokeEngine(["rollback", "--connection", connection])
36
+ if (result.exitCode !== 0) {
37
+ console.error(result.stderr || result.stdout)
38
+ process.exit(1)
39
+ }
40
+ console.log(result.stdout || "Rolled back.")
41
+ })
42
+
43
+ // reset — drop all tables and re-apply from scratch
44
+ program
45
+ .command("reset")
46
+ .description(
47
+ "Drop all managed tables and re-apply the schema from scratch (destructive)",
48
+ )
49
+ .option("--yes", "Skip confirmation prompt")
50
+ .option("--connection <url>", "Database connection URL (overrides config)")
51
+ .action(async (opts: { yes?: boolean; connection?: string }) => {
52
+ if (!opts.yes) {
53
+ const confirmed = await confirm(
54
+ "This will DROP all managed tables and re-apply the schema. Proceed? [y/N] ",
55
+ )
56
+ if (!confirmed) {
57
+ console.log("Aborted.")
58
+ return
59
+ }
60
+ }
61
+
62
+ const config = loadConfig()
63
+ const connection = opts.connection ?? config.connection
64
+
65
+ await ensureEngine()
66
+ const result = invokeEngine(["reset", "--connection", connection])
67
+ if (result.exitCode !== 0) {
68
+ console.error(result.stderr || result.stdout)
69
+ process.exit(1)
70
+ }
71
+ console.log(result.stdout || "Reset complete.")
72
+ })
73
+ }
74
+
75
+ async function confirm(prompt: string): Promise<boolean> {
76
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
77
+ return new Promise((resolve) => {
78
+ rl.question(prompt, (answer) => {
79
+ rl.close()
80
+ resolve(answer.toLowerCase() === "y")
81
+ })
82
+ })
83
+ }
@@ -0,0 +1,508 @@
1
+ import type { Command } from "commander"
2
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from "node:fs"
3
+ import { resolve, join } from "node:path"
4
+ import { spawnSync } from "node:child_process"
5
+
6
+ // ─── Registration ────────────────────────────────────────────────────────────
7
+
8
+ export function registerPlugins(program: Command): void {
9
+ const cmd = program
10
+ .command("plugins")
11
+ .description("Manage Supatype plugins (field types, composites, providers, widgets)")
12
+
13
+ cmd
14
+ .command("list")
15
+ .description("Show all installed and active plugins")
16
+ .action(() => {
17
+ listPlugins(process.cwd())
18
+ })
19
+
20
+ cmd
21
+ .command("search <query>")
22
+ .description("Search npm registry for Supatype plugins")
23
+ .action(async (query: string) => {
24
+ await searchPlugins(query)
25
+ })
26
+
27
+ cmd
28
+ .command("add <package>")
29
+ .description("Install a plugin package and register it")
30
+ .action((pkg: string) => {
31
+ addPlugin(process.cwd(), pkg)
32
+ })
33
+
34
+ cmd
35
+ .command("remove <package>")
36
+ .description("Uninstall and deregister a plugin")
37
+ .action((pkg: string) => {
38
+ removePlugin(process.cwd(), pkg)
39
+ })
40
+
41
+ cmd
42
+ .command("create")
43
+ .description("Scaffold a new plugin project")
44
+ .option("--type <type>", "Plugin type: field, composite, provider, or widget", "field")
45
+ .option("--name <name>", "Plugin name")
46
+ .action((opts: { type: string; name?: string }) => {
47
+ createPlugin(process.cwd(), opts)
48
+ })
49
+
50
+ cmd
51
+ .command("validate")
52
+ .description("Validate installed plugins for compatibility and correctness")
53
+ .action(() => {
54
+ validatePlugins(process.cwd())
55
+ })
56
+ }
57
+
58
+ // ─── List ────────────────────────────────────────────────────────────────────
59
+
60
+ function listPlugins(cwd: string): void {
61
+ const plugins = discoverInstalledPlugins(cwd)
62
+
63
+ if (plugins.length === 0) {
64
+ console.log("No Supatype plugins installed.")
65
+ console.log("\nSearch for plugins: npx supatype plugins search <query>")
66
+ console.log("Create a plugin: npx supatype plugins create")
67
+ return
68
+ }
69
+
70
+ console.log("Installed plugins:\n")
71
+ console.log(` ${"Name".padEnd(35)} ${"Type".padEnd(14)} ${"Version".padEnd(12)} Status`)
72
+ console.log(` ${"─".repeat(35)} ${"─".repeat(14)} ${"─".repeat(12)} ${"─".repeat(15)}`)
73
+
74
+ for (const p of plugins) {
75
+ const types = p.supatype?.types?.join(", ") ?? "unknown"
76
+ const status = p.compatible ? "active" : "incompatible"
77
+ console.log(` ${p.name.padEnd(35)} ${types.padEnd(14)} ${p.version.padEnd(12)} ${status}`)
78
+ }
79
+ }
80
+
81
+ // ─── Search ──────────────────────────────────────────────────────────────────
82
+
83
+ async function searchPlugins(query: string): Promise<void> {
84
+ console.log(`Searching npm for "${query}" supatype plugins...\n`)
85
+
86
+ try {
87
+ const searchUrl = `https://registry.npmjs.org/-/v1/search?text=supatype-plugin+${encodeURIComponent(query)}&size=20`
88
+ const res = await fetch(searchUrl, {
89
+ signal: AbortSignal.timeout(10_000),
90
+ })
91
+
92
+ if (!res.ok) {
93
+ console.error(`Search failed: ${res.statusText}`)
94
+ return
95
+ }
96
+
97
+ const data = await res.json() as {
98
+ objects: Array<{
99
+ package: {
100
+ name: string
101
+ version: string
102
+ description: string
103
+ keywords: string[]
104
+ }
105
+ score: { final: number }
106
+ }>
107
+ }
108
+
109
+ if (data.objects.length === 0) {
110
+ console.log("No plugins found.")
111
+ console.log("\nTry a different search term, or create your own plugin:")
112
+ console.log(" npx supatype plugins create")
113
+ return
114
+ }
115
+
116
+ console.log(` ${"Package".padEnd(40)} ${"Version".padEnd(12)} Description`)
117
+ console.log(` ${"─".repeat(40)} ${"─".repeat(12)} ${"─".repeat(40)}`)
118
+
119
+ for (const obj of data.objects) {
120
+ const pkg = obj.package
121
+ const desc = (pkg.description ?? "").slice(0, 50)
122
+ console.log(` ${pkg.name.padEnd(40)} ${pkg.version.padEnd(12)} ${desc}`)
123
+ }
124
+
125
+ console.log(`\nInstall: npx supatype plugins add <package-name>`)
126
+ } catch (err) {
127
+ console.error(`Error: ${err instanceof Error ? err.message : "unknown"}`)
128
+ }
129
+ }
130
+
131
+ // ─── Add ─────────────────────────────────────────────────────────────────────
132
+
133
+ function addPlugin(cwd: string, pkg: string): void {
134
+ console.log(`Installing ${pkg}...`)
135
+
136
+ // Detect package manager
137
+ const pm = detectPackageManager(cwd)
138
+ const installCmd = pm === "pnpm" ? ["pnpm", "add", pkg]
139
+ : pm === "yarn" ? ["yarn", "add", pkg]
140
+ : ["npm", "install", pkg]
141
+
142
+ const result = spawnSync(installCmd[0]!, installCmd.slice(1), {
143
+ stdio: "inherit",
144
+ cwd,
145
+ })
146
+
147
+ if (result.status !== 0) {
148
+ console.error(`Failed to install ${pkg}`)
149
+ process.exit(1)
150
+ }
151
+
152
+ // Check compatibility
153
+ const pluginPkgPath = resolvePackageJson(cwd, pkg)
154
+ if (pluginPkgPath) {
155
+ const pkgJson = JSON.parse(readFileSync(pluginPkgPath, "utf8")) as Record<string, unknown>
156
+ const supatype = pkgJson["supatype"] as Record<string, unknown> | undefined
157
+
158
+ if (supatype?.["pluginApi"] !== undefined) {
159
+ const pluginApi = supatype["pluginApi"] as number
160
+ if (pluginApi !== 1) {
161
+ console.warn(`\nWarning: ${pkg} targets plugin API v${pluginApi}, current is v1.`)
162
+ console.warn("The plugin may not work correctly.")
163
+ }
164
+ }
165
+ }
166
+
167
+ console.log(`\n${pkg} installed and registered.`)
168
+ console.log("Run 'npx supatype plugins list' to see active plugins.")
169
+ }
170
+
171
+ // ─── Remove ──────────────────────────────────────────────────────────────────
172
+
173
+ function removePlugin(cwd: string, pkg: string): void {
174
+ // Check if the plugin is referenced in the schema
175
+ // This is a best-effort check
176
+ const schemaFiles = findSchemaFiles(cwd)
177
+ for (const file of schemaFiles) {
178
+ const content = readFileSync(file, "utf8")
179
+ if (content.includes(pkg)) {
180
+ console.warn(`Warning: ${pkg} appears to be referenced in ${file}`)
181
+ console.warn("Removing it may break your schema. Proceed with caution.\n")
182
+ }
183
+ }
184
+
185
+ console.log(`Removing ${pkg}...`)
186
+
187
+ const pm = detectPackageManager(cwd)
188
+ const removeCmd = pm === "pnpm" ? ["pnpm", "remove", pkg]
189
+ : pm === "yarn" ? ["yarn", "remove", pkg]
190
+ : ["npm", "uninstall", pkg]
191
+
192
+ const result = spawnSync(removeCmd[0]!, removeCmd.slice(1), {
193
+ stdio: "inherit",
194
+ cwd,
195
+ })
196
+
197
+ if (result.status !== 0) {
198
+ console.error(`Failed to remove ${pkg}`)
199
+ process.exit(1)
200
+ }
201
+
202
+ console.log(`${pkg} removed.`)
203
+ }
204
+
205
+ // ─── Create ──────────────────────────────────────────────────────────────────
206
+
207
+ function createPlugin(cwd: string, opts: { type: string; name?: string }): void {
208
+ const validTypes = ["field", "composite", "provider", "widget"]
209
+ if (!validTypes.includes(opts.type)) {
210
+ console.error(`Invalid plugin type "${opts.type}". Must be one of: ${validTypes.join(", ")}`)
211
+ process.exit(1)
212
+ }
213
+
214
+ const name = opts.name ?? `supatype-plugin-my-${opts.type}`
215
+ const pluginDir = resolve(cwd, name)
216
+
217
+ if (existsSync(pluginDir)) {
218
+ console.error(`Directory "${name}" already exists.`)
219
+ process.exit(1)
220
+ }
221
+
222
+ mkdirSync(pluginDir, { recursive: true })
223
+ mkdirSync(join(pluginDir, "src"), { recursive: true })
224
+
225
+ // package.json
226
+ writeFileSync(join(pluginDir, "package.json"), JSON.stringify({
227
+ name,
228
+ version: "0.1.0",
229
+ description: `Supatype ${opts.type} plugin`,
230
+ type: "module",
231
+ main: "./dist/index.js",
232
+ types: "./dist/index.d.ts",
233
+ exports: {
234
+ ".": {
235
+ import: "./dist/index.js",
236
+ types: "./dist/index.d.ts",
237
+ },
238
+ },
239
+ keywords: ["supatype", "supatype-plugin"],
240
+ supatype: {
241
+ pluginApi: 1,
242
+ types: [opts.type],
243
+ },
244
+ scripts: {
245
+ build: "tsc",
246
+ typecheck: "tsc --noEmit",
247
+ },
248
+ dependencies: {
249
+ "@supatype/plugin-sdk": "^0.1.0",
250
+ },
251
+ devDependencies: {
252
+ typescript: "^5",
253
+ },
254
+ }, null, 2) + "\n", "utf8")
255
+
256
+ // tsconfig.json
257
+ writeFileSync(join(pluginDir, "tsconfig.json"), JSON.stringify({
258
+ compilerOptions: {
259
+ target: "ES2022",
260
+ module: "Node16",
261
+ moduleResolution: "Node16",
262
+ outDir: "dist",
263
+ rootDir: "src",
264
+ declaration: true,
265
+ strict: true,
266
+ esModuleInterop: true,
267
+ skipLibCheck: true,
268
+ },
269
+ include: ["src"],
270
+ }, null, 2) + "\n", "utf8")
271
+
272
+ // Source file based on type
273
+ const sourceContent = generatePluginTemplate(opts.type, name)
274
+ writeFileSync(join(pluginDir, "src/index.ts"), sourceContent, "utf8")
275
+
276
+ console.log(`\nCreated plugin project: ${name}/\n`)
277
+ console.log(" Files:")
278
+ console.log(` ${name}/package.json`)
279
+ console.log(` ${name}/tsconfig.json`)
280
+ console.log(` ${name}/src/index.ts`)
281
+ console.log(`\n Next steps:`)
282
+ console.log(` cd ${name}`)
283
+ console.log(` npm install`)
284
+ console.log(` npm run build`)
285
+ console.log(` npx supatype plugins validate`)
286
+ }
287
+
288
+ function generatePluginTemplate(type: string, name: string): string {
289
+ switch (type) {
290
+ case "field":
291
+ return `import { defineFieldType } from "@supatype/plugin-sdk"
292
+
293
+ export default defineFieldType({
294
+ name: "${name.replace(/.*plugin-/, "")}",
295
+ pgType: "TEXT",
296
+ tsType: "string",
297
+
298
+ validate(value) {
299
+ if (typeof value !== "string") return "Must be a string"
300
+ return null
301
+ },
302
+
303
+ serialise(value: string) {
304
+ return value
305
+ },
306
+
307
+ deserialise(raw) {
308
+ return String(raw)
309
+ },
310
+
311
+ filterOperators: ["eq", "neq", "in", "like"],
312
+ // widgetPath: "./src/Widget.tsx",
313
+ })
314
+ `
315
+ case "composite":
316
+ return `import { defineComposite } from "@supatype/plugin-sdk"
317
+
318
+ export default defineComposite({
319
+ name: "${name.replace(/.*plugin-/, "")}",
320
+ label: "${name.replace(/.*plugin-/, "").replace(/-/g, " ").replace(/\b\w/g, l => l.toUpperCase())}",
321
+ fields: [
322
+ { name: "example_field", type: "text", required: false },
323
+ ],
324
+ adminGroup: {
325
+ collapsible: true,
326
+ defaultCollapsed: false,
327
+ },
328
+ })
329
+ `
330
+ case "provider":
331
+ return `import { defineProvider, type EmailProvider } from "@supatype/plugin-sdk"
332
+
333
+ interface MyProviderConfig {
334
+ apiKey: string
335
+ region?: string
336
+ }
337
+
338
+ export default defineProvider<MyProviderConfig>({
339
+ name: "${name.replace(/.*plugin-/, "")}",
340
+ category: "email",
341
+ label: "${name.replace(/.*plugin-/, "").replace(/-/g, " ").replace(/\b\w/g, l => l.toUpperCase())}",
342
+ configSchema: {
343
+ apiKey: { type: "string", label: "API Key", required: true, secret: true },
344
+ region: { type: "select", label: "Region", options: ["us-east-1", "eu-west-1"] },
345
+ },
346
+ create(config): EmailProvider {
347
+ return {
348
+ async send(params) {
349
+ // Implement email sending using config.apiKey
350
+ console.log("Sending email to", params.to)
351
+ return { messageId: "msg_" + Date.now() }
352
+ },
353
+ }
354
+ },
355
+ })
356
+ `
357
+ case "widget":
358
+ return `import { defineWidget } from "@supatype/plugin-sdk"
359
+
360
+ export default defineWidget({
361
+ name: "${name.replace(/.*plugin-/, "")}",
362
+ label: "${name.replace(/.*plugin-/, "").replace(/-/g, " ").replace(/\b\w/g, l => l.toUpperCase())}",
363
+ compatibleTypes: ["text", "varchar"],
364
+ componentPath: "./src/Widget.tsx",
365
+ })
366
+ `
367
+ default:
368
+ return `// Unknown plugin type: ${type}\n`
369
+ }
370
+ }
371
+
372
+ // ─── Validate ────────────────────────────────────────────────────────────────
373
+
374
+ function validatePlugins(cwd: string): void {
375
+ const plugins = discoverInstalledPlugins(cwd)
376
+
377
+ if (plugins.length === 0) {
378
+ console.log("No plugins to validate.")
379
+ return
380
+ }
381
+
382
+ let hasErrors = false
383
+
384
+ for (const p of plugins) {
385
+ const issues: string[] = []
386
+
387
+ if (!p.supatype) {
388
+ issues.push("Missing 'supatype' field in package.json")
389
+ } else {
390
+ if (!p.supatype.pluginApi) {
391
+ issues.push("Missing supatype.pluginApi version")
392
+ } else if (p.supatype.pluginApi !== 1) {
393
+ issues.push(`Targets plugin API v${p.supatype.pluginApi}, current is v1`)
394
+ }
395
+ if (!p.supatype.types || p.supatype.types.length === 0) {
396
+ issues.push("Missing supatype.types array")
397
+ }
398
+ }
399
+
400
+ if (issues.length === 0) {
401
+ console.log(` ✓ ${p.name} — valid`)
402
+ } else {
403
+ hasErrors = true
404
+ console.log(` ✗ ${p.name}`)
405
+ for (const issue of issues) {
406
+ console.log(` - ${issue}`)
407
+ }
408
+ }
409
+ }
410
+
411
+ if (hasErrors) {
412
+ console.log("\nSome plugins have issues. Fix them before deploying.")
413
+ process.exit(1)
414
+ } else {
415
+ console.log("\nAll plugins are valid.")
416
+ }
417
+ }
418
+
419
+ // ─── Helpers ─────────────────────────────────────────────────────────────────
420
+
421
+ interface DiscoveredPlugin {
422
+ name: string
423
+ version: string
424
+ supatype?: {
425
+ pluginApi?: number | undefined
426
+ types?: string[] | undefined
427
+ } | undefined
428
+ compatible: boolean
429
+ }
430
+
431
+ function discoverInstalledPlugins(cwd: string): DiscoveredPlugin[] {
432
+ const nodeModulesDir = resolve(cwd, "node_modules")
433
+ if (!existsSync(nodeModulesDir)) return []
434
+
435
+ const plugins: DiscoveredPlugin[] = []
436
+
437
+ // Read package.json to find dependencies
438
+ const pkgJsonPath = resolve(cwd, "package.json")
439
+ if (!existsSync(pkgJsonPath)) return []
440
+
441
+ const pkgJson = JSON.parse(readFileSync(pkgJsonPath, "utf8")) as Record<string, Record<string, string>>
442
+ const deps = {
443
+ ...pkgJson["dependencies"],
444
+ ...pkgJson["devDependencies"],
445
+ }
446
+
447
+ for (const depName of Object.keys(deps)) {
448
+ const depPkgPath = resolvePackageJson(cwd, depName)
449
+ if (!depPkgPath) continue
450
+
451
+ try {
452
+ const depPkg = JSON.parse(readFileSync(depPkgPath, "utf8")) as Record<string, unknown>
453
+
454
+ // Check if it's a Supatype plugin
455
+ const keywords = (depPkg["keywords"] as string[] | undefined) ?? []
456
+ const supatype = depPkg["supatype"] as Record<string, unknown> | undefined
457
+
458
+ if (keywords.includes("supatype-plugin") || supatype) {
459
+ plugins.push({
460
+ name: depName,
461
+ version: (depPkg["version"] as string) ?? "unknown",
462
+ supatype: supatype ? {
463
+ pluginApi: supatype["pluginApi"] as number | undefined,
464
+ types: supatype["types"] as string[] | undefined,
465
+ } : undefined,
466
+ compatible: !supatype?.["pluginApi"] || supatype["pluginApi"] === 1,
467
+ })
468
+ }
469
+ } catch {
470
+ // Skip packages we can't read
471
+ }
472
+ }
473
+
474
+ return plugins
475
+ }
476
+
477
+ function resolvePackageJson(cwd: string, packageName: string): string | null {
478
+ // Handle scoped packages
479
+ const parts = packageName.startsWith("@") ? packageName.split("/") : [packageName]
480
+ const pkgPath = resolve(cwd, "node_modules", ...parts, "package.json")
481
+ return existsSync(pkgPath) ? pkgPath : null
482
+ }
483
+
484
+ function detectPackageManager(cwd: string): "pnpm" | "yarn" | "npm" {
485
+ if (existsSync(resolve(cwd, "pnpm-lock.yaml"))) return "pnpm"
486
+ if (existsSync(resolve(cwd, "yarn.lock"))) return "yarn"
487
+ return "npm"
488
+ }
489
+
490
+ function findSchemaFiles(cwd: string): string[] {
491
+ const schemaDir = resolve(cwd, "supatype/schema")
492
+ if (!existsSync(schemaDir)) return []
493
+
494
+ const files: string[] = []
495
+ try {
496
+ const { readdirSync, statSync } = require("node:fs") as typeof import("node:fs")
497
+ const entries = readdirSync(schemaDir)
498
+ for (const entry of entries) {
499
+ const fullPath = join(schemaDir, entry)
500
+ if (statSync(fullPath).isFile() && entry.endsWith(".ts")) {
501
+ files.push(fullPath)
502
+ }
503
+ }
504
+ } catch {
505
+ // Ignore errors
506
+ }
507
+ return files
508
+ }
@@ -0,0 +1,96 @@
1
+ import type { Command } from "commander"
2
+ import { mkdirSync, writeFileSync } from "node:fs"
3
+ import { resolve } from "node:path"
4
+ import { loadConfig } from "../config.js"
5
+ import { ensureEngine, invokeEngine } from "../engine.js"
6
+ import { pgTypeToField, toCamelCase, type ColumnInfo } from "../pull-utils.js"
7
+
8
+ interface IntrospectResult {
9
+ models: Array<{
10
+ name: string
11
+ tableName: string
12
+ columns: ColumnInfo[]
13
+ }>
14
+ }
15
+
16
+ export function registerPull(program: Command): void {
17
+ program
18
+ .command("pull")
19
+ .description(
20
+ "Introspect an existing Postgres database and generate TypeScript schema files",
21
+ )
22
+ .option("--connection <url>", "Database connection URL (overrides config)")
23
+ .option("--output <path>", "Output directory for schema files", "./schema")
24
+ .action(async (opts: { connection?: string; output: string }) => {
25
+ const cwd = process.cwd()
26
+ const connection = opts.connection ?? loadConfig(cwd).connection
27
+
28
+ await ensureEngine()
29
+ console.log("Introspecting database...")
30
+ const result = invokeEngine([
31
+ "introspect",
32
+ "--connection",
33
+ connection,
34
+ "--format",
35
+ "json",
36
+ ])
37
+ if (result.exitCode !== 0) {
38
+ console.error(result.stderr || result.stdout)
39
+ process.exit(1)
40
+ }
41
+
42
+ const introspected = JSON.parse(result.stdout) as IntrospectResult
43
+ const models = introspected.models ?? []
44
+
45
+ if (models.length === 0) {
46
+ console.log("No tables found in the database.")
47
+ return
48
+ }
49
+
50
+ const outputDir = resolve(cwd, opts.output)
51
+ mkdirSync(outputDir, { recursive: true })
52
+
53
+ for (const model of models) {
54
+ const content = generateModelFile(model)
55
+ writeFileSync(resolve(outputDir, `${model.name}.ts`), content, "utf8")
56
+ console.log(` wrote ${opts.output}/${model.name}.ts`)
57
+ }
58
+
59
+ const indexContent = generateIndexFile(models.map((m) => m.name))
60
+ writeFileSync(resolve(outputDir, "index.ts"), indexContent, "utf8")
61
+ console.log(` wrote ${opts.output}/index.ts`)
62
+
63
+ console.log(
64
+ `\nPulled ${models.length} model(s). Review TODO comments before running supatype push.\n`,
65
+ )
66
+ })
67
+ }
68
+
69
+ function generateModelFile(model: IntrospectResult["models"][number]): string {
70
+ const fieldLines = model.columns
71
+ .map((col) => ` ${col.name}: ${pgTypeToField(col)},`)
72
+ .join("\n")
73
+
74
+ return `import { model, field, access } from "@supatype/schema"
75
+
76
+ // TODO: review access rules — all operations default to authenticated
77
+ export const ${toCamelCase(model.name)} = model(${JSON.stringify(model.name)}, {
78
+ tableName: ${JSON.stringify(model.tableName)},
79
+ fields: {
80
+ ${fieldLines}
81
+ },
82
+ access: {
83
+ read: access.role("authenticated"),
84
+ create: access.role("authenticated"),
85
+ update: access.role("authenticated"),
86
+ delete: access.role("authenticated"),
87
+ },
88
+ })
89
+ `
90
+ }
91
+
92
+ function generateIndexFile(names: string[]): string {
93
+ return names
94
+ .map((n) => `export { ${toCamelCase(n)} } from "./${n}.js"`)
95
+ .join("\n") + "\n"
96
+ }