@shotik/cli 0.0.0-stage → 0.1.0

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.
package/README.md CHANGED
@@ -1,3 +1,14 @@
1
- # Temporary Holding Version
1
+ # @shotik/cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Set up Shotik in your app with your coding agent. Nothing is hosted: the CLI talks to the Shotik Mac app on 127.0.0.1.
4
+
5
+ ```
6
+ npx -y @shotik/cli setup
7
+ ```
8
+
9
+ - `shotik login` prints a code; approve it in the Shotik app.
10
+ - `shotik setup [path]` detects the project (Expo/React Native, Swift, Flutter), links it, installs the SDK, writes `.shotik/setup.json` and prints the next steps (use `@shotik/mcp` `get_recipe`).
11
+ - `shotik status`, `shotik logout`. Add `--json` for machine output.
12
+
13
+ Exit codes: 0 ok, 1 error, 2 denied or expired, 3 Shotik not running.
14
+ The token is kept in `~/.shotik/auth.json` (mode 0600) and never printed. `SHOTIK_DRY_RUN=1` prints the install command instead of running it.
package/bin/shotik.mjs ADDED
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ import { main } from '../src/cli.mjs'
3
+
4
+ main(process.argv.slice(2)).then(
5
+ (code) => process.exit(code),
6
+ (err) => {
7
+ process.stderr.write(`shotik: ${err.message}\n`)
8
+ process.exit(err.exitCode ?? 1)
9
+ }
10
+ )
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "@shotik/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Set up Shotik in your app with your coding agent",
5
+ "type": "module",
6
+ "bin": {
7
+ "shotik": "bin/shotik.mjs"
8
+ },
9
+ "files": [
10
+ "bin",
11
+ "src",
12
+ "README.md"
13
+ ],
14
+ "engines": {
15
+ "node": ">=18"
16
+ },
17
+ "license": "MIT",
18
+ "scripts": {
19
+ "test": "node --test test/cli.test.mjs"
20
+ }
21
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,243 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { spawnSync } from 'node:child_process'
3
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync, chmodSync } from 'node:fs'
4
+ import { homedir, hostname } from 'node:os'
5
+ import { basename, join, resolve } from 'node:path'
6
+
7
+ const SWIFT_URL = 'https://github.com/rahimwws/shotik-app'
8
+
9
+ class CliError extends Error {
10
+ constructor(message, exitCode = 1) {
11
+ super(message)
12
+ this.exitCode = exitCode
13
+ }
14
+ }
15
+
16
+ const home = () => process.env.SHOTIK_HOME || join(homedir(), '.shotik')
17
+ const readJson = (file) => {
18
+ try {
19
+ return JSON.parse(readFileSync(file, 'utf8'))
20
+ } catch {
21
+ return null
22
+ }
23
+ }
24
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
25
+
26
+ function writePrivate(file, data) {
27
+ mkdirSync(join(file, '..'), { recursive: true })
28
+ writeFileSync(file, JSON.stringify(data, null, 2) + '\n', { mode: 0o600 })
29
+ chmodSync(file, 0o600)
30
+ }
31
+
32
+ function parseArgs(argv) {
33
+ const flags = { json: false }
34
+ const rest = []
35
+ for (const a of argv) {
36
+ if (a === '--json') flags.json = true
37
+ else if (a === '--help' || a === '-h') flags.help = true
38
+ else rest.push(a)
39
+ }
40
+ return { flags, command: rest[0], args: rest.slice(1) }
41
+ }
42
+
43
+ function makeOut(json) {
44
+ return {
45
+ json,
46
+ say: (line = '') => {
47
+ if (!json) process.stdout.write(line + '\n')
48
+ },
49
+ result: (obj) => {
50
+ if (json) process.stdout.write(JSON.stringify(obj) + '\n')
51
+ }
52
+ }
53
+ }
54
+
55
+ function discover() {
56
+ const info = readJson(join(home(), 'local.json'))
57
+ if (!info || !info.port) throw new CliError("Shotik isn't running. Open the Shotik app and try again.", 3)
58
+ try {
59
+ process.kill(info.pid, 0)
60
+ } catch (e) {
61
+ if (e.code !== 'EPERM') throw new CliError("Shotik isn't running. Open the Shotik app and try again.", 3)
62
+ }
63
+ return info
64
+ }
65
+
66
+ async function call(info, method, path, { body, token, headers } = {}) {
67
+ let res
68
+ try {
69
+ res = await fetch(`http://127.0.0.1:${info.port}${path}`, {
70
+ method,
71
+ headers: {
72
+ ...(body ? { 'content-type': 'application/json' } : {}),
73
+ ...(token ? { authorization: `Bearer ${token}` } : {}),
74
+ ...headers
75
+ },
76
+ body: body ? JSON.stringify(body) : undefined
77
+ })
78
+ } catch {
79
+ throw new CliError("Shotik isn't running. Open the Shotik app and try again.", 3)
80
+ }
81
+ const data = await res.json().catch(() => ({}))
82
+ if (!res.ok) {
83
+ const err = new CliError(data.message || `Request failed (${res.status})`)
84
+ err.status = res.status
85
+ throw err
86
+ }
87
+ return data
88
+ }
89
+
90
+ async function login(info, out) {
91
+ const pollSecret = randomBytes(32).toString('base64url')
92
+ const started = await call(info, 'POST', '/v1/cli/login', {
93
+ body: { pollSecret, host: hostname(), cwd: process.cwd(), agent: process.env.SHOTIK_AGENT || undefined }
94
+ })
95
+ out.say(`Code: ${started.code}`)
96
+ out.say('Approve it in the Shotik app.')
97
+ out.result({ event: 'code', code: started.code })
98
+ const every = Number(process.env.SHOTIK_POLL_MS) || 1500
99
+ for (;;) {
100
+ const r = await call(info, 'GET', `/v1/cli/login/${started.id}`, { headers: { 'x-shotik-poll': pollSecret } })
101
+ if (r.status === 'approved') {
102
+ writePrivate(join(home(), 'auth.json'), { token: r.token, expiresAt: r.expiresAt })
103
+ out.say('Approved.')
104
+ return r.token
105
+ }
106
+ if (r.status === 'denied') throw new CliError('Login was denied in the Shotik app.', 2)
107
+ if (r.status === 'expired') throw new CliError('Login request expired. Run the command again.', 2)
108
+ if (r.status === 'gone') throw new CliError('Login request is no longer available. Run the command again.', 2)
109
+ await sleep(every)
110
+ }
111
+ }
112
+
113
+ async function ensureToken(info, out) {
114
+ const saved = readJson(join(home(), 'auth.json'))
115
+ if (saved?.token) {
116
+ try {
117
+ await call(info, 'GET', '/v1/cli/apps', { token: saved.token })
118
+ return saved.token
119
+ } catch (e) {
120
+ if (e.status !== 401 && e.status !== 403) throw e
121
+ }
122
+ }
123
+ return login(info, out)
124
+ }
125
+
126
+ function detect(dir) {
127
+ const pkg = readJson(join(dir, 'package.json'))
128
+ if (pkg) {
129
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies }
130
+ if (deps.expo || deps['react-native']) return { sdk: 'react-native', expo: Boolean(deps.expo), name: pkg.name }
131
+ }
132
+ const entries = readdirSync(dir)
133
+ if (entries.some((e) => e.endsWith('.xcodeproj')) || entries.includes('Package.swift')) return { sdk: 'swift' }
134
+ if (entries.includes('pubspec.yaml')) return { sdk: 'flutter' }
135
+ return null
136
+ }
137
+
138
+ function packageManager(dir) {
139
+ if (existsSync(join(dir, 'bun.lockb')) || existsSync(join(dir, 'bun.lock'))) return 'bun'
140
+ if (existsSync(join(dir, 'pnpm-lock.yaml'))) return 'pnpm'
141
+ if (existsSync(join(dir, 'yarn.lock'))) return 'yarn'
142
+ return 'npm'
143
+ }
144
+
145
+ function installCommand(project, dir) {
146
+ if (project.sdk === 'flutter') return ['flutter', 'pub', 'add', 'shotik']
147
+ if (project.sdk !== 'react-native') return null
148
+ if (project.expo) return ['npx', 'expo', 'install', '@shotik/react-native']
149
+ const pm = packageManager(dir)
150
+ return [pm, pm === 'npm' ? 'install' : 'add', '@shotik/react-native']
151
+ }
152
+
153
+ async function setup(info, target, out) {
154
+ const dir = resolve(target || '.')
155
+ const project = detect(dir)
156
+ if (!project) throw new CliError('No supported project found (expo/react-native, Xcode/Swift package, flutter).')
157
+ const token = await ensureToken(info, out)
158
+ const { apps } = await call(info, 'GET', '/v1/cli/apps', { token })
159
+ const existing = apps.find((a) => a.repoPath === dir)
160
+ const linked = await call(info, 'POST', '/v1/cli/link', {
161
+ token,
162
+ body: {
163
+ ...(existing ? { appId: existing.id } : { name: project.name || basename(dir) }),
164
+ repoPath: dir,
165
+ sdk: project.sdk
166
+ }
167
+ })
168
+ const cmd = installCommand(project, dir)
169
+ let installed = false
170
+ if (cmd) {
171
+ const line = cmd.join(' ')
172
+ if (process.env.SHOTIK_DRY_RUN === '1') {
173
+ out.say(`Dry run, would run: ${line}`)
174
+ } else {
175
+ out.say(`Running: ${line}`)
176
+ const r = spawnSync(cmd[0], cmd.slice(1), { cwd: dir, stdio: out.json ? ['ignore', 'ignore', 'inherit'] : 'inherit' })
177
+ if (r.status !== 0) throw new CliError(`Install failed: ${line}`)
178
+ installed = true
179
+ }
180
+ } else {
181
+ out.say('Add the package in Xcode: File > Add Package Dependencies.')
182
+ out.say(`Package URL: ${SWIFT_URL} (from 0.1.0)`)
183
+ }
184
+ mkdirSync(join(dir, '.shotik'), { recursive: true })
185
+ writeFileSync(
186
+ join(dir, '.shotik', 'setup.json'),
187
+ JSON.stringify({ sdk: project.sdk, appId: linked.app.id, appKey: linked.appKey }, null, 2) + '\n'
188
+ )
189
+ if (installed) await call(info, 'POST', '/v1/cli/event', { token, body: { kind: 'installed', sdk: project.sdk } })
190
+ await call(info, 'POST', '/v1/cli/event', { token, body: { kind: 'test', sdk: project.sdk } })
191
+ out.say()
192
+ out.say('Next: use @shotik/mcp get_recipe for the remaining code edits, with these variables:')
193
+ out.say(`APP_KEY=${linked.appKey}`)
194
+ out.say(`SERVER_URL=${linked.serverUrl}`)
195
+ out.result({ ok: true, sdk: project.sdk, appId: linked.app.id, APP_KEY: linked.appKey, SERVER_URL: linked.serverUrl })
196
+ }
197
+
198
+ export async function main(argv) {
199
+ const { flags, command, args } = parseArgs(argv)
200
+ const out = makeOut(flags.json)
201
+ if (!command || flags.help || !['login', 'setup', 'status', 'logout'].includes(command)) {
202
+ process.stdout.write('Usage: shotik <login|setup [path]|status|logout> [--json]\n')
203
+ return command && !flags.help ? 1 : 0
204
+ }
205
+ try {
206
+ if (command === 'logout') {
207
+ const saved = readJson(join(home(), 'auth.json'))
208
+ if (saved?.token) {
209
+ try {
210
+ await call(discover(), 'POST', '/v1/cli/logout', { token: saved.token })
211
+ } catch {}
212
+ rmSync(join(home(), 'auth.json'), { force: true })
213
+ }
214
+ out.say('Logged out.')
215
+ out.result({ ok: true })
216
+ return 0
217
+ }
218
+ const info = discover()
219
+ if (command === 'login') {
220
+ await login(info, out)
221
+ out.result({ ok: true })
222
+ } else if (command === 'status') {
223
+ const saved = readJson(join(home(), 'auth.json'))
224
+ let loggedIn = false
225
+ if (saved?.token) {
226
+ try {
227
+ await call(info, 'GET', '/v1/cli/apps', { token: saved.token })
228
+ loggedIn = true
229
+ } catch {}
230
+ }
231
+ out.say(`Shotik is running on port ${info.port}. ${loggedIn ? 'Logged in.' : 'Not logged in.'}`)
232
+ out.result({ running: true, port: info.port, loggedIn })
233
+ } else {
234
+ await setup(info, args[0], out)
235
+ }
236
+ return 0
237
+ } catch (e) {
238
+ if (!(e instanceof CliError)) throw e
239
+ if (flags.json) process.stdout.write(JSON.stringify({ ok: false, error: e.message, exitCode: e.exitCode }) + '\n')
240
+ else process.stderr.write(`shotik: ${e.message}\n`)
241
+ return e.exitCode
242
+ }
243
+ }