square-sdk-cli 0.2.0 → 0.3.1

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/dist/square.js CHANGED
@@ -1,6 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
  // @bun
3
3
 
4
+ // src/cli.ts
5
+ import { appendFileSync, writeFileSync } from "node:fs";
6
+
4
7
  // src/args.ts
5
8
  var STRING_FLAGS = {
6
9
  profile: "profile",
@@ -8,14 +11,24 @@ var STRING_FLAGS = {
8
11
  env: "env",
9
12
  json: "json",
10
13
  "max-items": "maxItems",
11
- "max-pages": "maxPages"
14
+ "max-pages": "maxPages",
15
+ timeout: "timeout",
16
+ retry: "retry",
17
+ select: "select",
18
+ output: "output"
12
19
  };
13
20
  var BOOL_FLAGS = {
14
21
  "json-output": "jsonOutput",
15
22
  stream: "stream",
23
+ "raw-page": "rawPage",
16
24
  "dry-run": "dryRun",
17
25
  yes: "yes",
18
- help: "help"
26
+ verbose: "verbose",
27
+ keychain: "keychain",
28
+ offline: "offline",
29
+ table: "table",
30
+ help: "help",
31
+ version: "version"
19
32
  };
20
33
  function parseArgs(argv) {
21
34
  const positionals = [];
@@ -24,6 +37,10 @@ function parseArgs(argv) {
24
37
  let i = 0;
25
38
  while (i < argv.length) {
26
39
  const arg = argv[i];
40
+ if (arg === "--") {
41
+ positionals.push(...argv.slice(i + 1));
42
+ break;
43
+ }
27
44
  if (arg.startsWith("--")) {
28
45
  const body = arg.slice(2);
29
46
  const eqIdx = body.indexOf("=");
@@ -86,91 +103,191 @@ function handleFlag(key, val, flags) {
86
103
  return false;
87
104
  }
88
105
 
89
- // src/merge.ts
90
- import * as fs from "fs";
91
- import { randomUUID } from "crypto";
92
- var STRING_SUFFIX = ":str";
93
- function coerce(value) {
94
- try {
95
- return JSON.parse(value);
96
- } catch {
106
+ // src/auth.ts
107
+ function parseEnvironment(value, source) {
108
+ if (value === "sandbox" || value === "production")
97
109
  return value;
98
- }
110
+ throw new Error(`Invalid ${source} "${value}". Expected "sandbox" or "production".`);
99
111
  }
100
- var FORBIDDEN_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
101
- function deepSet(obj, path, value) {
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
- }
108
- let current = obj;
109
- for (let i = 0;i < segments.length - 1; i++) {
110
- const seg = segments[i];
111
- const nextSeg = segments[i + 1];
112
- const isNextNumeric = /^\d+$/.test(nextSeg);
113
- if (current[seg] === undefined || current[seg] === null) {
114
- current[seg] = isNextNumeric ? [] : {};
115
- }
116
- current = current[seg];
112
+ function resolveEnvironment(flags, env) {
113
+ if (flags.env !== undefined)
114
+ return parseEnvironment(String(flags.env), "--env");
115
+ const envVal = env["SQUARE_ENVIRONMENT"];
116
+ if (envVal)
117
+ return parseEnvironment(envVal, "SQUARE_ENVIRONMENT");
118
+ return "sandbox";
119
+ }
120
+ function resolveProfileEnvironment(flags, profileEnvironment) {
121
+ if (flags.env === undefined)
122
+ return profileEnvironment;
123
+ return parseEnvironment(String(flags.env), "--env");
124
+ }
125
+ function profileToken(profile, name) {
126
+ if (profile.token)
127
+ return profile.token;
128
+ if (profile.keychain) {
129
+ throw new Error(`Profile "${name}" stores its token in the OS keychain, but no token was found. ` + `Re-run \`square config set ${name} --token - --keychain\` to store it again.`);
117
130
  }
118
- const lastSeg = segments[segments.length - 1];
119
- current[lastSeg] = value;
131
+ throw new Error(`Profile "${name}" has no token. Re-run \`square config set ${name} --token -\`.`);
120
132
  }
121
- function buildRequest(jsonStr, fields) {
122
- let base = {};
123
- if (jsonStr !== undefined) {
124
- let parsed;
125
- try {
126
- parsed = JSON.parse(jsonStr);
127
- } catch (e) {
128
- const msg = e instanceof Error ? e.message : String(e);
129
- throw new Error(`Invalid JSON: ${msg}`);
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
+ function resolveAuth(flags, env, config) {
134
+ if (flags.profile !== undefined) {
135
+ const profile = config.profiles[flags.profile];
136
+ if (!profile) {
137
+ throw new Error(`Profile "${flags.profile}" not found. Available profiles: ${Object.keys(config.profiles).join(", ") || "(none)"}`);
133
138
  }
134
- base = parsed;
139
+ return {
140
+ token: profileToken(profile, flags.profile),
141
+ environment: resolveProfileEnvironment(flags, profile.environment),
142
+ source: `profile "${flags.profile}"`
143
+ };
135
144
  }
136
- for (const field of fields) {
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
- }
145
+ const token = flags.token ?? env["SQUARE_ACCESS_TOKEN"];
146
+ if (token) {
147
+ const environment = resolveEnvironment(flags, env);
148
+ return { token, environment, source: flags.token ? "--token" : "SQUARE_ACCESS_TOKEN" };
142
149
  }
143
- return base;
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}`);
150
+ if (config.defaultProfile) {
151
+ const profile = config.profiles[config.defaultProfile];
152
+ if (profile) {
153
+ return {
154
+ token: profileToken(profile, config.defaultProfile),
155
+ environment: resolveProfileEnvironment(flags, profile.environment),
156
+ source: `default profile "${config.defaultProfile}"`
157
+ };
155
158
  }
156
159
  }
157
- return raw;
160
+ throw new Error("No authentication found. Provide --token, set SQUARE_ACCESS_TOKEN, use --profile, or configure a default profile with `square config use <profile>`.");
158
161
  }
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;
162
+
163
+ // src/client.ts
164
+ import { SquareClient, SquareEnvironment } from "square";
165
+ function createClient(auth, options = {}) {
166
+ const environment = auth.environment === "production" ? SquareEnvironment.Production : SquareEnvironment.Sandbox;
167
+ return new SquareClient({
168
+ token: auth.token,
169
+ environment,
170
+ ...options.timeoutInSeconds !== undefined ? { timeoutInSeconds: options.timeoutInSeconds } : {},
171
+ ...options.maxRetries !== undefined ? { maxRetries: options.maxRetries } : {}
172
+ });
173
+ }
174
+
175
+ // src/completion.ts
176
+ var GLOBAL_FLAGS = [
177
+ "--profile",
178
+ "--token",
179
+ "--env",
180
+ "--json",
181
+ "--json-output",
182
+ "--stream",
183
+ "--raw-page",
184
+ "--dry-run",
185
+ "--max-items",
186
+ "--max-pages",
187
+ "--timeout",
188
+ "--retry",
189
+ "--select",
190
+ "--table",
191
+ "--output",
192
+ "--yes",
193
+ "--verbose",
194
+ "--keychain",
195
+ "--offline",
196
+ "--help",
197
+ "--version"
198
+ ];
199
+ var ROOT_COMMANDS = ["search", "completion", "config", "whoami", "doctor"];
200
+ var SUPPORTED_SHELLS = ["bash", "zsh", "fish"];
201
+ function levels(tree) {
202
+ const out = [];
203
+ const walk = (node, prefix) => {
204
+ const words = [...node.children.keys(), ...node.methods.keys()];
205
+ out.push({
206
+ path: prefix,
207
+ words: prefix.length === 0 ? [...ROOT_COMMANDS, ...words, ...GLOBAL_FLAGS] : [...words, ...GLOBAL_FLAGS]
208
+ });
209
+ for (const [name, child] of node.children)
210
+ walk(child, [...prefix, name]);
211
+ };
212
+ walk(tree, []);
213
+ return out;
214
+ }
215
+ function bash(tree) {
216
+ const cases = levels(tree).map(({ path, words }) => {
217
+ const key = path.join(" ");
218
+ return ` ${JSON.stringify(key)})
219
+ COMPREPLY=( $(compgen -W ${JSON.stringify(words.join(" "))} -- "$cur") )
220
+ ;;`;
221
+ }).join(`
222
+ `);
223
+ return `# bash completion for square
224
+ _square() {
225
+ local cur path="" i
226
+ cur="\${COMP_WORDS[COMP_CWORD]}"
227
+ for ((i=1; i<COMP_CWORD; i++)); do path+="\${path:+ }\${COMP_WORDS[i]}"; done
228
+ COMPREPLY=()
229
+ case "$path" in
230
+ ${cases}
231
+ esac
232
+ }
233
+ complete -F _square square
234
+ `;
235
+ }
236
+ function zsh(tree) {
237
+ const cases = levels(tree).map(({ path, words }) => {
238
+ const key = path.join(" ");
239
+ return ` ${JSON.stringify(key)})
240
+ candidates=(${words.join(" ")})
241
+ ;;`;
242
+ }).join(`
243
+ `);
244
+ return `#compdef square
245
+ _square() {
246
+ local key="\${(j: :)words[2,CURRENT-1]}"
247
+ local -a candidates
248
+ case "$key" in
249
+ ${cases}
250
+ esac
251
+ (( \${#candidates} )) && compadd -- "\${candidates[@]}"
252
+ }
253
+ _square "$@"
254
+ `;
255
+ }
256
+ function fish(tree) {
257
+ const cases = levels(tree).map(({ path, words }) => {
258
+ const key = path.join(" ");
259
+ return ` case ${JSON.stringify(key)}
260
+ printf '%s\\n' ${words.join(" ")}`;
261
+ }).join(`
262
+ `);
263
+ return `# fish completion for square
264
+ function __square_complete
265
+ set -l key (string join ' ' (commandline -opc)[2..-1])
266
+ switch "$key"
267
+ ${cases}
268
+ case '*'
269
+ return
270
+ end
271
+ end
272
+ complete -c square -f -a '(__square_complete)'
273
+ `;
274
+ }
275
+ function renderCompletion(shell, tree) {
276
+ switch (shell) {
277
+ case "bash":
278
+ return bash(tree);
279
+ case "zsh":
280
+ return zsh(tree);
281
+ case "fish":
282
+ return fish(tree);
283
+ }
168
284
  }
169
285
 
170
286
  // src/config.ts
171
- import * as fs2 from "fs";
172
- import * as path from "path";
173
- import * as os from "os";
287
+ import { randomUUID } from "node:crypto";
288
+ import { chmod, mkdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
289
+ import * as os from "node:os";
290
+ import * as path from "node:path";
174
291
  function getConfigPath() {
175
292
  const override = process.env["SQUARE_CLI_CONFIG"];
176
293
  if (override)
@@ -181,10 +298,15 @@ function getConfigPath() {
181
298
  }
182
299
  async function load() {
183
300
  const configPath = getConfigPath();
184
- if (!fs2.existsSync(configPath)) {
185
- return { profiles: {} };
301
+ let raw;
302
+ try {
303
+ raw = await readFile(configPath, "utf8");
304
+ } catch (e) {
305
+ if (e.code === "ENOENT")
306
+ return { profiles: {} };
307
+ throw e;
186
308
  }
187
- const raw = fs2.readFileSync(configPath, "utf8");
309
+ await ensureOwnerOnlyPermissions(configPath);
188
310
  let parsed;
189
311
  try {
190
312
  parsed = JSON.parse(raw);
@@ -211,7 +333,11 @@ function validateConfig(parsed, configPath) {
211
333
  if (!isObject(profile))
212
334
  fail(`profile "${name}" must be an object`);
213
335
  const p = profile;
214
- if (typeof p["token"] !== "string" || p["token"] === "") {
336
+ if (p["keychain"] !== undefined && typeof p["keychain"] !== "boolean") {
337
+ fail(`profile "${name}" has a non-boolean "keychain"`);
338
+ }
339
+ const usesKeychain = p["keychain"] === true;
340
+ if (!usesKeychain && (typeof p["token"] !== "string" || p["token"] === "")) {
215
341
  fail(`profile "${name}" is missing a "token"`);
216
342
  }
217
343
  if (p["environment"] !== "sandbox" && p["environment"] !== "production") {
@@ -224,17 +350,34 @@ function validateConfig(parsed, configPath) {
224
350
  }
225
351
  return { ...cfg, profiles };
226
352
  }
353
+ async function ensureOwnerOnlyPermissions(configPath) {
354
+ if (process.platform === "win32")
355
+ return;
356
+ try {
357
+ const { mode } = await stat(configPath);
358
+ if (mode & 63)
359
+ await chmod(configPath, 384);
360
+ } catch {}
361
+ }
227
362
  async function save(cfg) {
228
363
  const configPath = getConfigPath();
229
364
  const dir = path.dirname(configPath);
230
- fs2.mkdirSync(dir, { recursive: true });
365
+ await mkdir(dir, { recursive: true, mode: 448 });
231
366
  const content = JSON.stringify(cfg, null, 2);
232
- fs2.writeFileSync(configPath, content, { mode: 384 });
367
+ const tmpPath = path.join(dir, `.${path.basename(configPath)}.${process.pid}.${randomUUID()}.tmp`);
368
+ try {
369
+ await writeFile(tmpPath, content, { mode: 384 });
370
+ await rename(tmpPath, configPath);
371
+ } catch (e) {
372
+ try {
373
+ await unlink(tmpPath);
374
+ } catch {}
375
+ throw e;
376
+ }
233
377
  }
234
- async function setProfile(name, partial) {
378
+ async function putProfile(name, profile) {
235
379
  const cfg = await load();
236
- const existing = cfg.profiles[name] ?? { token: "", environment: "sandbox" };
237
- cfg.profiles[name] = { ...existing, ...partial };
380
+ cfg.profiles[name] = profile;
238
381
  await save(cfg);
239
382
  }
240
383
  async function getProfile(name) {
@@ -262,54 +405,253 @@ async function removeProfile(name) {
262
405
  return wasDefault;
263
406
  }
264
407
 
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".`);
408
+ // src/doctor.ts
409
+ import { stat as stat2 } from "node:fs/promises";
410
+ function message(e) {
411
+ return e instanceof Error ? e.message : String(e);
270
412
  }
271
- function resolveEnvironment(flags, env) {
272
- if (flags.env !== undefined)
273
- return parseEnvironment(String(flags.env), "--env");
274
- const envVal = env["SQUARE_ENVIRONMENT"];
275
- if (envVal)
276
- return parseEnvironment(envVal, "SQUARE_ENVIRONMENT");
277
- return "sandbox";
413
+ function runtimeCheck() {
414
+ if (typeof Bun !== "undefined") {
415
+ return { name: "Runtime", ok: true, detail: `bun ${Bun.version}` };
416
+ }
417
+ return { name: "Runtime", ok: true, detail: `node ${process.versions.node}` };
278
418
  }
279
- function resolveAuth(flags, env, config) {
280
- if (flags.profile !== undefined) {
281
- const profile = config.profiles[flags.profile];
282
- if (!profile) {
283
- throw new Error(`Profile "${flags.profile}" not found. Available profiles: ${Object.keys(config.profiles).join(", ") || "(none)"}`);
419
+ async function configCheck() {
420
+ const configPath = getConfigPath();
421
+ try {
422
+ const { mode } = await stat2(configPath);
423
+ const permissions = (mode & 511).toString(8).padStart(3, "0");
424
+ const loose = process.platform !== "win32" && (mode & 63) !== 0;
425
+ return {
426
+ name: "Config",
427
+ ok: !loose,
428
+ detail: loose ? `${configPath} is ${permissions}; it should be 0600 (run: chmod 600 ${configPath})` : `${configPath} (${permissions})`
429
+ };
430
+ } catch (e) {
431
+ if (e.code === "ENOENT") {
432
+ return { name: "Config", ok: true, detail: `${configPath} (not created yet)` };
284
433
  }
285
- return { token: profile.token, environment: profile.environment, source: `profile "${flags.profile}"` };
434
+ return { name: "Config", ok: false, detail: message(e) };
286
435
  }
287
- const token = flags.token ?? env["SQUARE_ACCESS_TOKEN"];
288
- if (token) {
289
- const environment = resolveEnvironment(flags, env);
290
- return { token, environment, source: flags.token ? "--token" : "SQUARE_ACCESS_TOKEN" };
436
+ }
437
+ async function runDoctor(options) {
438
+ const checks = [runtimeCheck()];
439
+ checks.push(await configCheck());
440
+ let keychainProfiles = [];
441
+ try {
442
+ const config = await load();
443
+ keychainProfiles = Object.entries(config.profiles).filter(([, profile]) => profile.keychain).map(([name]) => name);
444
+ } catch {}
445
+ if (keychainProfiles.length > 0) {
446
+ const available = options.keychain.available();
447
+ checks.push({
448
+ name: "Keychain",
449
+ ok: available,
450
+ detail: available ? `in use for ${keychainProfiles.join(", ")}` : `unavailable, but needed by ${keychainProfiles.join(", ")}; re-run config set without --keychain`
451
+ });
291
452
  }
292
- if (config.defaultProfile) {
293
- const profile = config.profiles[config.defaultProfile];
294
- if (profile) {
295
- return {
296
- token: profile.token,
297
- environment: profile.environment,
298
- source: `default profile "${config.defaultProfile}"`
299
- };
453
+ let auth;
454
+ try {
455
+ auth = await options.resolveAuth();
456
+ checks.push({
457
+ name: "Auth",
458
+ ok: true,
459
+ detail: `${auth.source} (${auth.environment})`
460
+ });
461
+ } catch (e) {
462
+ checks.push({ name: "Auth", ok: false, detail: message(e) });
463
+ }
464
+ if (options.offline) {
465
+ checks.push({ name: "API", ok: true, detail: "skipped (--offline)" });
466
+ } else if (auth) {
467
+ try {
468
+ const client = options.createClient(auth);
469
+ const { merchant } = await client.merchants.get({ merchantId: "me" });
470
+ checks.push({
471
+ name: "API",
472
+ ok: true,
473
+ detail: merchant?.businessName ? `reachable — ${merchant.businessName} (${auth.environment})` : `reachable (${auth.environment})`
474
+ });
475
+ } catch (e) {
476
+ checks.push({ name: "API", ok: false, detail: message(e) });
300
477
  }
478
+ } else {
479
+ checks.push({ name: "API", ok: false, detail: "skipped because authentication failed" });
301
480
  }
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>`.");
481
+ return { ok: checks.every((check) => check.ok), checks };
482
+ }
483
+ function formatDoctorReport(report) {
484
+ const lines = report.checks.map((check) => `${check.ok ? "✓" : "✗"} ${check.name}: ${check.detail}`);
485
+ lines.push("");
486
+ lines.push(report.ok ? "All checks passed." : "Some checks failed.");
487
+ return lines.join(`
488
+ `);
303
489
  }
304
490
 
305
- // src/client.ts
306
- import { SquareClient, SquareEnvironment } from "square";
307
- function createClient(auth) {
308
- const environment = auth.environment === "production" ? SquareEnvironment.Production : SquareEnvironment.Sandbox;
309
- return new SquareClient({
310
- token: auth.token,
311
- environment
312
- });
491
+ // src/execute.ts
492
+ function isPage(value) {
493
+ if (value === null || typeof value !== "object")
494
+ return false;
495
+ const v = value;
496
+ return Symbol.asyncIterator in value && typeof v["hasNextPage"] === "function" && "data" in v;
497
+ }
498
+ async function* iteratePages(firstPage, options) {
499
+ const { maxItems, maxPages } = options;
500
+ let page = firstPage;
501
+ let pages = 1;
502
+ let items = 0;
503
+ while (true) {
504
+ for (const item of page.data) {
505
+ if (maxItems !== undefined && items >= maxItems)
506
+ return;
507
+ yield item;
508
+ items++;
509
+ }
510
+ if (!page.hasNextPage())
511
+ return;
512
+ if (maxPages !== undefined && pages >= maxPages)
513
+ return;
514
+ if (maxItems !== undefined && items >= maxItems)
515
+ return;
516
+ page = await page.getNextPage();
517
+ pages++;
518
+ }
519
+ }
520
+ async function collectPages(firstPage, options) {
521
+ const results = [];
522
+ for await (const item of iteratePages(firstPage, options))
523
+ results.push(item);
524
+ return results;
525
+ }
526
+ function pageEnvelope(page) {
527
+ const response = page.response;
528
+ if (response !== null && typeof response === "object")
529
+ return response;
530
+ return { data: page.data };
531
+ }
532
+ function execute(method, request, options) {
533
+ if (options.rawPage) {
534
+ return (async () => {
535
+ const result = await Promise.resolve(method.fn(request));
536
+ return isPage(result) ? pageEnvelope(result) : result;
537
+ })();
538
+ }
539
+ if (options.stream) {
540
+ return async function* () {
541
+ const result = await Promise.resolve(method.fn(request));
542
+ if (isPage(result)) {
543
+ yield* iteratePages(result, options);
544
+ } else {
545
+ yield result;
546
+ }
547
+ }();
548
+ }
549
+ return (async () => {
550
+ const result = await Promise.resolve(method.fn(request));
551
+ if (isPage(result)) {
552
+ return collectPages(result, options);
553
+ }
554
+ return result;
555
+ })();
556
+ }
557
+
558
+ // src/help.ts
559
+ var GLOBAL_FLAGS2 = `
560
+ Global flags:
561
+ --profile <name> Use a named profile from config
562
+ --token <token> Square API access token
563
+ --env <environment> "sandbox" or "production" (default: sandbox)
564
+ --json <json> JSON body for the request (@file or - for stdin)
565
+ --json-output Output as compact JSON (no pretty print)
566
+ --stream Stream pageable results as NDJSON (one item per line)
567
+ --raw-page Return a single raw page (with its cursor) instead of auto-paging
568
+ --dry-run Print the request that would be sent, without sending it
569
+ --max-items <n> Stop paging after n items
570
+ --max-pages <n> Stop paging after n pages
571
+ --timeout <seconds> HTTP timeout per request (SDK default if omitted)
572
+ --retry <n> Retry failed requests n times (SDK default: 2; 0 disables)
573
+ --select <a,b.c> Keep only these fields in the output
574
+ --table Render a list result as an aligned table
575
+ --output <file> Write the result to a file instead of stdout
576
+ --yes Skip the confirmation for write calls in production
577
+ --verbose Print request diagnostics and full error details to stderr
578
+ --keychain Store/lookup the token in the OS keychain (config set)
579
+ --offline Skip the API check (doctor)
580
+ --version Print the CLI and Square SDK versions
581
+ --help Show this help message
582
+ `.trim();
583
+ function renderRootHelp(tree) {
584
+ const lines = [];
585
+ lines.push("Square SDK CLI");
586
+ lines.push("");
587
+ lines.push("Usage:");
588
+ lines.push(" square <namespace> <method> [--json <body>] [--field value] [flags]");
589
+ lines.push(" square config <subcommand> [args]");
590
+ lines.push("");
591
+ lines.push("Namespaces:");
592
+ const namespaces = [...tree.children.keys()].sort();
593
+ for (const ns of namespaces) {
594
+ lines.push(` ${ns}`);
595
+ }
596
+ lines.push("");
597
+ lines.push("Built-in commands:");
598
+ lines.push(" config set <profile> [--token <tok>|-] --env <env> Create/update a profile");
599
+ lines.push(" (omit --token to be prompted)");
600
+ lines.push(" config get <profile> Show profile (token masked)");
601
+ lines.push(" config list List profiles (* marks the default)");
602
+ lines.push(" config use <profile> Set default profile");
603
+ lines.push(" config remove <profile> Delete a profile");
604
+ lines.push(" whoami Show the merchant for the current token");
605
+ lines.push(" search <term> Find namespaces and methods by name");
606
+ lines.push(" completion <bash|zsh|fish> Print a shell completion script");
607
+ lines.push(" doctor Check config, auth and API reachability");
608
+ lines.push("");
609
+ lines.push(GLOBAL_FLAGS2);
610
+ return lines.join(`
611
+ `);
612
+ }
613
+ function renderNamespaceHelp(node, path2 = node.name) {
614
+ const lines = [];
615
+ lines.push(`Namespace: ${path2}`);
616
+ lines.push("");
617
+ if (node.children.size > 0) {
618
+ lines.push("Sub-namespaces:");
619
+ for (const [name] of node.children) {
620
+ lines.push(` ${path2} ${name}`);
621
+ }
622
+ lines.push("");
623
+ }
624
+ if (node.methods.size > 0) {
625
+ lines.push("Methods:");
626
+ for (const [name] of node.methods) {
627
+ lines.push(` ${path2} ${name}`);
628
+ }
629
+ lines.push("");
630
+ }
631
+ lines.push(GLOBAL_FLAGS2);
632
+ return lines.join(`
633
+ `);
634
+ }
635
+ function renderMethodHelp(namespaceName, methodName) {
636
+ const lines = [];
637
+ lines.push(`Method: ${namespaceName} ${methodName}`);
638
+ lines.push("");
639
+ lines.push("Usage:");
640
+ lines.push(` square ${namespaceName} ${methodName} [options]`);
641
+ lines.push("");
642
+ lines.push("Request options:");
643
+ lines.push(" --json '<json>' Full request body as JSON");
644
+ lines.push(" --<field.path> <value> Set a field in the request by dotted path");
645
+ lines.push(` e.g. --amountMoney.amount 100`);
646
+ lines.push(" --<field.path>:str <value> Same, but keep the value a string (no JSON coercion)");
647
+ lines.push(` e.g. --address.postalCode:str 94103`);
648
+ lines.push(" --<field.path>=<value> Same, for values that start with -- (e.g. --note=--hi)");
649
+ lines.push("");
650
+ lines.push("Always pass a request object (even if it is empty).");
651
+ lines.push("");
652
+ lines.push(GLOBAL_FLAGS2);
653
+ return lines.join(`
654
+ `);
313
655
  }
314
656
 
315
657
  // src/introspect.ts
@@ -375,12 +717,52 @@ function findNamespace(tree, segments) {
375
717
  }
376
718
  return current;
377
719
  }
720
+ function editDistance(a, b) {
721
+ if (a === b)
722
+ return 0;
723
+ const row = new Array(b.length + 1);
724
+ for (let j = 0;j <= b.length; j++)
725
+ row[j] = j;
726
+ for (let i = 1;i <= a.length; i++) {
727
+ let diagonal = row[0];
728
+ row[0] = i;
729
+ for (let j = 1;j <= b.length; j++) {
730
+ const previous = row[j];
731
+ row[j] = Math.min(previous + 1, row[j - 1] + 1, diagonal + (a[i - 1] === b[j - 1] ? 0 : 1));
732
+ diagonal = previous;
733
+ }
734
+ }
735
+ return row[b.length];
736
+ }
737
+ function suggestToken(token, candidates) {
738
+ const needle = token.toLowerCase();
739
+ if (!needle)
740
+ return;
741
+ const maxDistance = needle.length <= 4 ? 1 : 2;
742
+ let best;
743
+ for (const candidate of candidates) {
744
+ const name = candidate.toLowerCase();
745
+ let score;
746
+ if (name === needle)
747
+ score = 0;
748
+ else if (needle.length >= 3 && name.startsWith(needle))
749
+ score = 1;
750
+ else {
751
+ const distance = editDistance(needle, name);
752
+ if (distance <= maxDistance)
753
+ score = 10 + distance;
754
+ }
755
+ if (score === undefined)
756
+ continue;
757
+ if (!best || score < best.score || score === best.score && candidate < best.name) {
758
+ best = { name: candidate, score };
759
+ }
760
+ }
761
+ return best?.name;
762
+ }
378
763
  function resolvePath(tree, segments) {
379
764
  if (segments.length === 0) {
380
- const validTokens = [
381
- ...tree.children.keys(),
382
- ...tree.methods.keys()
383
- ];
765
+ const validTokens = [...tree.children.keys(), ...tree.methods.keys()];
384
766
  return { error: "No path provided. Expected: <namespace> <method>", validTokens };
385
767
  }
386
768
  let current = tree;
@@ -389,8 +771,9 @@ function resolvePath(tree, segments) {
389
771
  const child = current.children.get(seg);
390
772
  if (!child) {
391
773
  const validTokens = [...current.children.keys()];
774
+ const hint = suggestToken(seg, validTokens);
392
775
  return {
393
- error: `Unknown namespace "${seg}". Valid options: ${validTokens.join(", ")}`,
776
+ error: hint ? `Unknown namespace "${seg}". Did you mean "${hint}"?` : `Unknown namespace "${seg}". Valid options: ${validTokens.join(", ")}`,
394
777
  validTokens
395
778
  };
396
779
  }
@@ -399,18 +782,16 @@ function resolvePath(tree, segments) {
399
782
  const methodName = segments[segments.length - 1];
400
783
  const method = current.methods.get(methodName);
401
784
  if (!method) {
402
- const validTokens = [
403
- ...current.methods.keys(),
404
- ...current.children.keys()
405
- ];
785
+ const validTokens = [...current.methods.keys(), ...current.children.keys()];
786
+ const hint = suggestToken(methodName, validTokens);
406
787
  if (current === tree) {
407
788
  return {
408
- error: `Unknown namespace "${methodName}". Valid options: ${validTokens.join(", ")}`,
789
+ error: hint ? `Unknown namespace "${methodName}". Did you mean "${hint}"?` : `Unknown namespace "${methodName}". Valid options: ${validTokens.join(", ")}`,
409
790
  validTokens
410
791
  };
411
792
  }
412
793
  return {
413
- error: `Unknown method "${methodName}" on namespace "${current.name}". Valid: ${validTokens.join(", ")}`,
794
+ error: hint ? `Unknown method "${methodName}" on namespace "${current.name}". Did you mean "${hint}"?` : `Unknown method "${methodName}" on namespace "${current.name}". Valid: ${validTokens.join(", ")}`,
414
795
  validTokens
415
796
  };
416
797
  }
@@ -420,60 +801,257 @@ var READ_ONLY_PREFIX = /^(get|list|search|retrieve|batchGet|bulkRetrieve|calcula
420
801
  function isReadOnlyMethod(name) {
421
802
  return READ_ONLY_PREFIX.test(name);
422
803
  }
804
+ function bindMethod(client, namespaceSegments, methodName) {
805
+ let target = client;
806
+ for (const segment of namespaceSegments) {
807
+ const next = target?.[segment];
808
+ if (next === null || typeof next !== "object")
809
+ return;
810
+ target = next;
811
+ }
812
+ const owner = target;
813
+ const fn = owner[methodName];
814
+ if (typeof fn !== "function")
815
+ return;
816
+ return {
817
+ name: methodName,
818
+ arity: fn.length,
819
+ fn: (...args) => owner[methodName].apply(owner, args)
820
+ };
821
+ }
822
+ function searchTree(tree, term, limit = 100) {
823
+ const needle = term.trim().toLowerCase();
824
+ if (!needle)
825
+ return [];
826
+ const matchPath = needle.includes(" ");
827
+ const matches = [];
828
+ const walk = (node, prefix) => {
829
+ for (const [name, child] of node.children) {
830
+ const path2 = [...prefix, name];
831
+ const pathText = path2.join(" ").toLowerCase();
832
+ if (matchPath ? pathText.includes(needle) : name.toLowerCase().includes(needle)) {
833
+ matches.push({ path: path2.join(" "), kind: "namespace" });
834
+ }
835
+ walk(child, path2);
836
+ }
837
+ for (const name of node.methods.keys()) {
838
+ const pathText = [...prefix, name].join(" ").toLowerCase();
839
+ if (matchPath ? pathText.includes(needle) : name.toLowerCase().includes(needle)) {
840
+ matches.push({ path: [...prefix, name].join(" "), kind: "method" });
841
+ }
842
+ }
843
+ };
844
+ walk(tree, []);
845
+ const rank = (match) => {
846
+ const path2 = match.path.toLowerCase();
847
+ if (path2 === needle)
848
+ return 0;
849
+ const last = path2.split(" ").pop();
850
+ if (last === needle)
851
+ return 1;
852
+ if (last.startsWith(needle))
853
+ return 2;
854
+ if (path2.startsWith(needle))
855
+ return 3;
856
+ return 4;
857
+ };
858
+ return matches.sort((a, b) => rank(a) - rank(b) || a.path.localeCompare(b.path)).slice(0, limit);
859
+ }
423
860
 
424
- // src/execute.ts
425
- function isPage(value) {
426
- if (value === null || typeof value !== "object")
427
- return false;
428
- const v = value;
429
- return Symbol.asyncIterator in value && typeof v["hasNextPage"] === "function" && "data" in v;
861
+ // src/keychain.ts
862
+ import { spawnSync } from "node:child_process";
863
+ var SERVICE = "square-sdk-cli";
864
+ var defaultRunner = (cmd, input) => {
865
+ const result = spawnSync(cmd[0], cmd.slice(1), { input, encoding: "utf8" });
866
+ return {
867
+ status: result.status ?? 1,
868
+ stdout: result.stdout ?? "",
869
+ stderr: result.stderr ?? result.error?.message ?? ""
870
+ };
871
+ };
872
+ function failure(tool, result) {
873
+ const detail = result.stderr.trim() || `exit code ${result.status}`;
874
+ return new Error(`${tool} failed: ${detail}`);
430
875
  }
431
- async function* iteratePages(firstPage, options) {
432
- const { maxItems, maxPages } = options;
433
- let page = firstPage;
434
- let pages = 1;
435
- let items = 0;
436
- while (true) {
437
- for (const item of page.data) {
438
- if (maxItems !== undefined && items >= maxItems)
439
- return;
440
- yield item;
441
- items++;
876
+ function createKeychain(platform = process.platform, run = defaultRunner) {
877
+ if (platform === "darwin") {
878
+ return {
879
+ available: () => true,
880
+ set(profile, token) {
881
+ const result = run([
882
+ "security",
883
+ "add-generic-password",
884
+ "-U",
885
+ "-a",
886
+ profile,
887
+ "-s",
888
+ SERVICE,
889
+ "-w",
890
+ token
891
+ ]);
892
+ if (result.status !== 0)
893
+ throw failure("security", result);
894
+ },
895
+ get(profile) {
896
+ const result = run([
897
+ "security",
898
+ "find-generic-password",
899
+ "-a",
900
+ profile,
901
+ "-s",
902
+ SERVICE,
903
+ "-w"
904
+ ]);
905
+ return result.status === 0 ? result.stdout.trim() : undefined;
906
+ },
907
+ delete(profile) {
908
+ run(["security", "delete-generic-password", "-a", profile, "-s", SERVICE]);
909
+ }
910
+ };
911
+ }
912
+ if (platform === "linux") {
913
+ return {
914
+ available: () => run(["which", "secret-tool"]).status === 0,
915
+ set(profile, token) {
916
+ const result = run([
917
+ "secret-tool",
918
+ "store",
919
+ "--label",
920
+ `Square CLI (${profile})`,
921
+ "service",
922
+ SERVICE,
923
+ "profile",
924
+ profile
925
+ ], token);
926
+ if (result.status !== 0)
927
+ throw failure("secret-tool", result);
928
+ },
929
+ get(profile) {
930
+ const result = run(["secret-tool", "lookup", "service", SERVICE, "profile", profile]);
931
+ return result.status === 0 ? result.stdout.trim() || undefined : undefined;
932
+ },
933
+ delete(profile) {
934
+ run(["secret-tool", "clear", "service", SERVICE, "profile", profile]);
935
+ }
936
+ };
937
+ }
938
+ const unsupported = () => {
939
+ throw new Error(`The OS keychain is not supported on ${platform}. Store the token in the config file instead (omit --keychain).`);
940
+ };
941
+ return {
942
+ available: () => false,
943
+ set: unsupported,
944
+ get: () => {
945
+ return;
946
+ },
947
+ delete: unsupported
948
+ };
949
+ }
950
+
951
+ // src/merge.ts
952
+ import { randomUUID as randomUUID2 } from "crypto";
953
+ import * as fs from "fs";
954
+ var STRING_SUFFIX = ":str";
955
+ function coerce(value) {
956
+ try {
957
+ return JSON.parse(value);
958
+ } catch {
959
+ return value;
960
+ }
961
+ }
962
+ var FORBIDDEN_SEGMENTS = new Set(["__proto__", "constructor", "prototype"]);
963
+ function describeKind(value) {
964
+ if (Array.isArray(value))
965
+ return "an array";
966
+ switch (typeof value) {
967
+ case "string":
968
+ return "a string";
969
+ case "number":
970
+ return "a number";
971
+ case "boolean":
972
+ return "a boolean";
973
+ case "object":
974
+ return "an object";
975
+ default:
976
+ return `a ${typeof value}`;
977
+ }
978
+ }
979
+ function pathConflict(path2, prefix, existing, wantsArray) {
980
+ const expected = wantsArray ? "an array" : "an object";
981
+ return new Error(`Invalid field path "${path2}": "${prefix}" is already ${describeKind(existing)}, ` + `but the path needs ${expected} there. Pass the whole value with --json instead.`);
982
+ }
983
+ function deepSet(obj, path2, value) {
984
+ const segments = path2.split(".");
985
+ for (const seg of segments) {
986
+ if (FORBIDDEN_SEGMENTS.has(seg)) {
987
+ throw new Error(`Invalid field path "${path2}": "${seg}" is not allowed`);
988
+ }
989
+ }
990
+ let current = obj;
991
+ for (let i = 0;i < segments.length - 1; i++) {
992
+ const seg = segments[i];
993
+ const nextSeg = segments[i + 1];
994
+ const wantsArray = /^\d+$/.test(nextSeg);
995
+ const existing = current[seg];
996
+ if (existing === undefined || existing === null) {
997
+ current[seg] = wantsArray ? [] : {};
998
+ } else if (typeof existing !== "object") {
999
+ throw pathConflict(path2, segments.slice(0, i + 1).join("."), existing, wantsArray);
1000
+ } else if (wantsArray !== Array.isArray(existing)) {
1001
+ throw pathConflict(path2, segments.slice(0, i + 1).join("."), existing, wantsArray);
1002
+ }
1003
+ current = current[seg];
1004
+ }
1005
+ const lastSeg = segments[segments.length - 1];
1006
+ current[lastSeg] = value;
1007
+ }
1008
+ function buildRequest(jsonStr, fields) {
1009
+ let base = {};
1010
+ if (jsonStr !== undefined) {
1011
+ let parsed;
1012
+ try {
1013
+ parsed = JSON.parse(jsonStr);
1014
+ } catch (e) {
1015
+ const msg = e instanceof Error ? e.message : String(e);
1016
+ throw new Error(`Invalid JSON: ${msg}`);
1017
+ }
1018
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
1019
+ throw new Error("Invalid JSON: request body must be a JSON object");
1020
+ }
1021
+ base = parsed;
1022
+ }
1023
+ for (const field of fields) {
1024
+ if (field.path.endsWith(STRING_SUFFIX)) {
1025
+ deepSet(base, field.path.slice(0, -STRING_SUFFIX.length), field.value);
1026
+ } else {
1027
+ deepSet(base, field.path, coerce(field.value));
442
1028
  }
443
- if (!page.hasNextPage())
444
- return;
445
- if (maxPages !== undefined && pages >= maxPages)
446
- return;
447
- if (maxItems !== undefined && items >= maxItems)
448
- return;
449
- page = await page.getNextPage();
450
- pages++;
451
1029
  }
1030
+ return base;
452
1031
  }
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
- }
459
- function execute(method, request, options) {
460
- if (options.stream) {
461
- return async function* () {
462
- const result = await Promise.resolve(method.fn(request));
463
- if (isPage(result)) {
464
- yield* iteratePages(result, options);
465
- } else {
466
- yield result;
467
- }
468
- }();
469
- }
470
- return (async () => {
471
- const result = await Promise.resolve(method.fn(request));
472
- if (isPage(result)) {
473
- return collectPages(result, options);
1032
+ function readJsonArg(raw, readFile2 = (source) => fs.readFileSync(source, "utf8")) {
1033
+ if (raw === "-")
1034
+ return readFile2(0);
1035
+ if (raw.startsWith("@")) {
1036
+ const file = raw.slice(1);
1037
+ try {
1038
+ return readFile2(file);
1039
+ } catch (e) {
1040
+ const msg = e instanceof Error ? e.message : String(e);
1041
+ throw new Error(`Cannot read --json file "${file}": ${msg}`);
474
1042
  }
475
- return result;
476
- })();
1043
+ }
1044
+ return raw;
1045
+ }
1046
+ function ensureIdempotencyKey(request, methodName, newKey = randomUUID2) {
1047
+ if (/IdempotencyKey/.test(methodName))
1048
+ return;
1049
+ const body = request;
1050
+ if (body["idempotencyKey"] !== undefined)
1051
+ return;
1052
+ const key = newKey();
1053
+ body["idempotencyKey"] = key;
1054
+ return key;
477
1055
  }
478
1056
 
479
1057
  // src/output.ts
@@ -481,14 +1059,41 @@ import { SquareError } from "square";
481
1059
  function bigIntReplacer(_key, value) {
482
1060
  return typeof value === "bigint" ? value.toString() : value;
483
1061
  }
1062
+ function formatJson(value, raw = false) {
1063
+ return raw ? JSON.stringify(value, bigIntReplacer) : JSON.stringify(value, bigIntReplacer, 2);
1064
+ }
484
1065
  function print(value, options = {}) {
485
1066
  const write = options.writeFn ?? ((msg) => process.stdout.write(msg + `
486
1067
  `));
487
- if (options.raw) {
488
- write(JSON.stringify(value, bigIntReplacer));
489
- } else {
490
- write(JSON.stringify(value, bigIntReplacer, 2));
1068
+ write(formatJson(value, options.raw === true));
1069
+ }
1070
+ var REQUEST_ID_HEADERS = [
1071
+ "request-id",
1072
+ "x-request-id",
1073
+ "square-request-id",
1074
+ "x-square-request-id"
1075
+ ];
1076
+ function getRequestId(err) {
1077
+ const body = err.body;
1078
+ for (const key of ["request_id", "requestId"]) {
1079
+ const value = body?.[key];
1080
+ if (typeof value === "string" && value)
1081
+ return value;
491
1082
  }
1083
+ const headers = err.rawResponse;
1084
+ if (headers?.headers?.get) {
1085
+ for (const name of REQUEST_ID_HEADERS) {
1086
+ const value = headers.headers.get(name);
1087
+ if (value)
1088
+ return value;
1089
+ }
1090
+ }
1091
+ return;
1092
+ }
1093
+ function getTraceId(err) {
1094
+ const headers = err.rawResponse;
1095
+ const value = headers?.headers?.get?.("cf-ray");
1096
+ return value || undefined;
492
1097
  }
493
1098
  var STATUS_REASON = {
494
1099
  400: "Bad Request",
@@ -536,11 +1141,18 @@ function camelize(field) {
536
1141
  function renderError(err, options = {}) {
537
1142
  const write = options.writeFn ?? ((msg) => process.stderr.write(msg + `
538
1143
  `));
1144
+ if (options.json) {
1145
+ write(JSON.stringify(errorPayload(err, options.verbose === true), bigIntReplacer));
1146
+ return 1;
1147
+ }
539
1148
  if (err instanceof SquareError) {
540
1149
  const status = err.statusCode;
541
1150
  const reason = status ? STATUS_REASON[status] : undefined;
542
1151
  const statusText = status ? `HTTP ${status}${reason ? " " + reason : ""}` : "request failed";
543
1152
  write(`✗ Square API request failed (${statusText})`);
1153
+ const requestId = getRequestId(err);
1154
+ if (requestId)
1155
+ write(` request id: ${requestId}`);
544
1156
  const errors = err.errors ?? [];
545
1157
  for (const e of errors) {
546
1158
  write("");
@@ -552,168 +1164,249 @@ function renderError(err, options = {}) {
552
1164
  if (hint)
553
1165
  write(` hint: ${hint}`);
554
1166
  }
1167
+ if (options.verbose) {
1168
+ const traceId = getTraceId(err);
1169
+ if (traceId)
1170
+ write(` trace id: ${traceId}`);
1171
+ if (err.body !== undefined) {
1172
+ write("");
1173
+ write(" body:");
1174
+ for (const line of prettyJson(err.body))
1175
+ write(` ${line}`);
1176
+ }
1177
+ if (err.cause !== undefined) {
1178
+ write(` cause: ${err.cause instanceof Error ? err.cause.message : String(err.cause)}`);
1179
+ }
1180
+ }
555
1181
  } else if (err instanceof Error) {
556
1182
  write(`✗ Error: ${err.message}`);
1183
+ if (options.verbose && err.stack) {
1184
+ for (const line of err.stack.split(`
1185
+ `).slice(1))
1186
+ write(` ${line.trim()}`);
1187
+ }
557
1188
  } else {
558
1189
  write(`✗ Error: ${String(err)}`);
559
1190
  }
560
1191
  return 1;
561
1192
  }
562
-
563
- // src/help.ts
564
- var GLOBAL_FLAGS = `
565
- Global flags:
566
- --profile <name> Use a named profile from config
567
- --token <token> Square API access token
568
- --env <environment> "sandbox" or "production" (default: sandbox)
569
- --json <json> JSON body for the request (@file or - for stdin)
570
- --json-output Output as compact JSON (no pretty print)
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
576
- --help Show this help message
577
- `.trim();
578
- function renderRootHelp(tree) {
579
- const lines = [];
580
- lines.push("Square SDK CLI");
581
- lines.push("");
582
- lines.push("Usage:");
583
- lines.push(" square <namespace> <method> [--json <body>] [--field value] [flags]");
584
- lines.push(" square config <subcommand> [args]");
585
- lines.push("");
586
- lines.push("Namespaces:");
587
- const namespaces = [...tree.children.keys()].sort();
588
- for (const ns of namespaces) {
589
- lines.push(` ${ns}`);
590
- }
591
- lines.push("");
592
- lines.push("Built-in commands:");
593
- lines.push(" config set <profile> [--token <tok>|-] --env <env> Create/update a profile");
594
- lines.push(" (omit --token to be prompted)");
595
- lines.push(" config get <profile> Show profile (token masked)");
596
- lines.push(" config list List profiles (* marks the default)");
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");
600
- lines.push("");
601
- lines.push(GLOBAL_FLAGS);
602
- return lines.join(`
1193
+ function prettyJson(value) {
1194
+ try {
1195
+ return JSON.stringify(value, bigIntReplacer, 2).split(`
603
1196
  `);
1197
+ } catch {
1198
+ return [String(value)];
1199
+ }
604
1200
  }
605
- function renderNamespaceHelp(node, path2 = node.name) {
606
- const lines = [];
607
- lines.push(`Namespace: ${path2}`);
608
- lines.push("");
609
- if (node.children.size > 0) {
610
- lines.push("Sub-namespaces:");
611
- for (const [name] of node.children) {
612
- lines.push(` ${path2} ${name}`);
613
- }
614
- lines.push("");
1201
+ function getPath(value, path2) {
1202
+ let current = value;
1203
+ for (const segment of path2.split(".")) {
1204
+ if (current === null || typeof current !== "object")
1205
+ return;
1206
+ current = current[segment];
615
1207
  }
616
- if (node.methods.size > 0) {
617
- lines.push("Methods:");
618
- for (const [name, method] of node.methods) {
619
- lines.push(` ${path2} ${name} (arity: ${method.arity})`);
1208
+ return current;
1209
+ }
1210
+ function setPath(target, path2, value) {
1211
+ const segments = path2.split(".");
1212
+ let current = target;
1213
+ for (let i = 0;i < segments.length - 1; i++) {
1214
+ const segment = segments[i];
1215
+ const next = current[segment];
1216
+ if (next === undefined || next === null || typeof next !== "object") {
1217
+ current[segment] = {};
620
1218
  }
621
- lines.push("");
1219
+ current = current[segment];
622
1220
  }
623
- lines.push(GLOBAL_FLAGS);
624
- return lines.join(`
625
- `);
1221
+ current[segments[segments.length - 1]] = value;
626
1222
  }
627
- function renderMethodHelp(namespaceName, methodName, arity) {
628
- const lines = [];
629
- lines.push(`Method: ${namespaceName} ${methodName}`);
630
- lines.push("");
631
- lines.push("Usage:");
632
- lines.push(` square ${namespaceName} ${methodName} [options]`);
633
- lines.push("");
634
- lines.push("Request options:");
635
- lines.push(" --json '<json>' Full request body as JSON");
636
- lines.push(" --<field.path> <value> Set a field in the request by dotted path");
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`);
640
- lines.push("");
641
- lines.push(`Note: arity hint = ${arity} (optional params may not be counted)`);
642
- lines.push(" Always pass a request object (even if empty).");
643
- lines.push("");
644
- lines.push(GLOBAL_FLAGS);
645
- return lines.join(`
1223
+ function selectFields(value, paths) {
1224
+ const pick = (item) => {
1225
+ const out = {};
1226
+ for (const path2 of paths)
1227
+ setPath(out, path2, getPath(item, path2));
1228
+ return out;
1229
+ };
1230
+ return Array.isArray(value) ? value.map(pick) : pick(value);
1231
+ }
1232
+ function renderTable(rows, columns) {
1233
+ const keys = columns && columns.length > 0 ? columns : inferColumns(rows[0]);
1234
+ if (keys.length === 0)
1235
+ return "";
1236
+ const cell = (row, key) => {
1237
+ const value = getPath(row, key);
1238
+ if (value === undefined || value === null)
1239
+ return "";
1240
+ return typeof value === "object" ? JSON.stringify(value, bigIntReplacer) : String(value);
1241
+ };
1242
+ const body = rows.map((row) => keys.map((key) => cell(row, key)));
1243
+ const widths = keys.map((key, i) => Math.max(key.length, ...body.map((cells) => cells[i].length)));
1244
+ const format = (cells) => cells.map((value, i) => value.padEnd(widths[i])).join(" ").trimEnd();
1245
+ return [format(keys), ...body.map(format)].join(`
646
1246
  `);
647
1247
  }
1248
+ function inferColumns(row) {
1249
+ if (row === null || typeof row !== "object" || Array.isArray(row))
1250
+ return [];
1251
+ return Object.keys(row);
1252
+ }
1253
+ function errorPayload(err, verbose) {
1254
+ if (err instanceof SquareError) {
1255
+ const payload2 = {
1256
+ error: "square_api",
1257
+ message: err.message,
1258
+ statusCode: err.statusCode,
1259
+ requestId: getRequestId(err),
1260
+ errors: (err.errors ?? []).map((e) => ({
1261
+ category: e.category,
1262
+ code: e.code,
1263
+ field: e.field,
1264
+ detail: e.detail
1265
+ }))
1266
+ };
1267
+ if (verbose && err.body !== undefined)
1268
+ payload2["body"] = err.body;
1269
+ if (verbose && err.cause !== undefined)
1270
+ payload2["cause"] = String(err.cause);
1271
+ if (verbose) {
1272
+ const traceId = getTraceId(err);
1273
+ if (traceId)
1274
+ payload2["traceId"] = traceId;
1275
+ }
1276
+ return payload2;
1277
+ }
1278
+ const payload = {
1279
+ error: "cli",
1280
+ message: err instanceof Error ? err.message : String(err)
1281
+ };
1282
+ if (verbose && err instanceof Error && err.stack)
1283
+ payload["stack"] = err.stack;
1284
+ return payload;
1285
+ }
648
1286
 
649
1287
  // 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(`
1288
+ import * as readline from "node:readline";
1289
+ function createPrompter({ stdin, stderr }) {
1290
+ return {
1291
+ isInteractive: () => Boolean(stdin.isTTY && stderr.isTTY),
1292
+ confirm: async (question) => {
1293
+ const rl = readline.createInterface({
1294
+ input: stdin,
1295
+ output: stderr,
1296
+ terminal: false
1297
+ });
1298
+ const answer = await new Promise((resolve) => rl.question(question, resolve));
1299
+ rl.close();
1300
+ return /^y(es)?$/i.test(answer.trim());
1301
+ },
1302
+ secret: (question) => new Promise((resolve, reject) => {
1303
+ let value = "";
1304
+ const finish = (err) => {
1305
+ stdin.off("data", onData);
1306
+ stdin.setRawMode?.(false);
1307
+ stdin.pause();
1308
+ stderr.write(`
670
1309
  `);
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 === `
1310
+ if (err)
1311
+ reject(err);
1312
+ else
1313
+ resolve(value);
1314
+ };
1315
+ const onData = (chunk) => {
1316
+ for (const ch of chunk) {
1317
+ if (ch === "\r" || ch === `
679
1318
  `)
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;
1319
+ return finish();
1320
+ if (ch === "\x03")
1321
+ return finish(new Error("Cancelled"));
1322
+ if (ch === "" || ch === "\b") {
1323
+ value = value.slice(0, -1);
1324
+ continue;
1325
+ }
1326
+ value += ch;
686
1327
  }
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
- });
1328
+ };
1329
+ stderr.write(question);
1330
+ stdin.setRawMode?.(true);
1331
+ stdin.setEncoding("utf8");
1332
+ stdin.resume();
1333
+ stdin.on("data", onData);
1334
+ }),
1335
+ readStdin: async () => {
1336
+ let data = "";
1337
+ stdin.setEncoding("utf8");
1338
+ for await (const chunk of stdin)
1339
+ data += chunk;
1340
+ return data;
1341
+ }
1342
+ };
1343
+ }
1344
+ var terminalPrompter = createPrompter({
1345
+ stdin: process.stdin,
1346
+ stderr: process.stderr
1347
+ });
1348
+
1349
+ // src/version.ts
1350
+ import { readFileSync as readFileSync2 } from "node:fs";
1351
+ import { createRequire } from "node:module";
1352
+ import { dirname as dirname2, join as join2 } from "node:path";
1353
+ import { fileURLToPath } from "node:url";
1354
+ var FALLBACK_CLI_VERSION = "0.0.0-dev";
1355
+ function readPackageVersion(dir) {
1356
+ try {
1357
+ const parsed = JSON.parse(readFileSync2(join2(dir, "package.json"), "utf8"));
1358
+ return typeof parsed.version === "string" && parsed.version ? parsed.version : undefined;
1359
+ } catch {
1360
+ return;
1361
+ }
1362
+ }
1363
+ function resolveSdkVersion(packageRoot) {
1364
+ try {
1365
+ const entry = createRequire(import.meta.url).resolve("square");
1366
+ const version = readPackageVersion(dirname2(entry));
1367
+ if (version)
1368
+ return version;
1369
+ } catch {}
1370
+ return readPackageVersion(join2(packageRoot, "node_modules", "square"));
1371
+ }
1372
+ function getVersions() {
1373
+ const packageRoot = dirname2(dirname2(fileURLToPath(import.meta.url)));
1374
+ return {
1375
+ cli: readPackageVersion(packageRoot) ?? FALLBACK_CLI_VERSION,
1376
+ sdk: resolveSdkVersion(packageRoot)
1377
+ };
696
1378
  }
697
- function readStdin() {
698
- return fs3.readFileSync(0, "utf8");
1379
+ function formatVersionLine(versions) {
1380
+ return versions.sdk ? `square-sdk-cli ${versions.cli} (Square SDK ${versions.sdk})` : `square-sdk-cli ${versions.cli}`;
699
1381
  }
700
- var terminalPrompter = { isInteractive, confirm, secret, readStdin };
701
1382
 
702
1383
  // src/cli.ts
703
1384
  var defaultDeps = {
704
1385
  createClient,
705
- prompter: terminalPrompter
1386
+ prompter: terminalPrompter,
1387
+ keychain: createKeychain()
706
1388
  };
707
- async function run(argv, deps = defaultDeps, stdoutWrite, stderrWrite) {
708
- const stdout = stdoutWrite ?? ((msg) => process.stdout.write(msg + `
1389
+ async function run(argv, options = {}) {
1390
+ const deps = options.deps ?? defaultDeps;
1391
+ const stdout = options.stdout ?? ((msg) => process.stdout.write(msg + `
709
1392
  `));
710
- const stderr = stderrWrite ?? ((msg) => process.stderr.write(msg + `
1393
+ const stderr = options.stderr ?? ((msg) => process.stderr.write(msg + `
711
1394
  `));
712
1395
  const prompter = deps.prompter ?? terminalPrompter;
1396
+ const keychain = deps.keychain ?? createKeychain();
713
1397
  const parsed = parseArgs(argv);
714
1398
  const { positionals, flags, fields } = parsed;
1399
+ const jsonOutput = flags.jsonOutput === true;
1400
+ if (flags.version) {
1401
+ if (flags.jsonOutput) {
1402
+ stdout(JSON.stringify(getVersions()));
1403
+ } else {
1404
+ stdout(formatVersionLine(getVersions()));
1405
+ }
1406
+ return 0;
1407
+ }
715
1408
  if (positionals[0] === "config") {
716
- return runConfigCommand(positionals.slice(1), flags, prompter, stdout, stderr);
1409
+ return runConfigCommand(positionals.slice(1), flags, prompter, keychain, stdout, stderr);
717
1410
  }
718
1411
  if (positionals[0] === "whoami") {
719
1412
  if (flags.help) {
@@ -722,9 +1415,69 @@ async function run(argv, deps = defaultDeps, stdoutWrite, stderrWrite) {
722
1415
  Show the merchant, environment, and token source in use.`);
723
1416
  return 0;
724
1417
  }
725
- return runWhoami(deps, flags, stdout, stderr);
1418
+ return runWhoami(deps, flags, keychain, stdout, stderr);
726
1419
  }
727
1420
  const shapeTree = buildTree(deps.createClient({ token: "dummy", environment: "sandbox" }));
1421
+ if (positionals[0] === "completion") {
1422
+ if (flags.help) {
1423
+ stdout(`Usage: square completion <bash|zsh|fish>
1424
+
1425
+ Print a completion script for your shell, e.g.
1426
+ square completion zsh > ~/.zsh/completions/_square`);
1427
+ return 0;
1428
+ }
1429
+ const shell = positionals[1];
1430
+ if (!shell) {
1431
+ stderr("Usage: square completion <bash|zsh|fish>");
1432
+ return 1;
1433
+ }
1434
+ if (!SUPPORTED_SHELLS.includes(shell)) {
1435
+ stderr(`Error: Unknown shell "${shell}". Expected bash, zsh, or fish.`);
1436
+ return 1;
1437
+ }
1438
+ stdout(renderCompletion(shell, shapeTree));
1439
+ return 0;
1440
+ }
1441
+ if (positionals[0] === "doctor") {
1442
+ if (flags.help) {
1443
+ stdout(`Usage: square doctor [--offline] [--profile <name>] [--json-output]
1444
+
1445
+ Check runtime, config file, credentials, keychain and API reachability.`);
1446
+ return 0;
1447
+ }
1448
+ return runDoctorCommand(deps, flags, keychain, stdout, stderr);
1449
+ }
1450
+ if (positionals[0] === "search") {
1451
+ if (flags.help) {
1452
+ stdout(`Usage: square search <term>
1453
+
1454
+ List namespaces, methods and built-in commands whose name contains <term>.
1455
+ Quote multi-word terms to match a path, e.g. square search "terminal actions".`);
1456
+ return 0;
1457
+ }
1458
+ const term = positionals.slice(1).join(" ");
1459
+ if (!term.trim()) {
1460
+ stderr("Usage: square search <term>");
1461
+ return 1;
1462
+ }
1463
+ const limit = 100;
1464
+ const needle = term.trim().toLowerCase();
1465
+ const builtinMatches = ROOT_COMMANDS.filter((name) => name.includes(needle)).map((name) => ({
1466
+ path: name,
1467
+ kind: "namespace"
1468
+ }));
1469
+ const matches = [...builtinMatches, ...searchTree(shapeTree, term, limit)].slice(0, limit);
1470
+ if (matches.length === 0) {
1471
+ stdout(`No matches for "${term}".`);
1472
+ return 0;
1473
+ }
1474
+ for (const match of matches)
1475
+ stdout(match.path);
1476
+ if (matches.length === limit) {
1477
+ stderr(`Showing the first ${limit} matches. Use a more specific term.`);
1478
+ }
1479
+ return 0;
1480
+ }
728
1481
  if (positionals.length === 0) {
729
1482
  stdout(renderRootHelp(shapeTree));
730
1483
  return 0;
@@ -739,7 +1492,7 @@ Show the merchant, environment, and token source in use.`);
739
1492
  if ("error" in shapeResult) {
740
1493
  stdout(renderRootHelp(shapeTree));
741
1494
  } else {
742
- stdout(renderMethodHelp(positionals.slice(0, -1).join(" "), shapeResult.method.name, shapeResult.method.arity));
1495
+ stdout(renderMethodHelp(positionals.slice(0, -1).join(" "), shapeResult.method.name));
743
1496
  }
744
1497
  return 0;
745
1498
  }
@@ -747,35 +1500,62 @@ Show the merchant, environment, and token source in use.`);
747
1500
  stderr(`Error: ${shapeResult.error}`);
748
1501
  return 1;
749
1502
  }
1503
+ let clientOptions;
1504
+ try {
1505
+ clientOptions = {};
1506
+ const timeoutInSeconds = parseTimeout(flags.timeout);
1507
+ const maxRetries = parseRetries(flags.retry);
1508
+ if (timeoutInSeconds !== undefined)
1509
+ clientOptions.timeoutInSeconds = timeoutInSeconds;
1510
+ if (maxRetries !== undefined)
1511
+ clientOptions.maxRetries = maxRetries;
1512
+ } catch (e) {
1513
+ return renderError(e, { writeFn: stderr, json: jsonOutput });
1514
+ }
750
1515
  let auth;
751
1516
  try {
752
- auth = await resolveAuthFromFlags(flags);
1517
+ auth = await resolveAuthFromFlags(flags, keychain);
753
1518
  } catch (e) {
754
- return renderError(e, { writeFn: stderr });
1519
+ return renderError(e, { writeFn: stderr, json: jsonOutput });
755
1520
  }
756
- const resolveResult = resolvePath(buildTree(deps.createClient(auth)), positionals);
757
- if ("error" in resolveResult) {
758
- stderr(`Error: ${resolveResult.error}`);
1521
+ const method = bindMethod(deps.createClient(auth, clientOptions), positionals.slice(0, -1), positionals[positionals.length - 1]);
1522
+ if (!method) {
1523
+ stderr(`Error: Unknown method "${positionals.join(" ")}"`);
759
1524
  return 1;
760
1525
  }
761
1526
  let request;
762
1527
  let maxItems;
763
1528
  let maxPages;
1529
+ let selectPaths;
764
1530
  try {
765
1531
  maxItems = parseLimit(flags.maxItems, "--max-items");
766
1532
  maxPages = parseLimit(flags.maxPages, "--max-pages");
1533
+ selectPaths = parseSelect(flags.select);
1534
+ if (flags.rawPage && flags.stream) {
1535
+ throw new Error("--raw-page cannot be combined with --stream");
1536
+ }
1537
+ if (flags.table && flags.stream) {
1538
+ throw new Error("--table cannot be combined with --stream");
1539
+ }
1540
+ if (flags.table && flags.rawPage) {
1541
+ throw new Error("--table cannot be combined with --raw-page");
1542
+ }
1543
+ if (flags.table && jsonOutput) {
1544
+ throw new Error("--table cannot be combined with --json-output");
1545
+ }
1546
+ if (flags.output !== undefined && typeof flags.output !== "string") {
1547
+ throw new Error("--output requires a file path");
1548
+ }
767
1549
  if (flags.json !== undefined && typeof flags.json !== "string") {
768
1550
  throw new Error("--json requires a value: a JSON string, @file, or - for stdin");
769
1551
  }
770
1552
  request = buildRequest(flags.json === undefined ? undefined : readJsonArg(flags.json), fields);
771
1553
  } catch (e) {
772
- renderError(e, { writeFn: stderr });
773
- return 1;
1554
+ return renderError(e, { writeFn: stderr, json: jsonOutput });
774
1555
  }
775
- const raw = flags.jsonOutput === true;
776
- const methodName = resolveResult.method.name;
1556
+ const raw = jsonOutput;
1557
+ const methodName = method.name;
777
1558
  const readOnly = isReadOnlyMethod(methodName);
778
- const generatedKey = readOnly ? undefined : ensureIdempotencyKey(request, methodName);
779
1559
  if (flags.dryRun) {
780
1560
  print({
781
1561
  dryRun: true,
@@ -788,41 +1568,74 @@ Show the merchant, environment, and token source in use.`);
788
1568
  if (auth.environment === "production" && !readOnly && !flags.yes) {
789
1569
  const command = positionals.join(" ");
790
1570
  if (!prompter.isInteractive()) {
791
- stderr(`✗ Error: Refusing to run "${command}" against PRODUCTION without confirmation. Pass --yes to proceed.`);
792
- return 1;
1571
+ return renderError(new Error(`Refusing to run "${command}" against PRODUCTION without confirmation. Pass --yes to proceed.`), { writeFn: stderr, json: jsonOutput });
793
1572
  }
794
1573
  const ok = await prompter.confirm(`About to run "${command}" against PRODUCTION. Continue? [y/N] `);
795
1574
  if (!ok) {
796
- stderr("Aborted.");
797
- return 1;
1575
+ return renderError(new Error("Aborted."), { writeFn: stderr, json: jsonOutput });
798
1576
  }
799
1577
  }
1578
+ const generatedKey = readOnly ? undefined : ensureIdempotencyKey(request, methodName);
800
1579
  if (generatedKey)
801
1580
  stderr(`Using idempotencyKey ${generatedKey} (pass --idempotencyKey to retry safely)`);
1581
+ const verbose = flags.verbose === true;
1582
+ const streamMode = flags.stream === true;
1583
+ const startedAt = Date.now();
1584
+ if (verbose)
1585
+ stderr(`→ ${positionals.join(" ")} (${auth.environment}; auth: ${auth.source})`);
802
1586
  try {
803
- const streamMode = flags.stream === true;
804
- const result = execute(resolveResult.method, request, { stream: streamMode, maxItems, maxPages });
1587
+ const result = execute(method, request, {
1588
+ stream: streamMode,
1589
+ rawPage: flags.rawPage === true,
1590
+ maxItems,
1591
+ maxPages
1592
+ });
1593
+ const emit = createEmitter(typeof flags.output === "string" ? flags.output : undefined, stdout);
805
1594
  if (streamMode) {
1595
+ let count = 0;
806
1596
  for await (const item of result) {
807
- stdout(JSON.stringify(item, bigIntReplacer));
1597
+ const selected = selectPaths ? selectFields(item, selectPaths) : item;
1598
+ emit(JSON.stringify(selected, bigIntReplacer));
1599
+ count++;
808
1600
  }
1601
+ if (verbose)
1602
+ stderr(`← ${count} item${count === 1 ? "" : "s"} in ${Date.now() - startedAt} ms`);
809
1603
  } else {
810
- const value = await result;
811
- print(value, { raw, writeFn: stdout });
1604
+ let value = await result;
1605
+ if (selectPaths)
1606
+ value = selectFields(value, selectPaths);
1607
+ if (flags.table === true) {
1608
+ if (!Array.isArray(value)) {
1609
+ throw new Error("--table requires a list result");
1610
+ }
1611
+ emit(renderTable(value, selectPaths));
1612
+ } else {
1613
+ emit(formatJson(value, raw));
1614
+ }
1615
+ if (verbose)
1616
+ stderr(`← done in ${Date.now() - startedAt} ms`);
812
1617
  }
813
1618
  return 0;
814
1619
  } catch (e) {
815
- return renderError(e, { writeFn: stderr });
1620
+ return renderError(e, { writeFn: stderr, verbose, json: jsonOutput });
816
1621
  }
817
1622
  }
818
- async function resolveAuthFromFlags(flags) {
1623
+ async function resolveAuthFromFlags(flags, keychain) {
819
1624
  const config = await load();
820
1625
  const env = process.env;
1626
+ const tokenFromEnv = flags.token ?? env["SQUARE_ACCESS_TOKEN"];
1627
+ const name = flags.profile ?? (tokenFromEnv ? undefined : config.defaultProfile);
1628
+ const profile = name ? config.profiles[name] : undefined;
1629
+ if (name && profile?.keychain && !profile.token) {
1630
+ const token = keychain.get(name);
1631
+ if (token)
1632
+ profile.token = token;
1633
+ }
821
1634
  return resolveAuth({ profile: flags.profile, token: flags.token, env: flags.env }, env, config);
822
1635
  }
823
- async function runWhoami(deps, flags, stdout, stderr) {
1636
+ async function runWhoami(deps, flags, keychain, stdout, stderr) {
824
1637
  try {
825
- const auth = await resolveAuthFromFlags(flags);
1638
+ const auth = await resolveAuthFromFlags(flags, keychain);
826
1639
  const client = deps.createClient(auth);
827
1640
  const { merchant } = await client.merchants.get({ merchantId: "me" });
828
1641
  print({
@@ -839,10 +1652,24 @@ async function runWhoami(deps, flags, stdout, stderr) {
839
1652
  }, { raw: flags.jsonOutput === true, writeFn: stdout });
840
1653
  return 0;
841
1654
  } catch (e) {
842
- return renderError(e, { writeFn: stderr });
1655
+ return renderError(e, {
1656
+ writeFn: stderr,
1657
+ verbose: flags.verbose === true,
1658
+ json: flags.jsonOutput === true
1659
+ });
843
1660
  }
844
1661
  }
845
- async function runConfigCommand(args, flags, prompter, stdout, stderr) {
1662
+ async function runDoctorCommand(deps, flags, keychain, stdout, stderr) {
1663
+ const report = await runDoctor({
1664
+ createClient: (auth) => deps.createClient(auth),
1665
+ keychain,
1666
+ offline: flags.offline === true,
1667
+ resolveAuth: () => resolveAuthFromFlags(flags, keychain)
1668
+ });
1669
+ stdout(flags.jsonOutput === true ? JSON.stringify(report) : formatDoctorReport(report));
1670
+ return report.ok ? 0 : 1;
1671
+ }
1672
+ async function runConfigCommand(args, flags, prompter, keychain, stdout, stderr) {
846
1673
  const subcommand = args[0];
847
1674
  switch (subcommand) {
848
1675
  case "set": {
@@ -851,7 +1678,7 @@ async function runConfigCommand(args, flags, prompter, stdout, stderr) {
851
1678
  stderr("Usage: square config set <profile> --token <token> [--env <environment>]");
852
1679
  return 1;
853
1680
  }
854
- let environment = "sandbox";
1681
+ let environment;
855
1682
  try {
856
1683
  if (flags.env !== undefined)
857
1684
  environment = parseEnvironment(String(flags.env), "--env");
@@ -861,7 +1688,7 @@ async function runConfigCommand(args, flags, prompter, stdout, stderr) {
861
1688
  let token;
862
1689
  try {
863
1690
  if (flags.token === "-") {
864
- token = prompter.readStdin().trim();
1691
+ token = (await prompter.readStdin()).trim();
865
1692
  } else if (typeof flags.token === "string") {
866
1693
  token = flags.token;
867
1694
  } else if (prompter.isInteractive()) {
@@ -877,7 +1704,33 @@ async function runConfigCommand(args, flags, prompter, stdout, stderr) {
877
1704
  stderr("Error: token is empty");
878
1705
  return 1;
879
1706
  }
880
- await setProfile(profileName, { token, environment });
1707
+ const existing = await getProfile(profileName);
1708
+ if (flags.keychain) {
1709
+ if (!keychain.available()) {
1710
+ stderr(`Error: no supported keychain on this platform. Omit --keychain to store the token in ${getConfigPath()}.`);
1711
+ return 1;
1712
+ }
1713
+ try {
1714
+ keychain.set(profileName, token);
1715
+ } catch (e) {
1716
+ return renderError(e, { writeFn: stderr, json: flags.jsonOutput === true });
1717
+ }
1718
+ await putProfile(profileName, {
1719
+ environment: environment ?? existing?.environment ?? "sandbox",
1720
+ keychain: true
1721
+ });
1722
+ stdout(`Profile "${profileName}" saved (token in keychain).`);
1723
+ return 0;
1724
+ }
1725
+ if (existing?.keychain) {
1726
+ try {
1727
+ keychain.delete(profileName);
1728
+ } catch {}
1729
+ }
1730
+ await putProfile(profileName, {
1731
+ token,
1732
+ environment: environment ?? existing?.environment ?? "sandbox"
1733
+ });
881
1734
  stdout(`Profile "${profileName}" saved.`);
882
1735
  return 0;
883
1736
  }
@@ -892,7 +1745,7 @@ async function runConfigCommand(args, flags, prompter, stdout, stderr) {
892
1745
  stderr(`Profile "${profileName}" not found.`);
893
1746
  return 1;
894
1747
  }
895
- const maskedToken = maskToken(profile.token);
1748
+ const maskedToken = profile.keychain ? "(stored in keychain)" : maskToken(profile.token ?? "");
896
1749
  stdout(JSON.stringify({ ...profile, token: maskedToken }, null, 2));
897
1750
  return 0;
898
1751
  }
@@ -906,8 +1759,10 @@ async function runConfigCommand(args, flags, prompter, stdout, stderr) {
906
1759
  const width = Math.max(...names.map((n) => n.length));
907
1760
  stdout("Profiles:");
908
1761
  for (const name of names) {
1762
+ const profile = cfg.profiles[name];
909
1763
  const marker = name === cfg.defaultProfile ? "*" : " ";
910
- stdout(`${marker} ${name.padEnd(width)} ${cfg.profiles[name].environment}`);
1764
+ const suffix = profile.keychain ? " (keychain)" : "";
1765
+ stdout(`${marker} ${name.padEnd(width)} ${profile.environment}${suffix}`);
911
1766
  }
912
1767
  if (cfg.defaultProfile)
913
1768
  stdout(`
@@ -921,6 +1776,12 @@ async function runConfigCommand(args, flags, prompter, stdout, stderr) {
921
1776
  return 1;
922
1777
  }
923
1778
  try {
1779
+ const profile = await getProfile(profileName);
1780
+ if (profile?.keychain) {
1781
+ try {
1782
+ keychain.delete(profileName);
1783
+ } catch {}
1784
+ }
924
1785
  const wasDefault = await removeProfile(profileName);
925
1786
  stdout(`Profile "${profileName}" removed.${wasDefault ? " It was the default; no default is set now." : ""}`);
926
1787
  return 0;
@@ -957,12 +1818,74 @@ function parseLimit(value, flag) {
957
1818
  }
958
1819
  return n;
959
1820
  }
1821
+ function parseTimeout(value) {
1822
+ if (value === undefined)
1823
+ return;
1824
+ const n = Number(value);
1825
+ if (typeof value !== "string" || !Number.isFinite(n) || n <= 0) {
1826
+ throw new Error("--timeout must be a positive number of seconds");
1827
+ }
1828
+ return n;
1829
+ }
1830
+ function parseRetries(value) {
1831
+ if (value === undefined)
1832
+ return;
1833
+ const n = Number(value);
1834
+ if (typeof value !== "string" || !Number.isInteger(n) || n < 0) {
1835
+ throw new Error("--retry must be a non-negative integer (0 disables retries)");
1836
+ }
1837
+ return n;
1838
+ }
1839
+ function parseSelect(value) {
1840
+ if (value === undefined)
1841
+ return;
1842
+ if (typeof value !== "string") {
1843
+ throw new Error("--select requires a comma-separated list of fields");
1844
+ }
1845
+ const paths = value.split(",").map((path2) => path2.trim()).filter(Boolean);
1846
+ if (paths.length === 0) {
1847
+ throw new Error("--select requires at least one field path");
1848
+ }
1849
+ return paths;
1850
+ }
1851
+ function createEmitter(file, stdout) {
1852
+ if (!file)
1853
+ return (line) => stdout(line);
1854
+ writeFileSync(file, "");
1855
+ return (line) => appendFileSync(file, `${line}
1856
+ `);
1857
+ }
960
1858
  function maskToken(token) {
961
1859
  if (token.length <= 4)
962
1860
  return "****";
963
1861
  return "*".repeat(token.length - 4) + token.slice(-4);
964
1862
  }
965
1863
 
1864
+ // src/epipe.ts
1865
+ function guardBrokenPipe(streams, options = {}) {
1866
+ const exit = options.exit ?? ((code) => process.exit(code));
1867
+ const report = options.report ?? ((err) => {
1868
+ const msg = err instanceof Error ? err.message : String(err);
1869
+ try {
1870
+ process.stderr.write(`✗ Error: ${msg}
1871
+ `);
1872
+ } catch {}
1873
+ });
1874
+ for (const stream of streams) {
1875
+ stream.on("error", (err) => {
1876
+ const code = err?.code;
1877
+ if (code === "EPIPE") {
1878
+ exit(0);
1879
+ return;
1880
+ }
1881
+ report(err);
1882
+ exit(1);
1883
+ });
1884
+ }
1885
+ }
1886
+
966
1887
  // bin/square.ts
1888
+ guardBrokenPipe([process.stdout, process.stderr]);
967
1889
  var exitCode = await run(process.argv.slice(2));
968
- process.exit(exitCode);
1890
+ process.exitCode = exitCode;
1891
+ setTimeout(() => process.exit(exitCode), 2000).unref();