square-sdk-cli 0.1.2 → 0.2.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/CHANGELOG.md ADDED
@@ -0,0 +1,89 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. The format follows
4
+ [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
+ [Semantic Versioning](https://semver.org/) (pre-1.0: minor versions may break).
6
+
7
+ ## [0.2.0] - 2026-10-12
8
+
9
+ ### ⚠️ Behavior changes (check scripts that use the CLI)
10
+
11
+ - **Write calls against production now need confirmation.** In a terminal you
12
+ are asked `Continue? [y/N]`; without a terminal (scripts, CI) the call is
13
+ refused unless you pass `--yes`. Reads (`get*`, `list*`, `search*`, …),
14
+ `--dry-run` and sandbox calls are unaffected.
15
+ - **`--stream` prints NDJSON**: one compact JSON object per line, instead of
16
+ pretty-printed multi-line objects.
17
+ - **Invalid environments are errors.** `--env`, `SQUARE_ENVIRONMENT` and
18
+ `config set --env` accept only `sandbox` or `production`; a typo like `prod`
19
+ used to fall back to sandbox silently.
20
+ - **Write calls get an automatic `idempotencyKey`** when none is given. The key
21
+ is printed to stderr; pass it back with `--idempotencyKey` to retry safely.
22
+ - **Unknown namespaces and methods exit 1** (e.g. `square bogus` used to print
23
+ help and exit 0).
24
+ - **`--json` must be a JSON object**; arrays and scalars are rejected.
25
+ - **The config file is validated on load**; a malformed profile now fails with
26
+ a message naming the file and the problem.
27
+ - **Field paths containing `__proto__`, `constructor` or `prototype` are rejected.**
28
+
29
+ ### Added
30
+
31
+ - `--dry-run`: print the environment, method and request without sending it.
32
+ - `--json @file.json` and `--json -` read the request body from a file or stdin.
33
+ - `--field:str value` keeps a value as a string instead of JSON-coercing it
34
+ (e.g. `--address.postalCode:str 94103`).
35
+ - `--max-items <n>` and `--max-pages <n>` cap paging.
36
+ - `--yes` skips the production write confirmation.
37
+ - `config set` without `--token` prompts for the token with hidden input, and
38
+ `--token -` reads it from stdin, keeping tokens out of shell history.
39
+ - `config remove <profile>`.
40
+ - `config list` marks the default profile and shows each profile's environment.
41
+ - `square whoami`: shows the merchant, environment and token source in use.
42
+ - Help for namespaces (including nested ones like `square terminal actions`)
43
+ works without credentials.
44
+ - CI on GitHub Actions (typecheck, tests, build, node 18/20/22 smoke tests) and
45
+ a weekly run against the latest `square` SDK release.
46
+ - `bun run typecheck` script; `prepublishOnly` now runs it.
47
+
48
+ ### Fixed
49
+
50
+ - `--json-output` had no effect; it now prints compact JSON.
51
+ - `square <namespace>` without credentials failed with "No authentication found"
52
+ instead of showing help.
53
+
54
+ ### Changed
55
+
56
+ - `typescript` moved from `peerDependencies` to `devDependencies`, so installing
57
+ the CLI no longer warns about a missing peer.
58
+ - `@types/bun` pinned to `^1.4.3` instead of `latest`.
59
+
60
+ ## [0.1.2] - 2026-06-21
61
+
62
+ ### Changed
63
+
64
+ - Square API errors are shown in readable form (HTTP status, detail, field and
65
+ code) with actionable hints for common problems.
66
+
67
+ ### Fixed
68
+
69
+ - README `list` examples now include the sort flags those endpoints require.
70
+
71
+ ## [0.1.1] - 2026-06-19
72
+
73
+ ### Added
74
+
75
+ - MIT `LICENSE` file.
76
+ - npm keywords for discoverability.
77
+
78
+ ## [0.1.0] - 2026-06-19
79
+
80
+ ### Added
81
+
82
+ - Initial release: every Square SDK namespace and method exposed by runtime
83
+ introspection, profile-based config, `--json` and `--field.path` request
84
+ building, automatic paging and `--stream`.
85
+
86
+ [0.2.0]: https://github.com/karthikdilliraj/square-sdk-cli/compare/v0.1.2...v0.2.0
87
+ [0.1.2]: https://github.com/karthikdilliraj/square-sdk-cli/compare/v0.1.1...v0.1.2
88
+ [0.1.1]: https://github.com/karthikdilliraj/square-sdk-cli/compare/45f2670...v0.1.1
89
+ [0.1.0]: https://github.com/karthikdilliraj/square-sdk-cli/tree/45f2670
package/README.md CHANGED
@@ -1,5 +1,7 @@
1
1
  # square-sdk-cli
2
2
 
3
+ [![CI](https://github.com/karthikdilliraj/square-sdk-cli/actions/workflows/ci.yml/badge.svg)](https://github.com/karthikdilliraj/square-sdk-cli/actions/workflows/ci.yml)
4
+
3
5
  A command-line interface for the [Square API](https://developer.squareup.com/),
4
6
  built with [Bun](https://bun.com). It exposes **every** Square SDK namespace and
5
7
  method dynamically by introspecting the SDK at runtime — no hardcoded API list.
@@ -32,13 +34,19 @@ Credentials are stored on your machine at
32
34
  Tokens are written with `0600` permissions and masked when read back.
33
35
 
34
36
  ```bash
35
- square config set sandbox --token <ACCESS_TOKEN> --env sandbox
36
- square config set prod --token <ACCESS_TOKEN> --env production
37
+ square config set sandbox --env sandbox # prompts for the token (hidden)
38
+ square config set prod --env production # same
39
+ pbpaste | square config set prod --token - --env production # token from stdin
37
40
  square config use sandbox # set default profile
38
- square config list
41
+ square config list # * marks the default; shows each environment
39
42
  square config get sandbox # token shown masked
43
+ square config remove sandbox # delete a profile (clears the default if it was)
44
+ square whoami # check the token: merchant, environment, token source
40
45
  ```
41
46
 
47
+ Omitting `--token` (or passing `--token -`) keeps the token out of your shell
48
+ history. `--token <ACCESS_TOKEN>` inline still works.
49
+
42
50
  Auth resolution order: `--profile <name>` → `--token` / `SQUARE_ACCESS_TOKEN`
43
51
  env → default profile.
44
52
 
@@ -71,9 +79,17 @@ square customers list --sortField DEFAULT --sortOrder ASC --stream
71
79
 
72
80
  ### Request body
73
81
 
74
- - `--json '<json>'` — full request body as JSON
82
+ - `--json '<json>'` — full request body as a JSON object; `--json @body.json`
83
+ reads it from a file, `--json -` reads it from stdin
75
84
  - `--field.path value` — set a field by dotted path (merged over `--json`;
76
85
  numeric path segments create arrays; values are JSON-coerced, falling back to string)
86
+ - `--field.path:str value` — same, but the value is always kept as a string
87
+ (e.g. `--address.postalCode:str 94103`, which would otherwise become a number)
88
+
89
+ ```bash
90
+ square payments create --json @payment.json --dry-run # preview, nothing sent
91
+ cat payment.json | square payments create --json -
92
+ ```
77
93
 
78
94
  ### Flags
79
95
 
@@ -81,12 +97,29 @@ square customers list --sortField DEFAULT --sortOrder ASC --stream
81
97
  | --------------- | ------------------------------------------- |
82
98
  | `--profile <n>` | use a named profile from config |
83
99
  | `--token <t>` | Square API access token |
84
- | `--env <e>` | `sandbox` or `production` (default sandbox) |
85
- | `--json '<j>'` | JSON request body |
100
+ | `--env <e>` | `sandbox` or `production` (default sandbox; anything else is an error) |
101
+ | `--json '<j>'` | JSON request body (`@file` or `-` for stdin) |
86
102
  | `--json-output` | compact JSON output (no pretty print) |
87
- | `--stream` | stream pageable results item by item |
103
+ | `--stream` | stream pageable results as NDJSON |
104
+ | `--dry-run` | print the request without sending it |
105
+ | `--max-items <n>` | stop paging after n items |
106
+ | `--max-pages <n>` | stop paging after n pages |
107
+ | `--yes` | skip the production write confirmation |
88
108
  | `--help` | show help |
89
109
 
110
+ ### Safety defaults
111
+
112
+ - **Production writes ask first.** Any call against `production` whose method
113
+ isn't a read (`get*`, `list*`, `search*`, `retrieve*`, `batchGet*`, …) asks
114
+ `Continue? [y/N]`. In scripts or CI (no terminal), it refuses unless you pass
115
+ `--yes`. `--dry-run` never prompts.
116
+ - **Automatic idempotency keys.** Write calls without an `idempotencyKey` get a
117
+ random one, printed to stderr. To retry safely, pass it back with
118
+ `--idempotencyKey <key>`. Endpoints that don't use a key ignore it.
119
+ - **Paging limits.** `list` calls fetch every page by default. Cap them with
120
+ `--max-items` or `--max-pages`. (`--limit` is still the API's own page-size
121
+ field.)
122
+
90
123
  > Per-field help is structural only — the SDK's field schemas live in its
91
124
  > `.d.ts` types and aren't available at runtime. Use `--json` for full bodies.
92
125
 
@@ -94,6 +127,7 @@ square customers list --sortField DEFAULT --sortOrder ASC --stream
94
127
 
95
128
  ```bash
96
129
  bun test # full suite (incl. SDK contract guard test)
130
+ bun run typecheck # tsc --noEmit
97
131
  bun bin/square.ts <namespace> <method>
98
132
  ```
99
133
 
package/dist/square.js CHANGED
@@ -6,11 +6,15 @@ var STRING_FLAGS = {
6
6
  profile: "profile",
7
7
  token: "token",
8
8
  env: "env",
9
- json: "json"
9
+ json: "json",
10
+ "max-items": "maxItems",
11
+ "max-pages": "maxPages"
10
12
  };
11
13
  var BOOL_FLAGS = {
12
14
  "json-output": "jsonOutput",
13
15
  stream: "stream",
16
+ "dry-run": "dryRun",
17
+ yes: "yes",
14
18
  help: "help"
15
19
  };
16
20
  function parseArgs(argv) {
@@ -83,6 +87,9 @@ function handleFlag(key, val, flags) {
83
87
  }
84
88
 
85
89
  // src/merge.ts
90
+ import * as fs from "fs";
91
+ import { randomUUID } from "crypto";
92
+ var STRING_SUFFIX = ":str";
86
93
  function coerce(value) {
87
94
  try {
88
95
  return JSON.parse(value);
@@ -90,8 +97,14 @@ function coerce(value) {
90
97
  return value;
91
98
  }
92
99
  }
100
+ var FORBIDDEN_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
93
101
  function deepSet(obj, path, value) {
94
102
  const segments = path.split(".");
103
+ for (const seg of segments) {
104
+ if (FORBIDDEN_SEGMENTS.has(seg)) {
105
+ throw new Error(`Invalid field path "${path}": "${seg}" is not allowed`);
106
+ }
107
+ }
95
108
  let current = obj;
96
109
  for (let i = 0;i < segments.length - 1; i++) {
97
110
  const seg = segments[i];
@@ -108,27 +121,54 @@ function deepSet(obj, path, value) {
108
121
  function buildRequest(jsonStr, fields) {
109
122
  let base = {};
110
123
  if (jsonStr !== undefined) {
124
+ let parsed;
111
125
  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
- }
126
+ parsed = JSON.parse(jsonStr);
118
127
  } catch (e) {
119
128
  const msg = e instanceof Error ? e.message : String(e);
120
129
  throw new Error(`Invalid JSON: ${msg}`);
121
130
  }
131
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
132
+ throw new Error("Invalid JSON: request body must be a JSON object");
133
+ }
134
+ base = parsed;
122
135
  }
123
136
  for (const field of fields) {
124
- const coerced = coerce(field.value);
125
- deepSet(base, field.path, coerced);
137
+ if (field.path.endsWith(STRING_SUFFIX)) {
138
+ deepSet(base, field.path.slice(0, -STRING_SUFFIX.length), field.value);
139
+ } else {
140
+ deepSet(base, field.path, coerce(field.value));
141
+ }
126
142
  }
127
143
  return base;
128
144
  }
145
+ function readJsonArg(raw, readFile = (source) => fs.readFileSync(source, "utf8")) {
146
+ if (raw === "-")
147
+ return readFile(0);
148
+ if (raw.startsWith("@")) {
149
+ const file = raw.slice(1);
150
+ try {
151
+ return readFile(file);
152
+ } catch (e) {
153
+ const msg = e instanceof Error ? e.message : String(e);
154
+ throw new Error(`Cannot read --json file "${file}": ${msg}`);
155
+ }
156
+ }
157
+ return raw;
158
+ }
159
+ function ensureIdempotencyKey(request, methodName, newKey = randomUUID) {
160
+ if (/IdempotencyKey/.test(methodName))
161
+ return;
162
+ const body = request;
163
+ if (body["idempotencyKey"] !== undefined)
164
+ return;
165
+ const key = newKey();
166
+ body["idempotencyKey"] = key;
167
+ return key;
168
+ }
129
169
 
130
170
  // src/config.ts
131
- import * as fs from "fs";
171
+ import * as fs2 from "fs";
132
172
  import * as path from "path";
133
173
  import * as os from "os";
134
174
  function getConfigPath() {
@@ -141,24 +181,55 @@ function getConfigPath() {
141
181
  }
142
182
  async function load() {
143
183
  const configPath = getConfigPath();
144
- if (!fs.existsSync(configPath)) {
184
+ if (!fs2.existsSync(configPath)) {
145
185
  return { profiles: {} };
146
186
  }
147
- const raw = fs.readFileSync(configPath, "utf8");
187
+ const raw = fs2.readFileSync(configPath, "utf8");
188
+ let parsed;
148
189
  try {
149
- const parsed = JSON.parse(raw);
150
- return parsed;
190
+ parsed = JSON.parse(raw);
151
191
  } catch (e) {
152
192
  const msg = e instanceof Error ? e.message : String(e);
153
193
  throw new Error(`Failed to parse config at ${configPath}: ${msg}`);
154
194
  }
195
+ return validateConfig(parsed, configPath);
196
+ }
197
+ function isObject(value) {
198
+ return value !== null && typeof value === "object" && !Array.isArray(value);
199
+ }
200
+ function validateConfig(parsed, configPath) {
201
+ const fail = (problem) => {
202
+ throw new Error(`Invalid config at ${configPath}: ${problem}`);
203
+ };
204
+ if (!isObject(parsed))
205
+ fail("expected a JSON object");
206
+ const cfg = parsed;
207
+ const profiles = cfg["profiles"] ?? {};
208
+ if (!isObject(profiles))
209
+ fail(`"profiles" must be an object`);
210
+ for (const [name, profile] of Object.entries(profiles)) {
211
+ if (!isObject(profile))
212
+ fail(`profile "${name}" must be an object`);
213
+ const p = profile;
214
+ if (typeof p["token"] !== "string" || p["token"] === "") {
215
+ fail(`profile "${name}" is missing a "token"`);
216
+ }
217
+ if (p["environment"] !== "sandbox" && p["environment"] !== "production") {
218
+ fail(`profile "${name}" has environment ${JSON.stringify(p["environment"])}; expected "sandbox" or "production"`);
219
+ }
220
+ }
221
+ const defaultProfile = cfg["defaultProfile"];
222
+ if (defaultProfile !== undefined && typeof defaultProfile !== "string") {
223
+ fail(`"defaultProfile" must be a string`);
224
+ }
225
+ return { ...cfg, profiles };
155
226
  }
156
227
  async function save(cfg) {
157
228
  const configPath = getConfigPath();
158
229
  const dir = path.dirname(configPath);
159
- fs.mkdirSync(dir, { recursive: true });
230
+ fs2.mkdirSync(dir, { recursive: true });
160
231
  const content = JSON.stringify(cfg, null, 2);
161
- fs.writeFileSync(configPath, content, { mode: 384 });
232
+ fs2.writeFileSync(configPath, content, { mode: 384 });
162
233
  }
163
234
  async function setProfile(name, partial) {
164
235
  const cfg = await load();
@@ -170,10 +241,6 @@ async function getProfile(name) {
170
241
  const cfg = await load();
171
242
  return cfg.profiles[name];
172
243
  }
173
- async function listProfiles() {
174
- const cfg = await load();
175
- return Object.keys(cfg.profiles);
176
- }
177
244
  async function useProfile(name) {
178
245
  const cfg = await load();
179
246
  if (!cfg.profiles[name]) {
@@ -182,15 +249,31 @@ async function useProfile(name) {
182
249
  cfg.defaultProfile = name;
183
250
  await save(cfg);
184
251
  }
252
+ async function removeProfile(name) {
253
+ const cfg = await load();
254
+ if (!cfg.profiles[name]) {
255
+ throw new Error(`Profile "${name}" does not exist.`);
256
+ }
257
+ delete cfg.profiles[name];
258
+ const wasDefault = cfg.defaultProfile === name;
259
+ if (wasDefault)
260
+ delete cfg.defaultProfile;
261
+ await save(cfg);
262
+ return wasDefault;
263
+ }
185
264
 
186
265
  // src/auth.ts
266
+ function parseEnvironment(value, source) {
267
+ if (value === "sandbox" || value === "production")
268
+ return value;
269
+ throw new Error(`Invalid ${source} "${value}". Expected "sandbox" or "production".`);
270
+ }
187
271
  function resolveEnvironment(flags, env) {
188
- if (flags.env) {
189
- return flags.env === "production" ? "production" : "sandbox";
190
- }
272
+ if (flags.env !== undefined)
273
+ return parseEnvironment(String(flags.env), "--env");
191
274
  const envVal = env["SQUARE_ENVIRONMENT"];
192
- if (envVal === "production")
193
- return "production";
275
+ if (envVal)
276
+ return parseEnvironment(envVal, "SQUARE_ENVIRONMENT");
194
277
  return "sandbox";
195
278
  }
196
279
  function resolveAuth(flags, env, config) {
@@ -199,17 +282,21 @@ function resolveAuth(flags, env, config) {
199
282
  if (!profile) {
200
283
  throw new Error(`Profile "${flags.profile}" not found. Available profiles: ${Object.keys(config.profiles).join(", ") || "(none)"}`);
201
284
  }
202
- return { token: profile.token, environment: profile.environment };
285
+ return { token: profile.token, environment: profile.environment, source: `profile "${flags.profile}"` };
203
286
  }
204
287
  const token = flags.token ?? env["SQUARE_ACCESS_TOKEN"];
205
288
  if (token) {
206
289
  const environment = resolveEnvironment(flags, env);
207
- return { token, environment };
290
+ return { token, environment, source: flags.token ? "--token" : "SQUARE_ACCESS_TOKEN" };
208
291
  }
209
292
  if (config.defaultProfile) {
210
293
  const profile = config.profiles[config.defaultProfile];
211
294
  if (profile) {
212
- return { token: profile.token, environment: profile.environment };
295
+ return {
296
+ token: profile.token,
297
+ environment: profile.environment,
298
+ source: `default profile "${config.defaultProfile}"`
299
+ };
213
300
  }
214
301
  }
215
302
  throw new Error("No authentication found. Provide --token, set SQUARE_ACCESS_TOKEN, use --profile, or configure a default profile with `square config use <profile>`.");
@@ -278,6 +365,16 @@ function buildTree(client) {
278
365
  const seen = new WeakSet;
279
366
  return buildNode("root", client, seen, 0);
280
367
  }
368
+ function findNamespace(tree, segments) {
369
+ let current = tree;
370
+ for (const seg of segments) {
371
+ const child = current.children.get(seg);
372
+ if (!child)
373
+ return;
374
+ current = child;
375
+ }
376
+ return current;
377
+ }
281
378
  function resolvePath(tree, segments) {
282
379
  if (segments.length === 0) {
283
380
  const validTokens = [
@@ -306,6 +403,12 @@ function resolvePath(tree, segments) {
306
403
  ...current.methods.keys(),
307
404
  ...current.children.keys()
308
405
  ];
406
+ if (current === tree) {
407
+ return {
408
+ error: `Unknown namespace "${methodName}". Valid options: ${validTokens.join(", ")}`,
409
+ validTokens
410
+ };
411
+ }
309
412
  return {
310
413
  error: `Unknown method "${methodName}" on namespace "${current.name}". Valid: ${validTokens.join(", ")}`,
311
414
  validTokens
@@ -313,6 +416,10 @@ function resolvePath(tree, segments) {
313
416
  }
314
417
  return { node: current, method };
315
418
  }
419
+ var READ_ONLY_PREFIX = /^(get|list|search|retrieve|batchGet|bulkRetrieve|calculate|info|changes|deprecatedGet|deprecatedBatchGet|v1List|v1Retrieve)/;
420
+ function isReadOnlyMethod(name) {
421
+ return READ_ONLY_PREFIX.test(name);
422
+ }
316
423
 
317
424
  // src/execute.ts
318
425
  function isPage(value) {
@@ -321,34 +428,40 @@ function isPage(value) {
321
428
  const v = value;
322
429
  return Symbol.asyncIterator in value && typeof v["hasNextPage"] === "function" && "data" in v;
323
430
  }
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) {
431
+ async function* iteratePages(firstPage, options) {
432
+ const { maxItems, maxPages } = options;
336
433
  let page = firstPage;
434
+ let pages = 1;
435
+ let items = 0;
337
436
  while (true) {
338
437
  for (const item of page.data) {
438
+ if (maxItems !== undefined && items >= maxItems)
439
+ return;
339
440
  yield item;
441
+ items++;
340
442
  }
341
443
  if (!page.hasNextPage())
342
- break;
444
+ return;
445
+ if (maxPages !== undefined && pages >= maxPages)
446
+ return;
447
+ if (maxItems !== undefined && items >= maxItems)
448
+ return;
343
449
  page = await page.getNextPage();
450
+ pages++;
344
451
  }
345
452
  }
453
+ async function collectPages(firstPage, options) {
454
+ const results = [];
455
+ for await (const item of iteratePages(firstPage, options))
456
+ results.push(item);
457
+ return results;
458
+ }
346
459
  function execute(method, request, options) {
347
460
  if (options.stream) {
348
461
  return async function* () {
349
462
  const result = await Promise.resolve(method.fn(request));
350
463
  if (isPage(result)) {
351
- yield* streamPages(result);
464
+ yield* iteratePages(result, options);
352
465
  } else {
353
466
  yield result;
354
467
  }
@@ -357,7 +470,7 @@ function execute(method, request, options) {
357
470
  return (async () => {
358
471
  const result = await Promise.resolve(method.fn(request));
359
472
  if (isPage(result)) {
360
- return collectPages(result);
473
+ return collectPages(result, options);
361
474
  }
362
475
  return result;
363
476
  })();
@@ -453,9 +566,13 @@ Global flags:
453
566
  --profile <name> Use a named profile from config
454
567
  --token <token> Square API access token
455
568
  --env <environment> "sandbox" or "production" (default: sandbox)
456
- --json <json> JSON body for the request
569
+ --json <json> JSON body for the request (@file or - for stdin)
457
570
  --json-output Output as compact JSON (no pretty print)
458
- --stream Stream pageable results item by item
571
+ --stream Stream pageable results as NDJSON (one item per line)
572
+ --dry-run Print the request that would be sent, without sending it
573
+ --max-items <n> Stop paging after n items
574
+ --max-pages <n> Stop paging after n pages
575
+ --yes Skip the confirmation for write calls in production
459
576
  --help Show this help message
460
577
  `.trim();
461
578
  function renderRootHelp(tree) {
@@ -473,30 +590,33 @@ function renderRootHelp(tree) {
473
590
  }
474
591
  lines.push("");
475
592
  lines.push("Built-in commands:");
476
- lines.push(" config set <profile> --token <tok> --env <env> Create/update a profile");
593
+ lines.push(" config set <profile> [--token <tok>|-] --env <env> Create/update a profile");
594
+ lines.push(" (omit --token to be prompted)");
477
595
  lines.push(" config get <profile> Show profile (token masked)");
478
- lines.push(" config list List all profiles");
596
+ lines.push(" config list List profiles (* marks the default)");
479
597
  lines.push(" config use <profile> Set default profile");
598
+ lines.push(" config remove <profile> Delete a profile");
599
+ lines.push(" whoami Show the merchant for the current token");
480
600
  lines.push("");
481
601
  lines.push(GLOBAL_FLAGS);
482
602
  return lines.join(`
483
603
  `);
484
604
  }
485
- function renderNamespaceHelp(node) {
605
+ function renderNamespaceHelp(node, path2 = node.name) {
486
606
  const lines = [];
487
- lines.push(`Namespace: ${node.name}`);
607
+ lines.push(`Namespace: ${path2}`);
488
608
  lines.push("");
489
609
  if (node.children.size > 0) {
490
610
  lines.push("Sub-namespaces:");
491
611
  for (const [name] of node.children) {
492
- lines.push(` ${node.name} ${name}`);
612
+ lines.push(` ${path2} ${name}`);
493
613
  }
494
614
  lines.push("");
495
615
  }
496
616
  if (node.methods.size > 0) {
497
617
  lines.push("Methods:");
498
618
  for (const [name, method] of node.methods) {
499
- lines.push(` ${node.name} ${name} (arity: ${method.arity})`);
619
+ lines.push(` ${path2} ${name} (arity: ${method.arity})`);
500
620
  }
501
621
  lines.push("");
502
622
  }
@@ -515,6 +635,8 @@ function renderMethodHelp(namespaceName, methodName, arity) {
515
635
  lines.push(" --json '<json>' Full request body as JSON");
516
636
  lines.push(" --<field.path> <value> Set a field in the request by dotted path");
517
637
  lines.push(` e.g. --amountMoney.amount 100`);
638
+ lines.push(" --<field.path>:str <value> Same, but keep the value a string (no JSON coercion)");
639
+ lines.push(` e.g. --address.postalCode:str 94103`);
518
640
  lines.push("");
519
641
  lines.push(`Note: arity hint = ${arity} (optional params may not be counted)`);
520
642
  lines.push(" Always pass a request object (even if empty).");
@@ -524,100 +646,203 @@ function renderMethodHelp(namespaceName, methodName, arity) {
524
646
  `);
525
647
  }
526
648
 
649
+ // src/prompt.ts
650
+ import * as fs3 from "fs";
651
+ import * as readline from "readline";
652
+ function isInteractive() {
653
+ return Boolean(process.stdin.isTTY && process.stderr.isTTY);
654
+ }
655
+ async function confirm(question) {
656
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
657
+ const answer = await new Promise((resolve) => rl.question(question, resolve));
658
+ rl.close();
659
+ return /^y(es)?$/i.test(answer.trim());
660
+ }
661
+ function secret(question) {
662
+ return new Promise((resolve, reject) => {
663
+ const stdin = process.stdin;
664
+ let value = "";
665
+ const finish = (err) => {
666
+ stdin.off("data", onData);
667
+ stdin.setRawMode(false);
668
+ stdin.pause();
669
+ process.stderr.write(`
670
+ `);
671
+ if (err)
672
+ reject(err);
673
+ else
674
+ resolve(value);
675
+ };
676
+ const onData = (chunk) => {
677
+ for (const ch of chunk) {
678
+ if (ch === "\r" || ch === `
679
+ `)
680
+ return finish();
681
+ if (ch === "\x03")
682
+ return finish(new Error("Cancelled"));
683
+ if (ch === "" || ch === "\b") {
684
+ value = value.slice(0, -1);
685
+ continue;
686
+ }
687
+ value += ch;
688
+ }
689
+ };
690
+ process.stderr.write(question);
691
+ stdin.setRawMode(true);
692
+ stdin.setEncoding("utf8");
693
+ stdin.resume();
694
+ stdin.on("data", onData);
695
+ });
696
+ }
697
+ function readStdin() {
698
+ return fs3.readFileSync(0, "utf8");
699
+ }
700
+ var terminalPrompter = { isInteractive, confirm, secret, readStdin };
701
+
527
702
  // src/cli.ts
528
703
  var defaultDeps = {
529
- createClient
704
+ createClient,
705
+ prompter: terminalPrompter
530
706
  };
531
707
  async function run(argv, deps = defaultDeps, stdoutWrite, stderrWrite) {
532
708
  const stdout = stdoutWrite ?? ((msg) => process.stdout.write(msg + `
533
709
  `));
534
710
  const stderr = stderrWrite ?? ((msg) => process.stderr.write(msg + `
535
711
  `));
712
+ const prompter = deps.prompter ?? terminalPrompter;
536
713
  const parsed = parseArgs(argv);
537
714
  const { positionals, flags, fields } = parsed;
538
715
  if (positionals[0] === "config") {
539
- return runConfigCommand(positionals.slice(1), flags, stdout, stderr);
716
+ return runConfigCommand(positionals.slice(1), flags, prompter, stdout, stderr);
540
717
  }
541
- if (flags.help) {
542
- try {
543
- const dummyClient = deps.createClient({ token: "dummy", environment: "sandbox" });
544
- const tree2 = buildTree(dummyClient);
545
- if (positionals.length === 0) {
546
- stdout(renderRootHelp(tree2));
547
- return 0;
548
- }
549
- if (positionals.length === 1) {
550
- const nsNode = tree2.children.get(positionals[0]);
551
- if (nsNode) {
552
- stdout(renderNamespaceHelp(nsNode));
553
- return 0;
554
- }
555
- } else {
556
- const resolveResult2 = resolvePath(tree2, positionals);
557
- if (!("error" in resolveResult2)) {
558
- stdout(renderMethodHelp(positionals.slice(0, -1).join(" "), resolveResult2.method.name, resolveResult2.method.arity));
559
- return 0;
560
- }
561
- }
562
- stdout(renderRootHelp(tree2));
563
- return 0;
564
- } catch {
565
- stdout("Square SDK CLI\n\nUse `square --help` for available namespaces.");
718
+ if (positionals[0] === "whoami") {
719
+ if (flags.help) {
720
+ stdout(`Usage: square whoami [--profile <name>] [--json-output]
721
+
722
+ Show the merchant, environment, and token source in use.`);
566
723
  return 0;
567
724
  }
725
+ return runWhoami(deps, flags, stdout, stderr);
726
+ }
727
+ const shapeTree = buildTree(deps.createClient({ token: "dummy", environment: "sandbox" }));
728
+ if (positionals.length === 0) {
729
+ stdout(renderRootHelp(shapeTree));
730
+ return 0;
731
+ }
732
+ const nsNode = findNamespace(shapeTree, positionals);
733
+ if (nsNode) {
734
+ stdout(renderNamespaceHelp(nsNode, positionals.join(" ")));
735
+ return 0;
736
+ }
737
+ const shapeResult = resolvePath(shapeTree, positionals);
738
+ if (flags.help) {
739
+ if ("error" in shapeResult) {
740
+ stdout(renderRootHelp(shapeTree));
741
+ } else {
742
+ stdout(renderMethodHelp(positionals.slice(0, -1).join(" "), shapeResult.method.name, shapeResult.method.arity));
743
+ }
744
+ return 0;
745
+ }
746
+ if ("error" in shapeResult) {
747
+ stderr(`Error: ${shapeResult.error}`);
748
+ return 1;
568
749
  }
569
750
  let auth;
570
751
  try {
571
- const config = await load();
572
- const env = process.env;
573
- auth = resolveAuth({ profile: flags.profile, token: flags.token, env: flags.env }, env, config);
752
+ auth = await resolveAuthFromFlags(flags);
574
753
  } catch (e) {
575
- const exitCode = renderError(e, { writeFn: stderr });
576
- return exitCode;
577
- }
578
- const client = deps.createClient(auth);
579
- const tree = buildTree(client);
580
- if (positionals.length === 1) {
581
- const nsNode = tree.children.get(positionals[0]);
582
- if (nsNode) {
583
- stdout(renderNamespaceHelp(nsNode));
584
- return 0;
585
- }
586
- }
587
- if (positionals.length < 2) {
588
- stdout(renderRootHelp(tree));
589
- return 0;
754
+ return renderError(e, { writeFn: stderr });
590
755
  }
591
- const resolveResult = resolvePath(tree, positionals);
756
+ const resolveResult = resolvePath(buildTree(deps.createClient(auth)), positionals);
592
757
  if ("error" in resolveResult) {
593
758
  stderr(`Error: ${resolveResult.error}`);
594
- stderr(`Valid options: ${resolveResult.validTokens.join(", ")}`);
595
759
  return 1;
596
760
  }
597
761
  let request;
762
+ let maxItems;
763
+ let maxPages;
598
764
  try {
599
- request = buildRequest(flags.json, fields);
765
+ maxItems = parseLimit(flags.maxItems, "--max-items");
766
+ maxPages = parseLimit(flags.maxPages, "--max-pages");
767
+ if (flags.json !== undefined && typeof flags.json !== "string") {
768
+ throw new Error("--json requires a value: a JSON string, @file, or - for stdin");
769
+ }
770
+ request = buildRequest(flags.json === undefined ? undefined : readJsonArg(flags.json), fields);
600
771
  } catch (e) {
601
772
  renderError(e, { writeFn: stderr });
602
773
  return 1;
603
774
  }
775
+ const raw = flags.jsonOutput === true;
776
+ const methodName = resolveResult.method.name;
777
+ const readOnly = isReadOnlyMethod(methodName);
778
+ const generatedKey = readOnly ? undefined : ensureIdempotencyKey(request, methodName);
779
+ if (flags.dryRun) {
780
+ print({
781
+ dryRun: true,
782
+ environment: auth.environment,
783
+ method: positionals.join(" "),
784
+ request
785
+ }, { raw, writeFn: stdout });
786
+ return 0;
787
+ }
788
+ if (auth.environment === "production" && !readOnly && !flags.yes) {
789
+ const command = positionals.join(" ");
790
+ if (!prompter.isInteractive()) {
791
+ stderr(`✗ Error: Refusing to run "${command}" against PRODUCTION without confirmation. Pass --yes to proceed.`);
792
+ return 1;
793
+ }
794
+ const ok = await prompter.confirm(`About to run "${command}" against PRODUCTION. Continue? [y/N] `);
795
+ if (!ok) {
796
+ stderr("Aborted.");
797
+ return 1;
798
+ }
799
+ }
800
+ if (generatedKey)
801
+ stderr(`Using idempotencyKey ${generatedKey} (pass --idempotencyKey to retry safely)`);
604
802
  try {
605
803
  const streamMode = flags.stream === true;
606
- const result = execute(resolveResult.method, request, { stream: streamMode });
804
+ const result = execute(resolveResult.method, request, { stream: streamMode, maxItems, maxPages });
607
805
  if (streamMode) {
608
806
  for await (const item of result) {
609
- stdout(JSON.stringify(item, bigIntReplacer, 2));
807
+ stdout(JSON.stringify(item, bigIntReplacer));
610
808
  }
611
809
  } else {
612
810
  const value = await result;
613
- print(value, { writeFn: stdout });
811
+ print(value, { raw, writeFn: stdout });
614
812
  }
615
813
  return 0;
616
814
  } catch (e) {
617
815
  return renderError(e, { writeFn: stderr });
618
816
  }
619
817
  }
620
- async function runConfigCommand(args, flags, stdout, stderr) {
818
+ async function resolveAuthFromFlags(flags) {
819
+ const config = await load();
820
+ const env = process.env;
821
+ return resolveAuth({ profile: flags.profile, token: flags.token, env: flags.env }, env, config);
822
+ }
823
+ async function runWhoami(deps, flags, stdout, stderr) {
824
+ try {
825
+ const auth = await resolveAuthFromFlags(flags);
826
+ const client = deps.createClient(auth);
827
+ const { merchant } = await client.merchants.get({ merchantId: "me" });
828
+ print({
829
+ environment: auth.environment,
830
+ tokenSource: auth.source,
831
+ merchant: {
832
+ id: merchant?.id,
833
+ businessName: merchant?.businessName,
834
+ country: merchant?.country,
835
+ currency: merchant?.currency,
836
+ status: merchant?.status,
837
+ mainLocationId: merchant?.mainLocationId
838
+ }
839
+ }, { raw: flags.jsonOutput === true, writeFn: stdout });
840
+ return 0;
841
+ } catch (e) {
842
+ return renderError(e, { writeFn: stderr });
843
+ }
844
+ }
845
+ async function runConfigCommand(args, flags, prompter, stdout, stderr) {
621
846
  const subcommand = args[0];
622
847
  switch (subcommand) {
623
848
  case "set": {
@@ -626,12 +851,33 @@ async function runConfigCommand(args, flags, stdout, stderr) {
626
851
  stderr("Usage: square config set <profile> --token <token> [--env <environment>]");
627
852
  return 1;
628
853
  }
629
- if (!flags.token) {
630
- stderr("Error: --token is required for config set");
854
+ let environment = "sandbox";
855
+ try {
856
+ if (flags.env !== undefined)
857
+ environment = parseEnvironment(String(flags.env), "--env");
858
+ } catch (e) {
859
+ return renderError(e, { writeFn: stderr });
860
+ }
861
+ let token;
862
+ try {
863
+ if (flags.token === "-") {
864
+ token = prompter.readStdin().trim();
865
+ } else if (typeof flags.token === "string") {
866
+ token = flags.token;
867
+ } else if (prompter.isInteractive()) {
868
+ token = (await prompter.secret("Access token: ")).trim();
869
+ } else {
870
+ stderr("Error: --token is required for config set (use --token - to read it from stdin)");
871
+ return 1;
872
+ }
873
+ } catch (e) {
874
+ return renderError(e, { writeFn: stderr });
875
+ }
876
+ if (!token) {
877
+ stderr("Error: token is empty");
631
878
  return 1;
632
879
  }
633
- const environment = flags.env === "production" ? "production" : "sandbox";
634
- await setProfile(profileName, { token: flags.token, environment });
880
+ await setProfile(profileName, { token, environment });
635
881
  stdout(`Profile "${profileName}" saved.`);
636
882
  return 0;
637
883
  }
@@ -651,17 +897,37 @@ async function runConfigCommand(args, flags, stdout, stderr) {
651
897
  return 0;
652
898
  }
653
899
  case "list": {
654
- const names = await listProfiles();
900
+ const cfg = await load();
901
+ const names = Object.keys(cfg.profiles);
655
902
  if (names.length === 0) {
656
903
  stdout("No profiles configured.");
657
- } else {
658
- stdout("Profiles:");
659
- for (const name of names) {
660
- stdout(` ${name}`);
661
- }
904
+ return 0;
905
+ }
906
+ const width = Math.max(...names.map((n) => n.length));
907
+ stdout("Profiles:");
908
+ for (const name of names) {
909
+ const marker = name === cfg.defaultProfile ? "*" : " ";
910
+ stdout(`${marker} ${name.padEnd(width)} ${cfg.profiles[name].environment}`);
662
911
  }
912
+ if (cfg.defaultProfile)
913
+ stdout(`
914
+ (* = default)`);
663
915
  return 0;
664
916
  }
917
+ case "remove": {
918
+ const profileName = args[1];
919
+ if (!profileName) {
920
+ stderr("Usage: square config remove <profile>");
921
+ return 1;
922
+ }
923
+ try {
924
+ const wasDefault = await removeProfile(profileName);
925
+ stdout(`Profile "${profileName}" removed.${wasDefault ? " It was the default; no default is set now." : ""}`);
926
+ return 0;
927
+ } catch (e) {
928
+ return renderError(e, { writeFn: stderr });
929
+ }
930
+ }
665
931
  case "use": {
666
932
  const profileName = args[1];
667
933
  if (!profileName) {
@@ -677,11 +943,20 @@ async function runConfigCommand(args, flags, stdout, stderr) {
677
943
  }
678
944
  }
679
945
  default: {
680
- stderr(`Unknown config subcommand: "${subcommand}". Use set, get, list, or use.`);
946
+ stderr(`Unknown config subcommand: "${subcommand}". Use set, get, list, use, or remove.`);
681
947
  return 1;
682
948
  }
683
949
  }
684
950
  }
951
+ function parseLimit(value, flag) {
952
+ if (value === undefined)
953
+ return;
954
+ const n = Number(value);
955
+ if (typeof value !== "string" || !Number.isInteger(n) || n < 1) {
956
+ throw new Error(`${flag} must be a positive integer`);
957
+ }
958
+ return n;
959
+ }
685
960
  function maskToken(token) {
686
961
  if (token.length <= 4)
687
962
  return "****";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "square-sdk-cli",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Command-line interface for the Square API, exposing every SDK namespace and method via runtime introspection.",
5
5
  "keywords": [
6
6
  "square",
@@ -27,7 +27,8 @@
27
27
  },
28
28
  "files": [
29
29
  "dist",
30
- "README.md"
30
+ "README.md",
31
+ "CHANGELOG.md"
31
32
  ],
32
33
  "engines": {
33
34
  "node": ">=18"
@@ -35,15 +36,14 @@
35
36
  "scripts": {
36
37
  "build": "bun scripts/build.ts",
37
38
  "test": "bun test",
38
- "prepublishOnly": "bun run build && bun test"
39
+ "typecheck": "tsc --noEmit",
40
+ "prepublishOnly": "bun run typecheck && bun run build && bun test"
39
41
  },
40
42
  "devDependencies": {
41
- "@types/bun": "latest"
42
- },
43
- "peerDependencies": {
44
- "typescript": "^5"
43
+ "@types/bun": "^1.4.3",
44
+ "typescript": "^5.9.3"
45
45
  },
46
46
  "dependencies": {
47
- "square": "^44.1.0"
47
+ "square": "^44.2.1"
48
48
  }
49
49
  }