square-sdk-cli 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.
Files changed (3) hide show
  1. package/README.md +119 -0
  2. package/dist/square.js +640 -0
  3. package/package.json +39 -0
package/README.md ADDED
@@ -0,0 +1,119 @@
1
+ # square-sdk-cli
2
+
3
+ A command-line interface for the [Square API](https://developer.squareup.com/),
4
+ built with [Bun](https://bun.com). It exposes **every** Square SDK namespace and
5
+ method dynamically by introspecting the SDK at runtime — no hardcoded API list.
6
+
7
+ ## Install
8
+
9
+ Global install (provides the `square` command on your PATH):
10
+
11
+ ```bash
12
+ npm install -g square-sdk-cli # works with node >= 18
13
+ # or
14
+ bun add -g square-sdk-cli
15
+ ```
16
+
17
+ The published package ships a node-runnable bundle (`dist/square.js`), so a
18
+ runtime install via `npm i -g` does not require Bun.
19
+
20
+ ### From source
21
+
22
+ ```bash
23
+ bun install
24
+ bun run build # produces dist/square.js
25
+ npm install -g . # or: bun link
26
+ ```
27
+
28
+ ## Configure
29
+
30
+ Credentials are stored on your machine at
31
+ `~/.config/square-cli/config.json` (XDG-aware; override with `SQUARE_CLI_CONFIG`).
32
+ Tokens are written with `0600` permissions and masked when read back.
33
+
34
+ ```bash
35
+ square config set sandbox --token <ACCESS_TOKEN> --env sandbox
36
+ square config set prod --token <ACCESS_TOKEN> --env production
37
+ square config use sandbox # set default profile
38
+ square config list
39
+ square config get sandbox # token shown masked
40
+ ```
41
+
42
+ Auth resolution order: `--profile <name>` → `--token` / `SQUARE_ACCESS_TOKEN`
43
+ env → default profile.
44
+
45
+ ## Usage
46
+
47
+ ```
48
+ square <namespace> [<sub-namespace>...] <method> [--json '<body>'] [--field.path value] [flags]
49
+ ```
50
+
51
+ ```bash
52
+ # Discover what's available (no auth needed)
53
+ square --help
54
+ square payments --help
55
+ square terminal actions create --help
56
+
57
+ # Call methods
58
+ square payments list
59
+ square payments create --json '{"sourceId":"...","idempotencyKey":"..."}' --amountMoney.amount 100 --amountMoney.currency USD
60
+ square customers list --stream
61
+ ```
62
+
63
+ ### Request body
64
+
65
+ - `--json '<json>'` — full request body as JSON
66
+ - `--field.path value` — set a field by dotted path (merged over `--json`;
67
+ numeric path segments create arrays; values are JSON-coerced, falling back to string)
68
+
69
+ ### Flags
70
+
71
+ | Flag | Description |
72
+ | --------------- | ------------------------------------------- |
73
+ | `--profile <n>` | use a named profile from config |
74
+ | `--token <t>` | Square API access token |
75
+ | `--env <e>` | `sandbox` or `production` (default sandbox) |
76
+ | `--json '<j>'` | JSON request body |
77
+ | `--json-output` | compact JSON output (no pretty print) |
78
+ | `--stream` | stream pageable results item by item |
79
+ | `--help` | show help |
80
+
81
+ > Per-field help is structural only — the SDK's field schemas live in its
82
+ > `.d.ts` types and aren't available at runtime. Use `--json` for full bodies.
83
+
84
+ ## Develop
85
+
86
+ ```bash
87
+ bun test # full suite (incl. SDK contract guard test)
88
+ bun bin/square.ts <namespace> <method>
89
+ ```
90
+
91
+ ## Supported Square SDK versions
92
+
93
+ Currently built and tested against **`square@44.1.0`** (pinned `^44.1.0` in
94
+ `package.json`).
95
+
96
+ The CLI is **version-agnostic by design**: it reads the SDK's namespace/method
97
+ tree at runtime, so new Square APIs, methods, and fields are picked up
98
+ automatically with a simple `bun update square` — no CLI code change.
99
+
100
+ It relies on the SDK's structural _conventions_, not a specific version number.
101
+ Those conventions have been stable across the modern fluent SDK line
102
+ (**v40 → v44**):
103
+
104
+ - exports `SquareClient`, `SquareEnvironment`, `SquareError`
105
+ - constructs with `new SquareClient({ token, environment })`
106
+ - API namespaces are lazy getters on the client prototype (nested recursively)
107
+ - internal duplicate methods are `__`-prefixed (filtered out)
108
+ - list methods return async-iterable pageable results
109
+
110
+ A major SDK rewrite that changes any of the above is the _only_ case requiring a
111
+ CLI code change. `tests/contract.test.ts` guards these conventions against the
112
+ installed `square` package — if a future bump breaks the contract, those tests
113
+ go red and point at exactly what to fix.
114
+
115
+ | Square release type | CLI action |
116
+ | ------------------------------- | ------------------------------- |
117
+ | New API / method / field (most) | `bun update square` |
118
+ | Patch / minor | nothing |
119
+ | Major structural rewrite (rare) | update introspect/client/output |
package/dist/square.js ADDED
@@ -0,0 +1,640 @@
1
+ #!/usr/bin/env node
2
+ // @bun
3
+
4
+ // src/args.ts
5
+ var STRING_FLAGS = {
6
+ profile: "profile",
7
+ token: "token",
8
+ env: "env",
9
+ json: "json"
10
+ };
11
+ var BOOL_FLAGS = {
12
+ "json-output": "jsonOutput",
13
+ stream: "stream",
14
+ help: "help"
15
+ };
16
+ function parseArgs(argv) {
17
+ const positionals = [];
18
+ const flags = {};
19
+ const fields = [];
20
+ let i = 0;
21
+ while (i < argv.length) {
22
+ const arg = argv[i];
23
+ if (arg.startsWith("--")) {
24
+ const body = arg.slice(2);
25
+ const eqIdx = body.indexOf("=");
26
+ if (eqIdx !== -1) {
27
+ const key2 = body.slice(0, eqIdx);
28
+ const val = body.slice(eqIdx + 1);
29
+ if (handleFlag(key2, val, flags)) {
30
+ i++;
31
+ continue;
32
+ }
33
+ fields.push({ path: key2, value: val });
34
+ i++;
35
+ continue;
36
+ }
37
+ const key = body;
38
+ if (key in BOOL_FLAGS) {
39
+ const flagKey = BOOL_FLAGS[key];
40
+ flags[flagKey] = true;
41
+ i++;
42
+ continue;
43
+ }
44
+ if (key in STRING_FLAGS) {
45
+ const flagKey = STRING_FLAGS[key];
46
+ const nextVal2 = argv[i + 1];
47
+ if (nextVal2 !== undefined && !nextVal2.startsWith("--")) {
48
+ flags[flagKey] = nextVal2;
49
+ i += 2;
50
+ continue;
51
+ }
52
+ flags[flagKey] = true;
53
+ i++;
54
+ continue;
55
+ }
56
+ const nextVal = argv[i + 1];
57
+ if (nextVal !== undefined && !nextVal.startsWith("--")) {
58
+ fields.push({ path: key, value: nextVal });
59
+ i += 2;
60
+ continue;
61
+ }
62
+ fields.push({ path: key, value: "true" });
63
+ i++;
64
+ continue;
65
+ }
66
+ positionals.push(arg);
67
+ i++;
68
+ }
69
+ return { positionals, flags, fields };
70
+ }
71
+ function handleFlag(key, val, flags) {
72
+ if (key in BOOL_FLAGS) {
73
+ const flagKey = BOOL_FLAGS[key];
74
+ flags[flagKey] = true;
75
+ return true;
76
+ }
77
+ if (key in STRING_FLAGS) {
78
+ const flagKey = STRING_FLAGS[key];
79
+ flags[flagKey] = val;
80
+ return true;
81
+ }
82
+ return false;
83
+ }
84
+
85
+ // src/merge.ts
86
+ function coerce(value) {
87
+ try {
88
+ return JSON.parse(value);
89
+ } catch {
90
+ return value;
91
+ }
92
+ }
93
+ function deepSet(obj, path, value) {
94
+ const segments = path.split(".");
95
+ let current = obj;
96
+ for (let i = 0;i < segments.length - 1; i++) {
97
+ const seg = segments[i];
98
+ const nextSeg = segments[i + 1];
99
+ const isNextNumeric = /^\d+$/.test(nextSeg);
100
+ if (current[seg] === undefined || current[seg] === null) {
101
+ current[seg] = isNextNumeric ? [] : {};
102
+ }
103
+ current = current[seg];
104
+ }
105
+ const lastSeg = segments[segments.length - 1];
106
+ current[lastSeg] = value;
107
+ }
108
+ function buildRequest(jsonStr, fields) {
109
+ let base = {};
110
+ if (jsonStr !== undefined) {
111
+ try {
112
+ const parsed = JSON.parse(jsonStr);
113
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {
114
+ base = parsed;
115
+ } else {
116
+ base = parsed;
117
+ }
118
+ } catch (e) {
119
+ const msg = e instanceof Error ? e.message : String(e);
120
+ throw new Error(`Invalid JSON: ${msg}`);
121
+ }
122
+ }
123
+ for (const field of fields) {
124
+ const coerced = coerce(field.value);
125
+ deepSet(base, field.path, coerced);
126
+ }
127
+ return base;
128
+ }
129
+
130
+ // src/config.ts
131
+ import * as fs from "fs";
132
+ import * as path from "path";
133
+ import * as os from "os";
134
+ function getConfigPath() {
135
+ const override = process.env["SQUARE_CLI_CONFIG"];
136
+ if (override)
137
+ return override;
138
+ const xdg = process.env["XDG_CONFIG_HOME"];
139
+ const base = xdg ? xdg : path.join(os.homedir(), ".config");
140
+ return path.join(base, "square-cli", "config.json");
141
+ }
142
+ async function load() {
143
+ const configPath = getConfigPath();
144
+ if (!fs.existsSync(configPath)) {
145
+ return { profiles: {} };
146
+ }
147
+ const raw = fs.readFileSync(configPath, "utf8");
148
+ try {
149
+ const parsed = JSON.parse(raw);
150
+ return parsed;
151
+ } catch (e) {
152
+ const msg = e instanceof Error ? e.message : String(e);
153
+ throw new Error(`Failed to parse config at ${configPath}: ${msg}`);
154
+ }
155
+ }
156
+ async function save(cfg) {
157
+ const configPath = getConfigPath();
158
+ const dir = path.dirname(configPath);
159
+ fs.mkdirSync(dir, { recursive: true });
160
+ const content = JSON.stringify(cfg, null, 2);
161
+ fs.writeFileSync(configPath, content, { mode: 384 });
162
+ }
163
+ async function setProfile(name, partial) {
164
+ const cfg = await load();
165
+ const existing = cfg.profiles[name] ?? { token: "", environment: "sandbox" };
166
+ cfg.profiles[name] = { ...existing, ...partial };
167
+ await save(cfg);
168
+ }
169
+ async function getProfile(name) {
170
+ const cfg = await load();
171
+ return cfg.profiles[name];
172
+ }
173
+ async function listProfiles() {
174
+ const cfg = await load();
175
+ return Object.keys(cfg.profiles);
176
+ }
177
+ async function useProfile(name) {
178
+ const cfg = await load();
179
+ if (!cfg.profiles[name]) {
180
+ throw new Error(`Profile "${name}" does not exist. Use "config set ${name} --token <TOKEN>" to create it.`);
181
+ }
182
+ cfg.defaultProfile = name;
183
+ await save(cfg);
184
+ }
185
+
186
+ // src/auth.ts
187
+ function resolveEnvironment(flags, env) {
188
+ if (flags.env) {
189
+ return flags.env === "production" ? "production" : "sandbox";
190
+ }
191
+ const envVal = env["SQUARE_ENVIRONMENT"];
192
+ if (envVal === "production")
193
+ return "production";
194
+ return "sandbox";
195
+ }
196
+ function resolveAuth(flags, env, config) {
197
+ if (flags.profile !== undefined) {
198
+ const profile = config.profiles[flags.profile];
199
+ if (!profile) {
200
+ throw new Error(`Profile "${flags.profile}" not found. Available profiles: ${Object.keys(config.profiles).join(", ") || "(none)"}`);
201
+ }
202
+ return { token: profile.token, environment: profile.environment };
203
+ }
204
+ const token = flags.token ?? env["SQUARE_ACCESS_TOKEN"];
205
+ if (token) {
206
+ const environment = resolveEnvironment(flags, env);
207
+ return { token, environment };
208
+ }
209
+ if (config.defaultProfile) {
210
+ const profile = config.profiles[config.defaultProfile];
211
+ if (profile) {
212
+ return { token: profile.token, environment: profile.environment };
213
+ }
214
+ }
215
+ throw new Error("No authentication found. Provide --token, set SQUARE_ACCESS_TOKEN, use --profile, or configure a default profile with `square config use <profile>`.");
216
+ }
217
+
218
+ // src/client.ts
219
+ import { SquareClient, SquareEnvironment } from "square";
220
+ function createClient(auth) {
221
+ const environment = auth.environment === "production" ? SquareEnvironment.Production : SquareEnvironment.Sandbox;
222
+ return new SquareClient({
223
+ token: auth.token,
224
+ environment
225
+ });
226
+ }
227
+
228
+ // src/introspect.ts
229
+ var MAX_DEPTH = 6;
230
+ function collectDescriptors(instance) {
231
+ const proto = Object.getPrototypeOf(instance);
232
+ if (!proto || proto === Object.prototype)
233
+ return {};
234
+ return Object.getOwnPropertyDescriptors(proto);
235
+ }
236
+ function shouldSkip(name) {
237
+ return name === "constructor" || name.startsWith("_");
238
+ }
239
+ function buildNode(name, instance, seen, depth) {
240
+ const node = {
241
+ name,
242
+ instance,
243
+ methods: new Map,
244
+ children: new Map
245
+ };
246
+ if (depth >= MAX_DEPTH)
247
+ return node;
248
+ if (seen.has(instance))
249
+ return node;
250
+ seen.add(instance);
251
+ const descriptors = collectDescriptors(instance);
252
+ for (const [propName, descriptor] of Object.entries(descriptors)) {
253
+ if (shouldSkip(propName))
254
+ continue;
255
+ const isGetterOnly = typeof descriptor.get === "function" && typeof descriptor.set === "undefined" && descriptor.value === undefined;
256
+ if (isGetterOnly) {
257
+ try {
258
+ const childInstance = instance[propName];
259
+ if (childInstance && typeof childInstance === "object") {
260
+ const childNode = buildNode(propName, childInstance, seen, depth + 1);
261
+ node.children.set(propName, childNode);
262
+ }
263
+ } catch {}
264
+ } else if (typeof descriptor.value === "function") {
265
+ const rawFn = descriptor.value;
266
+ const capturedInstance = instance;
267
+ const capturedName = propName;
268
+ node.methods.set(propName, {
269
+ name: propName,
270
+ arity: rawFn.length,
271
+ fn: (...args) => capturedInstance[capturedName](...args)
272
+ });
273
+ }
274
+ }
275
+ return node;
276
+ }
277
+ function buildTree(client) {
278
+ const seen = new WeakSet;
279
+ return buildNode("root", client, seen, 0);
280
+ }
281
+ function resolvePath(tree, segments) {
282
+ if (segments.length === 0) {
283
+ const validTokens = [
284
+ ...tree.children.keys(),
285
+ ...tree.methods.keys()
286
+ ];
287
+ return { error: "No path provided. Expected: <namespace> <method>", validTokens };
288
+ }
289
+ let current = tree;
290
+ for (let i = 0;i < segments.length - 1; i++) {
291
+ const seg = segments[i];
292
+ const child = current.children.get(seg);
293
+ if (!child) {
294
+ const validTokens = [...current.children.keys()];
295
+ return {
296
+ error: `Unknown namespace "${seg}". Valid options: ${validTokens.join(", ")}`,
297
+ validTokens
298
+ };
299
+ }
300
+ current = child;
301
+ }
302
+ const methodName = segments[segments.length - 1];
303
+ const method = current.methods.get(methodName);
304
+ if (!method) {
305
+ const validTokens = [
306
+ ...current.methods.keys(),
307
+ ...current.children.keys()
308
+ ];
309
+ return {
310
+ error: `Unknown method "${methodName}" on namespace "${current.name}". Valid: ${validTokens.join(", ")}`,
311
+ validTokens
312
+ };
313
+ }
314
+ return { node: current, method };
315
+ }
316
+
317
+ // src/execute.ts
318
+ function isPage(value) {
319
+ if (value === null || typeof value !== "object")
320
+ return false;
321
+ const v = value;
322
+ return Symbol.asyncIterator in value && typeof v["hasNextPage"] === "function" && "data" in v;
323
+ }
324
+ async function collectPages(firstPage) {
325
+ const results = [];
326
+ let page = firstPage;
327
+ while (true) {
328
+ results.push(...page.data);
329
+ if (!page.hasNextPage())
330
+ break;
331
+ page = await page.getNextPage();
332
+ }
333
+ return results;
334
+ }
335
+ async function* streamPages(firstPage) {
336
+ let page = firstPage;
337
+ while (true) {
338
+ for (const item of page.data) {
339
+ yield item;
340
+ }
341
+ if (!page.hasNextPage())
342
+ break;
343
+ page = await page.getNextPage();
344
+ }
345
+ }
346
+ function execute(method, request, options) {
347
+ if (options.stream) {
348
+ return async function* () {
349
+ const result = await Promise.resolve(method.fn(request));
350
+ if (isPage(result)) {
351
+ yield* streamPages(result);
352
+ } else {
353
+ yield result;
354
+ }
355
+ }();
356
+ }
357
+ return (async () => {
358
+ const result = await Promise.resolve(method.fn(request));
359
+ if (isPage(result)) {
360
+ return collectPages(result);
361
+ }
362
+ return result;
363
+ })();
364
+ }
365
+
366
+ // src/output.ts
367
+ import { SquareError } from "square";
368
+ function bigIntReplacer(_key, value) {
369
+ return typeof value === "bigint" ? value.toString() : value;
370
+ }
371
+ function print(value, options = {}) {
372
+ const write = options.writeFn ?? ((msg) => process.stdout.write(msg + `
373
+ `));
374
+ if (options.raw) {
375
+ write(JSON.stringify(value, bigIntReplacer));
376
+ } else {
377
+ write(JSON.stringify(value, bigIntReplacer, 2));
378
+ }
379
+ }
380
+ function renderError(err, options = {}) {
381
+ const write = options.writeFn ?? ((msg) => process.stderr.write(msg + `
382
+ `));
383
+ if (err instanceof SquareError) {
384
+ write(`Square API Error: HTTP ${err.statusCode}`);
385
+ for (const e of err.errors) {
386
+ const detail = e.detail;
387
+ write(` [${e.category}] ${e.code}${detail ? ": " + detail : ""}`);
388
+ }
389
+ } else if (err instanceof Error) {
390
+ write(`Error: ${err.message}`);
391
+ } else {
392
+ write(`Error: ${String(err)}`);
393
+ }
394
+ return 1;
395
+ }
396
+
397
+ // src/help.ts
398
+ var GLOBAL_FLAGS = `
399
+ Global flags:
400
+ --profile <name> Use a named profile from config
401
+ --token <token> Square API access token
402
+ --env <environment> "sandbox" or "production" (default: sandbox)
403
+ --json <json> JSON body for the request
404
+ --json-output Output as compact JSON (no pretty print)
405
+ --stream Stream pageable results item by item
406
+ --help Show this help message
407
+ `.trim();
408
+ function renderRootHelp(tree) {
409
+ const lines = [];
410
+ lines.push("Square SDK CLI");
411
+ lines.push("");
412
+ lines.push("Usage:");
413
+ lines.push(" square <namespace> <method> [--json <body>] [--field value] [flags]");
414
+ lines.push(" square config <subcommand> [args]");
415
+ lines.push("");
416
+ lines.push("Namespaces:");
417
+ const namespaces = [...tree.children.keys()].sort();
418
+ for (const ns of namespaces) {
419
+ lines.push(` ${ns}`);
420
+ }
421
+ lines.push("");
422
+ lines.push("Built-in commands:");
423
+ lines.push(" config set <profile> --token <tok> --env <env> Create/update a profile");
424
+ lines.push(" config get <profile> Show profile (token masked)");
425
+ lines.push(" config list List all profiles");
426
+ lines.push(" config use <profile> Set default profile");
427
+ lines.push("");
428
+ lines.push(GLOBAL_FLAGS);
429
+ return lines.join(`
430
+ `);
431
+ }
432
+ function renderNamespaceHelp(node) {
433
+ const lines = [];
434
+ lines.push(`Namespace: ${node.name}`);
435
+ lines.push("");
436
+ if (node.children.size > 0) {
437
+ lines.push("Sub-namespaces:");
438
+ for (const [name] of node.children) {
439
+ lines.push(` ${node.name} ${name}`);
440
+ }
441
+ lines.push("");
442
+ }
443
+ if (node.methods.size > 0) {
444
+ lines.push("Methods:");
445
+ for (const [name, method] of node.methods) {
446
+ lines.push(` ${node.name} ${name} (arity: ${method.arity})`);
447
+ }
448
+ lines.push("");
449
+ }
450
+ lines.push(GLOBAL_FLAGS);
451
+ return lines.join(`
452
+ `);
453
+ }
454
+ function renderMethodHelp(namespaceName, methodName, arity) {
455
+ const lines = [];
456
+ lines.push(`Method: ${namespaceName} ${methodName}`);
457
+ lines.push("");
458
+ lines.push("Usage:");
459
+ lines.push(` square ${namespaceName} ${methodName} [options]`);
460
+ lines.push("");
461
+ lines.push("Request options:");
462
+ lines.push(" --json '<json>' Full request body as JSON");
463
+ lines.push(" --<field.path> <value> Set a field in the request by dotted path");
464
+ lines.push(` e.g. --amountMoney.amount 100`);
465
+ lines.push("");
466
+ lines.push(`Note: arity hint = ${arity} (optional params may not be counted)`);
467
+ lines.push(" Always pass a request object (even if empty).");
468
+ lines.push("");
469
+ lines.push(GLOBAL_FLAGS);
470
+ return lines.join(`
471
+ `);
472
+ }
473
+
474
+ // src/cli.ts
475
+ var defaultDeps = {
476
+ createClient
477
+ };
478
+ async function run(argv, deps = defaultDeps, stdoutWrite, stderrWrite) {
479
+ const stdout = stdoutWrite ?? ((msg) => process.stdout.write(msg + `
480
+ `));
481
+ const stderr = stderrWrite ?? ((msg) => process.stderr.write(msg + `
482
+ `));
483
+ const parsed = parseArgs(argv);
484
+ const { positionals, flags, fields } = parsed;
485
+ if (positionals[0] === "config") {
486
+ return runConfigCommand(positionals.slice(1), flags, stdout, stderr);
487
+ }
488
+ if (flags.help) {
489
+ try {
490
+ const dummyClient = deps.createClient({ token: "dummy", environment: "sandbox" });
491
+ const tree2 = buildTree(dummyClient);
492
+ if (positionals.length === 0) {
493
+ stdout(renderRootHelp(tree2));
494
+ return 0;
495
+ }
496
+ if (positionals.length === 1) {
497
+ const nsNode = tree2.children.get(positionals[0]);
498
+ if (nsNode) {
499
+ stdout(renderNamespaceHelp(nsNode));
500
+ return 0;
501
+ }
502
+ } else {
503
+ const resolveResult2 = resolvePath(tree2, positionals);
504
+ if (!("error" in resolveResult2)) {
505
+ stdout(renderMethodHelp(positionals.slice(0, -1).join(" "), resolveResult2.method.name, resolveResult2.method.arity));
506
+ return 0;
507
+ }
508
+ }
509
+ stdout(renderRootHelp(tree2));
510
+ return 0;
511
+ } catch {
512
+ stdout("Square SDK CLI\n\nUse `square --help` for available namespaces.");
513
+ return 0;
514
+ }
515
+ }
516
+ let auth;
517
+ try {
518
+ const config = await load();
519
+ const env = process.env;
520
+ auth = resolveAuth({ profile: flags.profile, token: flags.token, env: flags.env }, env, config);
521
+ } catch (e) {
522
+ const exitCode = renderError(e, { writeFn: stderr });
523
+ return exitCode;
524
+ }
525
+ const client = deps.createClient(auth);
526
+ const tree = buildTree(client);
527
+ if (positionals.length === 1) {
528
+ const nsNode = tree.children.get(positionals[0]);
529
+ if (nsNode) {
530
+ stdout(renderNamespaceHelp(nsNode));
531
+ return 0;
532
+ }
533
+ }
534
+ if (positionals.length < 2) {
535
+ stdout(renderRootHelp(tree));
536
+ return 0;
537
+ }
538
+ const resolveResult = resolvePath(tree, positionals);
539
+ if ("error" in resolveResult) {
540
+ stderr(`Error: ${resolveResult.error}`);
541
+ stderr(`Valid options: ${resolveResult.validTokens.join(", ")}`);
542
+ return 1;
543
+ }
544
+ let request;
545
+ try {
546
+ request = buildRequest(flags.json, fields);
547
+ } catch (e) {
548
+ renderError(e, { writeFn: stderr });
549
+ return 1;
550
+ }
551
+ try {
552
+ const streamMode = flags.stream === true;
553
+ const result = execute(resolveResult.method, request, { stream: streamMode });
554
+ if (streamMode) {
555
+ for await (const item of result) {
556
+ stdout(JSON.stringify(item, bigIntReplacer, 2));
557
+ }
558
+ } else {
559
+ const value = await result;
560
+ print(value, { writeFn: stdout });
561
+ }
562
+ return 0;
563
+ } catch (e) {
564
+ return renderError(e, { writeFn: stderr });
565
+ }
566
+ }
567
+ async function runConfigCommand(args, flags, stdout, stderr) {
568
+ const subcommand = args[0];
569
+ switch (subcommand) {
570
+ case "set": {
571
+ const profileName = args[1];
572
+ if (!profileName) {
573
+ stderr("Usage: square config set <profile> --token <token> [--env <environment>]");
574
+ return 1;
575
+ }
576
+ if (!flags.token) {
577
+ stderr("Error: --token is required for config set");
578
+ return 1;
579
+ }
580
+ const environment = flags.env === "production" ? "production" : "sandbox";
581
+ await setProfile(profileName, { token: flags.token, environment });
582
+ stdout(`Profile "${profileName}" saved.`);
583
+ return 0;
584
+ }
585
+ case "get": {
586
+ const profileName = args[1];
587
+ if (!profileName) {
588
+ stderr("Usage: square config get <profile>");
589
+ return 1;
590
+ }
591
+ const profile = await getProfile(profileName);
592
+ if (!profile) {
593
+ stderr(`Profile "${profileName}" not found.`);
594
+ return 1;
595
+ }
596
+ const maskedToken = maskToken(profile.token);
597
+ stdout(JSON.stringify({ ...profile, token: maskedToken }, null, 2));
598
+ return 0;
599
+ }
600
+ case "list": {
601
+ const names = await listProfiles();
602
+ if (names.length === 0) {
603
+ stdout("No profiles configured.");
604
+ } else {
605
+ stdout("Profiles:");
606
+ for (const name of names) {
607
+ stdout(` ${name}`);
608
+ }
609
+ }
610
+ return 0;
611
+ }
612
+ case "use": {
613
+ const profileName = args[1];
614
+ if (!profileName) {
615
+ stderr("Usage: square config use <profile>");
616
+ return 1;
617
+ }
618
+ try {
619
+ await useProfile(profileName);
620
+ stdout(`Default profile set to "${profileName}".`);
621
+ return 0;
622
+ } catch (e) {
623
+ return renderError(e, { writeFn: stderr });
624
+ }
625
+ }
626
+ default: {
627
+ stderr(`Unknown config subcommand: "${subcommand}". Use set, get, list, or use.`);
628
+ return 1;
629
+ }
630
+ }
631
+ }
632
+ function maskToken(token) {
633
+ if (token.length <= 4)
634
+ return "****";
635
+ return "*".repeat(token.length - 4) + token.slice(-4);
636
+ }
637
+
638
+ // bin/square.ts
639
+ var exitCode = await run(process.argv.slice(2));
640
+ process.exit(exitCode);
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "square-sdk-cli",
3
+ "version": "0.1.0",
4
+ "description": "Command-line interface for the Square API, exposing every SDK namespace and method via runtime introspection.",
5
+ "module": "bin/square.ts",
6
+ "type": "module",
7
+ "license": "MIT",
8
+ "author": "karthikdilliraj",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/karthikdilliraj/square-sdk-cli.git"
12
+ },
13
+ "homepage": "https://github.com/karthikdilliraj/square-sdk-cli#readme",
14
+ "bugs": "https://github.com/karthikdilliraj/square-sdk-cli/issues",
15
+ "bin": {
16
+ "square": "dist/square.js"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=18"
24
+ },
25
+ "scripts": {
26
+ "build": "bun scripts/build.ts",
27
+ "test": "bun test",
28
+ "prepublishOnly": "bun run build && bun test"
29
+ },
30
+ "devDependencies": {
31
+ "@types/bun": "latest"
32
+ },
33
+ "peerDependencies": {
34
+ "typescript": "^5"
35
+ },
36
+ "dependencies": {
37
+ "square": "^44.1.0"
38
+ }
39
+ }