@assinafy/cli 2.4.0 → 2.4.2

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/cli.cjs CHANGED
@@ -9038,10 +9038,10 @@ var require_abort = __commonJS({
9038
9038
  "use strict";
9039
9039
  module2.exports = abort;
9040
9040
  function abort(state) {
9041
- Object.keys(state.jobs).forEach(clean2.bind(state));
9041
+ Object.keys(state.jobs).forEach(clean.bind(state));
9042
9042
  state.jobs = {};
9043
9043
  }
9044
- function clean2(key) {
9044
+ function clean(key) {
9045
9045
  if (typeof this.jobs[key] == "function") {
9046
9046
  this.jobs[key]();
9047
9047
  }
@@ -21206,6 +21206,19 @@ function cleanParams(params) {
21206
21206
  }
21207
21207
  return out;
21208
21208
  }
21209
+ function stripEmpty(body) {
21210
+ const out = {};
21211
+ for (const [key, value] of Object.entries(body)) {
21212
+ if (value !== void 0 && value !== null) {
21213
+ out[key] = value;
21214
+ }
21215
+ }
21216
+ return out;
21217
+ }
21218
+ function appendFilePart(form, data, contentType, fileName) {
21219
+ const view = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
21220
+ form.append("file", new Blob([view], { type: contentType }), fileName);
21221
+ }
21209
21222
  function publicRequestConfig(config = {}) {
21210
21223
  return {
21211
21224
  ...config,
@@ -21446,7 +21459,7 @@ function buildAssignmentPayload(payload, options = {}) {
21446
21459
  if (!options.skipDigitalCertificateStepValidation) {
21447
21460
  validateSigningSteps(normalisedSigners);
21448
21461
  }
21449
- return cleanParams({
21462
+ return stripEmpty({
21450
21463
  method: payload.method ?? "virtual",
21451
21464
  signers: normalisedSigners,
21452
21465
  message: payload.message,
@@ -21477,7 +21490,7 @@ function normaliseSignerRef(ref, options) {
21477
21490
  const input = ref;
21478
21491
  const id = input.id ?? input.signer_id;
21479
21492
  validateSignerOptions(input);
21480
- const normalised = cleanParams({
21493
+ const normalised = stripEmpty({
21481
21494
  id,
21482
21495
  verification_method: input.verification_method,
21483
21496
  notification_methods: input.notification_methods,
@@ -21676,6 +21689,7 @@ var AuthenticationResource = class extends BaseResource {
21676
21689
  var import_node_fs2 = require("fs");
21677
21690
  var import_node_path2 = __toESM(require("path"), 1);
21678
21691
  var MAX_UPLOAD_BYTES = 25 * 1024 * 1024;
21692
+ var DOCUMENT_SORTS = ["name", "-name", "updated_at", "-updated_at"];
21679
21693
  var READY_STATUSES = /* @__PURE__ */ new Set([
21680
21694
  "metadata_ready",
21681
21695
  "pending_signature",
@@ -21723,7 +21737,7 @@ var DocumentResource = class extends BaseResource {
21723
21737
  */
21724
21738
  async list(params = {}, accountId) {
21725
21739
  const id = this.accountId(accountId);
21726
- requireSort(params.sort, ["name", "-name", "updated_at", "-updated_at"]);
21740
+ requireSort(params.sort, DOCUMENT_SORTS);
21727
21741
  return this.callList(
21728
21742
  "Failed to list documents",
21729
21743
  () => this.http.get(`/accounts/${id}/documents`, {
@@ -21741,7 +21755,7 @@ var DocumentResource = class extends BaseResource {
21741
21755
  */
21742
21756
  async search(params = {}, accountId) {
21743
21757
  const id = this.accountId(accountId);
21744
- requireSort(params.sort, ["name", "-name", "updated_at", "-updated_at"]);
21758
+ requireSort(params.sort, DOCUMENT_SORTS);
21745
21759
  return this.callList(
21746
21760
  "Failed to search documents",
21747
21761
  () => this.http.get(`/accounts/${id}/documents/search`, {
@@ -22096,8 +22110,7 @@ function validateUpload(buffer, fileName) {
22096
22110
  }
22097
22111
  function buildUploadForm(buffer, fileName, name, metadata) {
22098
22112
  const form = new FormData();
22099
- const view = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
22100
- form.append("file", new Blob([view], { type: "application/pdf" }), fileName);
22113
+ appendFilePart(form, buffer, "application/pdf", fileName);
22101
22114
  form.append("name", name);
22102
22115
  if (metadata) {
22103
22116
  form.append("metadata", JSON.stringify(metadata));
@@ -22207,26 +22220,35 @@ var FieldsResource = class extends BaseResource {
22207
22220
  }
22208
22221
  };
22209
22222
  function validationConfig(signerAccessCode) {
22210
- return signerAccessCode ? signerAccessConfig(signerAccessCode) : void 0;
22223
+ if (signerAccessCode === void 0) return void 0;
22224
+ if (typeof signerAccessCode !== "string" || !signerAccessCode.trim()) {
22225
+ throw new ValidationError("signerAccessCode is required when supplied");
22226
+ }
22227
+ return signerAccessConfig(signerAccessCode);
22211
22228
  }
22212
22229
 
22213
22230
  // src/api/resources/oauth.ts
22214
22231
  var import_node_crypto = require("crypto");
22215
- var formRequestConfig = publicRequestConfig({
22216
- headers: { "Content-Type": "application/x-www-form-urlencoded" }
22217
- });
22232
+ function formRequestConfig() {
22233
+ return publicRequestConfig({
22234
+ headers: { "Content-Type": "application/x-www-form-urlencoded" }
22235
+ });
22236
+ }
22218
22237
  var OAuthResource = class extends BaseResource {
22219
22238
  /** `GET /.well-known/oauth-protected-resource` at the API origin, outside `/v1`. */
22220
22239
  async metadata() {
22221
- return this.call(
22222
- "Failed to discover OAuth resource",
22223
- () => this.http.get(
22240
+ return this.call("Failed to discover OAuth resource", () => {
22241
+ const baseURL = this.http.defaults.baseURL;
22242
+ if (!baseURL) {
22243
+ throw new ValidationError("A base URL is required to discover OAuth metadata");
22244
+ }
22245
+ return this.http.get(
22224
22246
  "/.well-known/oauth-protected-resource",
22225
22247
  publicRequestConfig({
22226
- baseURL: new URL(this.http.defaults.baseURL).origin
22248
+ baseURL: new URL(baseURL).origin
22227
22249
  })
22228
- )
22229
- );
22250
+ );
22251
+ });
22230
22252
  }
22231
22253
  /** Read RFC 8414 metadata from an HTTPS issuer and verify its issuer identity. */
22232
22254
  async discovery(issuer) {
@@ -22310,6 +22332,9 @@ var OAuthResource = class extends BaseResource {
22310
22332
  if (callback.searchParams.get("iss") !== request.issuer) {
22311
22333
  throw new ValidationError("OAuth issuer mismatch");
22312
22334
  }
22335
+ if (callback.searchParams.has("code") === callback.searchParams.has("error")) {
22336
+ throw new ValidationError("OAuth callback must contain exactly one of code or error");
22337
+ }
22313
22338
  if (callback.searchParams.has("error")) {
22314
22339
  const error = callback.searchParams.get("error");
22315
22340
  const oauthError = error.length > 0 && error.length <= 64 && !/[^a-z_]/.test(error) ? error : "unknown_error";
@@ -22350,7 +22375,7 @@ var OAuthResource = class extends BaseResource {
22350
22375
  }
22351
22376
  const tokens = await this.call(
22352
22377
  "OAuth token request failed",
22353
- () => this.http.post("/oauth/token", payload, formRequestConfig)
22378
+ () => this.http.post("/oauth/token", payload, formRequestConfig())
22354
22379
  );
22355
22380
  const next = tokens?.refresh_token;
22356
22381
  if (payload.grant_type === "refresh_token" && (typeof next !== "string" || !next.trim() || next === payload.refresh_token)) {
@@ -22371,7 +22396,7 @@ var OAuthResource = class extends BaseResource {
22371
22396
  }
22372
22397
  await this.call(
22373
22398
  "OAuth revocation failed",
22374
- () => this.http.post("/oauth/revoke", payload, formRequestConfig)
22399
+ () => this.http.post("/oauth/revoke", payload, formRequestConfig())
22375
22400
  );
22376
22401
  }
22377
22402
  /** `GET /oauth/userinfo` — flat OIDC claims; requires a bearer token with `openid`. */
@@ -22769,12 +22794,18 @@ var SignerResource = class extends BaseResource {
22769
22794
  requireEmail(email);
22770
22795
  try {
22771
22796
  const lower = email.toLowerCase();
22772
- for (let page = 1; ; page++) {
22797
+ for (let page = 1; page <= MAX_SEARCH_PAGES; page++) {
22773
22798
  const { data, meta } = await this.list({ search: email, per_page: 100, page }, accountId);
22774
22799
  const match = data.find((s) => (s.email ?? "").toLowerCase() === lower);
22775
22800
  if (match) return match;
22776
- if (!data.length || !meta?.last_page || page >= meta.last_page) return null;
22801
+ if (!data.length) return null;
22802
+ if (meta?.last_page !== void 0) {
22803
+ if (page >= meta.last_page) return null;
22804
+ } else if (data.length < 100) {
22805
+ return null;
22806
+ }
22777
22807
  }
22808
+ throw new ValidationError("Signer email search exceeded the maximum page count");
22778
22809
  } catch (err) {
22779
22810
  if (err instanceof ApiError && err.statusCode === 404) {
22780
22811
  return null;
@@ -22783,6 +22814,7 @@ var SignerResource = class extends BaseResource {
22783
22814
  }
22784
22815
  }
22785
22816
  };
22817
+ var MAX_SEARCH_PAGES = 100;
22786
22818
  function normaliseSignerPayload(payload, useGovernmentId = false) {
22787
22819
  const normalised = {
22788
22820
  full_name: payload.full_name,
@@ -22797,7 +22829,7 @@ function normaliseSignerPayload(payload, useGovernmentId = false) {
22797
22829
  if ("metadata" in payload && payload.metadata !== void 0) {
22798
22830
  normalised.metadata = payload.metadata;
22799
22831
  }
22800
- return cleanParams(normalised);
22832
+ return stripEmpty(normalised);
22801
22833
  }
22802
22834
 
22803
22835
  // src/api/resources/tags.ts
@@ -22818,7 +22850,7 @@ var TagResource = class extends BaseResource {
22818
22850
  const id = this.accountId(accountId);
22819
22851
  return this.call(
22820
22852
  "Failed to create tag",
22821
- () => this.http.post(`/accounts/${id}/tags`, cleanParams({ ...payload }))
22853
+ () => this.http.post(`/accounts/${id}/tags`, stripEmpty({ ...payload }))
22822
22854
  );
22823
22855
  }
22824
22856
  /**
@@ -23091,9 +23123,8 @@ var WorkspaceResource = class extends BaseResource {
23091
23123
  throw new ValidationError("Logo buffer is required");
23092
23124
  }
23093
23125
  const contentType = options.contentType ?? "image/png";
23094
- const view = new Uint8Array(logo.buffer, logo.byteOffset, logo.byteLength);
23095
23126
  const form = new FormData();
23096
- form.append("file", new Blob([view], { type: contentType }), options.fileName ?? "logo.png");
23127
+ appendFilePart(form, logo, contentType, options.fileName ?? "logo.png");
23097
23128
  return this.call(
23098
23129
  "Failed to upload workspace logo",
23099
23130
  () => this.http.post(`/accounts/${id}/logo`, form, {
@@ -23557,6 +23588,21 @@ function addSortableListOptions(command, description) {
23557
23588
  function addListOptions(command, sortDescription = "Sort by field") {
23558
23589
  return addSearchListOptions(command).option("--sort <field>", sortDescription);
23559
23590
  }
23591
+ function addDownloadOptions(command) {
23592
+ return command.option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists");
23593
+ }
23594
+ function addSignerRefOptions(command) {
23595
+ return command.addOption(
23596
+ new Option("--signer-ids <csv>", "Comma-separated signer IDs (required)").conflicts(
23597
+ "signers"
23598
+ )
23599
+ ).addOption(
23600
+ new Option(
23601
+ "--signers <json>",
23602
+ "JSON array of signer refs, with verification_method, step, \u2026 (required)"
23603
+ ).conflicts("signerIds")
23604
+ );
23605
+ }
23560
23606
 
23561
23607
  // src/lib/output.ts
23562
23608
  var import_picocolors = __toESM(require_picocolors(), 1);
@@ -23662,6 +23708,11 @@ function paginationFooter(result) {
23662
23708
  }
23663
23709
  return parts.length > 0 ? import_picocolors2.default.dim(parts.join(" \xB7 ")) : "";
23664
23710
  }
23711
+ function tableWithFooter(table, result) {
23712
+ const footer = paginationFooter(result);
23713
+ return footer ? `${table}
23714
+ ${footer}` : table;
23715
+ }
23665
23716
 
23666
23717
  // src/lib/config.ts
23667
23718
  var import_node_crypto3 = require("crypto");
@@ -23692,7 +23743,33 @@ function readConfigFile(options = {}) {
23692
23743
  }
23693
23744
  try {
23694
23745
  const parsed = JSON.parse((0, import_node_fs3.readFileSync)(file, "utf8"));
23695
- if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
23746
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
23747
+ if (parsed.default_profile !== void 0 && typeof parsed.default_profile !== "string") {
23748
+ throw new Error("Invalid default_profile");
23749
+ }
23750
+ if (parsed.profiles !== void 0) {
23751
+ if (!parsed.profiles || typeof parsed.profiles !== "object" || Array.isArray(parsed.profiles)) {
23752
+ throw new Error("Invalid profiles");
23753
+ }
23754
+ for (const profile of Object.values(parsed.profiles)) {
23755
+ if (!profile || typeof profile !== "object" || Array.isArray(profile)) {
23756
+ throw new Error("Invalid profile");
23757
+ }
23758
+ for (const key of [
23759
+ "api_key",
23760
+ "token",
23761
+ "account_id",
23762
+ "base_url",
23763
+ "webhook_secret"
23764
+ ]) {
23765
+ if (profile[key] !== void 0 && typeof profile[key] !== "string") {
23766
+ throw new Error("Invalid profile field");
23767
+ }
23768
+ }
23769
+ }
23770
+ }
23771
+ return parsed;
23772
+ }
23696
23773
  if (options.strict) {
23697
23774
  throw new CliError(`Config file at ${file} is not a JSON object; refusing to overwrite it.`);
23698
23775
  }
@@ -23704,10 +23781,12 @@ function readConfigFile(options = {}) {
23704
23781
  } catch (error) {
23705
23782
  if (error instanceof CliError) throw error;
23706
23783
  if (options.strict) {
23707
- throw new CliError(`Config file at ${file} is not valid JSON; refusing to overwrite it.`);
23784
+ throw new CliError(
23785
+ `Config file at ${file} has invalid JSON or field types; refusing to overwrite it.`
23786
+ );
23708
23787
  }
23709
23788
  process.stderr.write(
23710
- `${import_picocolors3.default.yellow("!")} Config file at ${sanitizeTerminalText(file)} is not valid JSON; ignoring it.
23789
+ `${import_picocolors3.default.yellow("!")} Config file at ${sanitizeTerminalText(file)} has invalid JSON or field types; ignoring it.
23711
23790
  `
23712
23791
  );
23713
23792
  return {};
@@ -23718,6 +23797,7 @@ function writeConfigFile(config) {
23718
23797
  if (!(0, import_node_fs3.existsSync)(dir)) {
23719
23798
  (0, import_node_fs3.mkdirSync)(dir, { recursive: true, mode: 448 });
23720
23799
  }
23800
+ if (process.platform !== "win32") (0, import_node_fs3.chmodSync)(dir, 448);
23721
23801
  const file = configPath();
23722
23802
  const tmp = `${file}.${(0, import_node_crypto3.randomUUID)()}.tmp`;
23723
23803
  try {
@@ -23740,13 +23820,13 @@ function resolveConfig2(globals) {
23740
23820
  const file = readConfigFile();
23741
23821
  const profileName = activeProfileName(globals, file);
23742
23822
  const profile = file.profiles?.[profileName] ?? {};
23743
- const pick = (flag, env, stored) => flag ?? env ?? stored;
23823
+ const pick = (flag, env, stored) => flag || env || stored || void 0;
23744
23824
  const baseUrl = pick(globals.baseUrl, process.env.ASSINAFY_BASE_URL, profile.base_url) ?? DEFAULT_BASE_URL2;
23745
23825
  const credentials = [
23746
23826
  { apiKey: globals.apiKey, token: globals.token },
23747
23827
  { apiKey: process.env.ASSINAFY_API_KEY, token: process.env.ASSINAFY_TOKEN },
23748
23828
  { apiKey: profile.api_key, token: profile.token }
23749
- ].find(({ apiKey, token }) => apiKey !== void 0 || token !== void 0);
23829
+ ].find(({ apiKey, token }) => apiKey || token);
23750
23830
  return {
23751
23831
  apiKey: credentials?.apiKey,
23752
23832
  token: credentials?.token,
@@ -24787,7 +24867,7 @@ async function withSpinner(message, config, task) {
24787
24867
  if (!useSpinner) {
24788
24868
  return task();
24789
24869
  }
24790
- const s = spinner();
24870
+ const s = spinner({ output: process.stderr });
24791
24871
  s.start(message);
24792
24872
  try {
24793
24873
  const result = await task();
@@ -24864,7 +24944,7 @@ function displayWidth(text2) {
24864
24944
  }
24865
24945
 
24866
24946
  // src/commands/assignments.ts
24867
- function resolveSigners(signersJson, signerIdsCsv, required2 = true) {
24947
+ function resolveAssignmentSignerRefs(signersJson, signerIdsCsv, required2 = true) {
24868
24948
  if (signersJson) {
24869
24949
  return parseJsonArray(signersJson, "--signers");
24870
24950
  }
@@ -24894,25 +24974,22 @@ var listCommand = addSortableListOptions(
24894
24974
  { header: "SIGNERS", value: (r2) => r2.signers?.length },
24895
24975
  { header: "EXPIRES", value: (r2) => r2.expires_at }
24896
24976
  ]);
24897
- const footer = paginationFooter(result);
24898
- return footer ? `${table}
24899
- ${footer}` : table;
24977
+ return tableWithFooter(table, result);
24900
24978
  });
24901
24979
  });
24902
24980
  });
24903
- var createCommand = new Command("create").description("Create a signing assignment for a document").argument("<documentId>", "Document ID").addOption(new Option("--signer-ids <csv>", "Comma-separated signer IDs").conflicts("signers")).addOption(
24904
- new Option(
24905
- "--signers <json>",
24906
- "JSON array of signer refs (with verification_method, step, \u2026)"
24907
- ).conflicts("signerIds")
24908
- ).option("--method <method>", "virtual or collect", "virtual").option("--message <message>", "Message shown to signers").option("--expires-at <iso8601>", "Expiration timestamp").option("--copy-receivers <csv>", "Comma-separated signer IDs to receive a copy of the document").option(
24981
+ var createCommand = addSignerRefOptions(
24982
+ new Command("create").description("Create a signing assignment for a document").argument("<documentId>", "Document ID")
24983
+ ).addOption(
24984
+ new Option("--method <method>", "virtual or collect").choices(["virtual", "collect"]).default("virtual")
24985
+ ).option("--message <message>", "Message shown to signers").option("--expires-at <iso8601>", "Expiration timestamp").option("--copy-receivers <csv>", "Comma-separated signer IDs to receive a copy of the document").option(
24909
24986
  "--entries <json>",
24910
24987
  `JSON array of field placement entries, required for --method collect (e.g. '[{"page_id":"p1","fields":[{"signer_id":"s1","field_id":"f1"}]}]')`
24911
24988
  ).action(async (documentId, opts, command) => {
24912
24989
  await runWithClient(command, async ({ client, config }) => {
24913
24990
  const payload = {
24914
24991
  method: opts.method,
24915
- signers: resolveSigners(opts.signers, opts.signerIds)
24992
+ signers: resolveAssignmentSignerRefs(opts.signers, opts.signerIds)
24916
24993
  };
24917
24994
  if (opts.message) payload.message = opts.message;
24918
24995
  if (opts.expiresAt) payload.expires_at = opts.expiresAt;
@@ -24939,7 +25016,11 @@ var createCommand = new Command("create").description("Create a signing assignme
24939
25016
  );
24940
25017
  });
24941
25018
  });
24942
- var estimateCostCommand = new Command("estimate-cost").description("Estimate the credit cost of an assignment").argument("<documentId>", "Document ID").addOption(new Option("--signer-ids <csv>", "Comma-separated signer IDs").conflicts("signers")).addOption(new Option("--signers <json>", "JSON array of signer refs").conflicts("signerIds")).option("--method <method>", "virtual or collect", "virtual").option(
25019
+ var estimateCostCommand = addSignerRefOptions(
25020
+ new Command("estimate-cost").description("Estimate the credit cost of an assignment").argument("<documentId>", "Document ID")
25021
+ ).addOption(
25022
+ new Option("--method <method>", "virtual or collect").choices(["virtual", "collect"]).default("virtual")
25023
+ ).option(
24943
25024
  "--entries <json>",
24944
25025
  "JSON array of field placement entries, required for --method collect"
24945
25026
  ).action(async (documentId, opts, command) => {
@@ -24947,7 +25028,7 @@ var estimateCostCommand = new Command("estimate-cost").description("Estimate the
24947
25028
  const method = opts.method;
24948
25029
  const payload = {
24949
25030
  method,
24950
- signers: resolveSigners(opts.signers, opts.signerIds, method !== "collect")
25031
+ signers: resolveAssignmentSignerRefs(opts.signers, opts.signerIds, true)
24951
25032
  };
24952
25033
  if (opts.entries) {
24953
25034
  payload.entries = parseJsonArray(opts.entries, "--entries");
@@ -25023,11 +25104,11 @@ var assignmentsCommand = new Command("assignments").description("Create and mana
25023
25104
 
25024
25105
  // src/lib/prompts.ts
25025
25106
  async function promptText(message, placeholder) {
25026
- const value = await text({ message, placeholder });
25107
+ const value = await text({ message, placeholder, output: process.stderr });
25027
25108
  return unwrap(value);
25028
25109
  }
25029
25110
  async function promptSecret(message) {
25030
- const value = await password({ message });
25111
+ const value = await password({ message, output: process.stderr });
25031
25112
  return unwrap(value);
25032
25113
  }
25033
25114
  async function confirmDestructive(message, force) {
@@ -25035,13 +25116,13 @@ async function confirmDestructive(message, force) {
25035
25116
  if (!process.stdin.isTTY) {
25036
25117
  throw new CliError("Refusing to proceed without confirmation. Re-run with --yes to confirm.");
25037
25118
  }
25038
- const value = await confirm({ message });
25119
+ const value = await confirm({ message, output: process.stderr });
25039
25120
  return unwrap(value);
25040
25121
  }
25041
25122
  function unwrap(value) {
25042
25123
  if (isCancel3(value)) {
25043
- cancel("Cancelled.");
25044
- process.exit(130);
25124
+ cancel("Cancelled.", { output: process.stderr });
25125
+ throw new CliError("Cancelled.", { exitCode: 130 });
25045
25126
  }
25046
25127
  return value;
25047
25128
  }
@@ -25074,7 +25155,9 @@ var loginCommand = new Command("login").description(
25074
25155
  );
25075
25156
  });
25076
25157
  });
25077
- var socialLoginCommand = new Command("social-login").description("Exchange a provider token for an Assinafy JWT (no existing credentials required)").requiredOption("--provider <provider>", "OAuth provider (e.g. google)").addOption(
25158
+ var socialLoginCommand = new Command("social-login").description("Exchange a provider token for an Assinafy JWT (no existing credentials required)").addOption(
25159
+ new Option("--provider <provider>", "OAuth provider").choices(["google"]).makeOptionMandatory()
25160
+ ).addOption(
25078
25161
  new Option("--provider-token <token>", "Provider token").env("ASSINAFY_PROVIDER_TOKEN").makeOptionMandatory()
25079
25162
  ).option("--accept-terms", "Accept the platform terms").action(async (opts, command) => {
25080
25163
  await runWithPublicClient(command, async ({ client, config }) => {
@@ -25323,24 +25406,181 @@ var pathCommand = new Command("path").description("Print the config file path").
25323
25406
  });
25324
25407
  var configCommand = new Command("config").description("Manage credentials, profiles, and settings").addCommand(setCommand).addCommand(getCommand).addCommand(listCommand2).addCommand(useCommand).addCommand(removeCommand).addCommand(pathCommand);
25325
25408
 
25326
- // src/commands/docs.ts
25409
+ // src/lib/oauth-browser.ts
25327
25410
  var import_node_child_process2 = require("child_process");
25411
+ var import_node_crypto4 = require("crypto");
25412
+ var import_node_events2 = require("events");
25413
+ var import_node_http = require("http");
25414
+ var CLI_OAUTH_REDIRECT_URI = "https://integrations.assinafy.com.br/assinafy-cli/oauth-callback";
25415
+ var clearHistory = "history.replaceState(null, '', '/');";
25416
+ var brandOrigin = "https://integrations.assinafy.com.br";
25417
+ var callbackCopy = {
25418
+ received: {
25419
+ heading: "Volte ao terminal.",
25420
+ status: "A resposta de autoriza\xE7\xE3o foi recebida. Confira no terminal se a conex\xE3o foi conclu\xEDda."
25421
+ },
25422
+ denied: {
25423
+ heading: "Conex\xE3o n\xE3o autorizada.",
25424
+ status: "A autoriza\xE7\xE3o n\xE3o foi conclu\xEDda. Confira o erro no terminal e inicie uma nova conex\xE3o."
25425
+ },
25426
+ invalid: {
25427
+ heading: "Retorno inv\xE1lido.",
25428
+ status: "Continue na janela original de autoriza\xE7\xE3o. Se ela expirou, inicie uma nova conex\xE3o no terminal."
25429
+ }
25430
+ };
25431
+ function callbackPage(status) {
25432
+ const copy = callbackCopy[status];
25433
+ return `<!doctype html>
25434
+ <html lang="pt-BR">
25435
+ <head>
25436
+ <meta charset="utf-8">
25437
+ <meta name="viewport" content="width=device-width,initial-scale=1">
25438
+ <meta name="referrer" content="no-referrer">
25439
+ <meta name="robots" content="noindex, nofollow, noarchive">
25440
+ <title>${copy.heading} | Assinafy CLI</title>
25441
+ <script>${clearHistory}</script>
25442
+ <link rel="icon" href="${brandOrigin}/brand/assinafy-icon.png">
25443
+ <link rel="stylesheet" href="${brandOrigin}/brand/colors.css">
25444
+ <link rel="stylesheet" href="${brandOrigin}/brand/site.css">
25445
+ <link rel="stylesheet" href="${brandOrigin}/oauth-callback.css">
25446
+ </head>
25447
+ <body>
25448
+ <a class="skip-link" href="#conteudo">Pular para o conte\xFAdo</a>
25449
+ <header class="site-header wrap">
25450
+ <a class="brand" href="${brandOrigin}" aria-label="Assinafy Integra\xE7\xF5es, in\xEDcio">
25451
+ <img src="${brandOrigin}/brand/assinafy-logotype.svg" width="148" height="32" alt="Assinafy">
25452
+ <span class="brand-section">integra\xE7\xF5es</span>
25453
+ </a>
25454
+ </header>
25455
+ <main id="conteudo" class="hero wrap">
25456
+ <div>
25457
+ <p class="eyebrow"><img src="${brandOrigin}/assinafy-cli/cli-icon.svg" width="24" height="24" alt="">Conex\xE3o com a Assinafy CLI</p>
25458
+ <h1>${copy.heading}</h1>
25459
+ <p class="hero-description" role="status">${copy.status}</p>
25460
+ <a class="button button-primary" href="${brandOrigin}/assinafy-cli">Ajuda para conectar<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12h16m-7-7 7 7-7 7"/></svg></a>
25461
+ </div>
25462
+ <figure class="connection-art">
25463
+ <div class="connection-map" role="img" aria-label="Retorno de autoriza\xE7\xE3o: Assinafy para Assinafy CLI.">
25464
+ <svg class="connection-lines" viewBox="0 0 480 240" preserveAspectRatio="none" fill="none" aria-hidden="true">
25465
+ <path class="connection-route" d="M120 106H240"/>
25466
+ <path class="connection-complete" d="M240 106H374m-64-5 5 5-5 5"/>
25467
+ </svg>
25468
+ <div class="connection-node connection-assinafy" aria-hidden="true">
25469
+ <span class="connection-tile"><img src="${brandOrigin}/brand/assinafy-icon.png" width="60" height="60" alt=""></span>
25470
+ <span class="connection-label">Assinafy</span>
25471
+ </div>
25472
+ <div class="connection-node connection-application" aria-hidden="true">
25473
+ <span class="connection-tile"><img src="${brandOrigin}/assinafy-cli/cli-icon.svg" width="36" height="36" alt=""></span>
25474
+ <span class="connection-label">Assinafy CLI</span>
25475
+ </div>
25476
+ </div>
25477
+ <figcaption class="connection-caption">Continue no terminal que iniciou a conex\xE3o.</figcaption>
25478
+ </figure>
25479
+ </main>
25480
+ <footer class="site-footer wrap"><span>Assinafy. Assinaturas que conectam.</span></footer>
25481
+ </body>
25482
+ </html>`;
25483
+ }
25484
+ var callbackHeaders = {
25485
+ "Content-Type": "text/html; charset=utf-8",
25486
+ "Cache-Control": "no-store",
25487
+ "Referrer-Policy": "no-referrer",
25488
+ "X-Content-Type-Options": "nosniff",
25489
+ "X-Robots-Tag": "noindex, nofollow, noarchive",
25490
+ "Content-Security-Policy": `default-src 'none'; script-src 'sha256-${(0, import_node_crypto4.createHash)("sha256").update(clearHistory).digest("base64")}'; style-src ${brandOrigin}; img-src ${brandOrigin}; font-src ${brandOrigin}; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
25491
+ Connection: "close"
25492
+ };
25493
+ function openBrowser(url2) {
25494
+ const [executable, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["rundll32.exe", ["url.dll,FileProtocolHandler", url2]] : ["xdg-open", [url2]];
25495
+ return new Promise((resolve, reject) => {
25496
+ const child = (0, import_node_child_process2.spawn)(executable, args, {
25497
+ stdio: "ignore",
25498
+ detached: true,
25499
+ windowsHide: true
25500
+ });
25501
+ child.once("error", () => reject(new CliError("Could not open the system browser.")));
25502
+ child.once("spawn", () => {
25503
+ child.unref();
25504
+ resolve();
25505
+ });
25506
+ });
25507
+ }
25508
+ async function connectOAuth(oauth, options, onAuthorize, timeoutMs = 18e4) {
25509
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e5) {
25510
+ throw new CliError("OAuth connection timeout must be between 1 and 600000 milliseconds.");
25511
+ }
25512
+ const request = await oauth.authorize(options);
25513
+ if (new URL(request.redirect_uri).search) {
25514
+ throw new CliError("The browser relay redirect URI must not contain query parameters.");
25515
+ }
25516
+ const server = (0, import_node_http.createServer)({ maxHeaderSize: 8192, requestTimeout: 5e3, headersTimeout: 5e3 });
25517
+ server.maxConnections = 8;
25518
+ server.setTimeout(5e3, (socket) => socket.destroy());
25519
+ let timer;
25520
+ let callbackUrl;
25521
+ try {
25522
+ server.listen(0, "127.0.0.1");
25523
+ await (0, import_node_events2.once)(server, "listening");
25524
+ const address = server.address();
25525
+ if (!address || typeof address === "string") throw new CliError("No OAuth listener address.");
25526
+ const host = `127.0.0.1:${address.port}`;
25527
+ request.state += `.${address.port}`;
25528
+ const expectedState = Buffer.from(request.state);
25529
+ const authorization = new URL(request.authorization_url);
25530
+ authorization.searchParams.set("state", request.state);
25531
+ request.authorization_url = authorization.toString();
25532
+ callbackUrl = await new Promise((resolve, reject) => {
25533
+ let consumed = false;
25534
+ timer = setTimeout(
25535
+ () => reject(new CliError("OAuth connection timed out. Start again.")),
25536
+ timeoutMs
25537
+ );
25538
+ server.once("error", reject);
25539
+ server.on("request", (incoming, response) => {
25540
+ const raw = incoming.url ?? "";
25541
+ const url2 = new URL(raw.startsWith("/callback?") ? raw : "/invalid", `http://${host}`);
25542
+ const query = url2.searchParams;
25543
+ const state = Buffer.from(query.get("state") ?? "");
25544
+ const valid = !consumed && incoming.method === "GET" && incoming.headers.host === host && raw.startsWith("/callback?") && raw.length <= 8192 && url2.origin === `http://${host}` && url2.pathname === "/callback" && !url2.hash && [...query.keys()].every((key) => query.getAll(key).length === 1) && state.length === expectedState.length && (0, import_node_crypto4.timingSafeEqual)(state, expectedState) && query.get("iss") === request.issuer && query.has("code") !== query.has("error") && Boolean((query.get("code") ?? query.get("error"))?.trim());
25545
+ if (!valid) {
25546
+ response.writeHead(400, callbackHeaders);
25547
+ response.end(callbackPage("invalid"));
25548
+ return;
25549
+ }
25550
+ consumed = true;
25551
+ const callback = new URL(request.redirect_uri);
25552
+ for (const key of ["code", "state", "iss", "error"]) {
25553
+ if (query.has(key)) callback.searchParams.set(key, query.get(key));
25554
+ }
25555
+ response.writeHead(200, callbackHeaders);
25556
+ response.end(
25557
+ callbackPage(query.has("error") ? "denied" : "received"),
25558
+ () => resolve(callback.toString())
25559
+ );
25560
+ });
25561
+ void Promise.resolve().then(() => onAuthorize(request.authorization_url)).catch(reject);
25562
+ });
25563
+ } finally {
25564
+ clearTimeout(timer);
25565
+ await new Promise((resolve) => {
25566
+ server.close(() => resolve());
25567
+ server.closeAllConnections();
25568
+ });
25569
+ }
25570
+ return oauth.exchangeCode(callbackUrl, request);
25571
+ }
25572
+
25573
+ // src/commands/docs.ts
25328
25574
  var DOCS_URL = "https://api.assinafy.com.br/v1/docs";
25329
25575
  var docsCommand = new Command("docs").description("Print (or open) the Assinafy API documentation URL").option("--open", "Open the documentation in your default browser").action(async (opts, command) => {
25330
25576
  await runAction(command, async ({ config }) => {
25331
25577
  if (opts.open) {
25332
- const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open";
25333
- const child = (0, import_node_child_process2.spawn)(opener, [DOCS_URL], {
25334
- stdio: "ignore",
25335
- detached: true,
25336
- shell: process.platform === "win32"
25337
- });
25338
- child.on(
25339
- "error",
25340
- () => printWarning(`Could not open a browser. Visit ${DOCS_URL}`, config)
25341
- );
25342
- child.unref();
25343
- printInfo(`Opening ${DOCS_URL}`, config);
25578
+ try {
25579
+ await openBrowser(DOCS_URL);
25580
+ printInfo(`Opening ${DOCS_URL}`, config);
25581
+ } catch {
25582
+ printWarning(`Could not open a browser. Visit ${DOCS_URL}`, config);
25583
+ }
25344
25584
  }
25345
25585
  printData({ docs: DOCS_URL }, config, (data) => data.docs);
25346
25586
  });
@@ -25376,6 +25616,16 @@ function defaultArtifactFilename(documentId, artifact) {
25376
25616
  const ext = artifact === "thumbnail" ? "jpg" : artifact === "bundle" ? "zip" : "pdf";
25377
25617
  return `${documentId}-${artifact}.${ext}`;
25378
25618
  }
25619
+ async function saveDownload(config, options) {
25620
+ const buffer = await withSpinner(options.message, config, options.download);
25621
+ const out = writeBinary(options.output ?? options.defaultName, buffer, { force: options.force });
25622
+ printSuccess(`Saved ${buffer.byteLength} bytes to ${out}`, config);
25623
+ printData(
25624
+ { path: out, bytes: buffer.byteLength, ...options.data },
25625
+ config,
25626
+ (d) => sanitizeTerminalText(d.path)
25627
+ );
25628
+ }
25379
25629
 
25380
25630
  // src/commands/documents.ts
25381
25631
  var uploadCommand = new Command("upload").description("Upload a PDF to the workspace").argument("<file>", "Path to the PDF file").option("--name <name>", "Override the document name (defaults to the file name)").option("--metadata <json>", "JSON object of metadata to attach").option("--wait", "Wait until the document finishes processing").action(async (file, opts, command) => {
@@ -25421,12 +25671,15 @@ function renderDocumentListTable(result) {
25421
25671
  { header: "STATUS", value: (r2) => r2.status },
25422
25672
  { header: "CREATED", value: (r2) => r2.created_at }
25423
25673
  ]);
25424
- const footer = paginationFooter(result);
25425
- return footer ? `${table}
25426
- ${footer}` : table;
25674
+ return tableWithFooter(table, result);
25427
25675
  }
25428
25676
  var listCommand3 = addListOptions(
25429
- new Command("list").description("List workspace documents").option("--status <status>", "Filter by document status").option("--method <method>", "Filter by signature method (virtual or collect)").option("--tags <ids>", "Comma-separated tag IDs (AND semantics)")
25677
+ new Command("list").description("List workspace documents").option("--status <status>", "Filter by document status").addOption(
25678
+ new Option("--method <method>", "Filter by signature method (virtual or collect)").choices([
25679
+ "virtual",
25680
+ "collect"
25681
+ ])
25682
+ ).option("--tags <ids>", "Comma-separated tag IDs (AND semantics)")
25430
25683
  ).action(async (opts, command) => {
25431
25684
  await runWithClient(command, async ({ client, config }) => {
25432
25685
  const accountId = requireAccountId(config);
@@ -25491,63 +25744,49 @@ var renameCommand = new Command("rename").description("Rename a document (only b
25491
25744
  printData(doc, config, (d) => renderKeyValue({ id: d.id, name: d.name, status: d.status }));
25492
25745
  });
25493
25746
  });
25494
- var downloadCommand = new Command("download").description("Download a document artifact").argument("<id>", "Document ID").option(
25495
- "--artifact <name>",
25496
- "original | certificated | certificate-page | pades | bundle",
25497
- "certificated"
25498
- ).option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (id, opts, command) => {
25747
+ var downloadCommand = addDownloadOptions(
25748
+ new Command("download").description("Download a document artifact").argument("<id>", "Document ID").option(
25749
+ "--artifact <name>",
25750
+ "original | certificated | certificate-page | pades | bundle",
25751
+ "certificated"
25752
+ )
25753
+ ).action(async (id, opts, command) => {
25499
25754
  await runWithClient(command, async ({ client, config }) => {
25500
25755
  const artifact = requireDocumentArtifactName(opts.artifact);
25501
- const buffer = await withSpinner(
25502
- "Downloading document",
25503
- config,
25504
- () => client.documents.download(id, artifact)
25505
- );
25506
- const out = writeBinary(opts.output ?? defaultArtifactFilename(id, artifact), buffer, {
25507
- force: opts.force
25756
+ await saveDownload(config, {
25757
+ message: "Downloading document",
25758
+ download: () => client.documents.download(id, artifact),
25759
+ output: opts.output,
25760
+ defaultName: defaultArtifactFilename(id, artifact),
25761
+ force: opts.force,
25762
+ data: { artifact }
25508
25763
  });
25509
- printSuccess(`Saved ${buffer.byteLength} bytes to ${out}`, config);
25510
- printData(
25511
- { path: out, bytes: buffer.byteLength, artifact },
25512
- config,
25513
- (d) => sanitizeTerminalText(d.path)
25514
- );
25515
25764
  });
25516
25765
  });
25517
- var thumbnailCommand = new Command("thumbnail").description("Download the document thumbnail (JPEG)").argument("<id>", "Document ID").option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (id, opts, command) => {
25766
+ var thumbnailCommand = addDownloadOptions(
25767
+ new Command("thumbnail").description("Download the document thumbnail (JPEG)").argument("<id>", "Document ID")
25768
+ ).action(async (id, opts, command) => {
25518
25769
  await runWithClient(command, async ({ client, config }) => {
25519
- const buffer = await withSpinner(
25520
- "Downloading thumbnail",
25521
- config,
25522
- () => client.documents.thumbnail(id)
25523
- );
25524
- const out = writeBinary(opts.output ?? defaultArtifactFilename(id, "thumbnail"), buffer, {
25770
+ await saveDownload(config, {
25771
+ message: "Downloading thumbnail",
25772
+ download: () => client.documents.thumbnail(id),
25773
+ output: opts.output,
25774
+ defaultName: defaultArtifactFilename(id, "thumbnail"),
25525
25775
  force: opts.force
25526
25776
  });
25527
- printSuccess(`Saved ${buffer.byteLength} bytes to ${out}`, config);
25528
- printData(
25529
- { path: out, bytes: buffer.byteLength },
25530
- config,
25531
- (d) => sanitizeTerminalText(d.path)
25532
- );
25533
25777
  });
25534
25778
  });
25535
- var downloadPageCommand = new Command("download-page").description("Download a single document page (JPEG)").argument("<id>", "Document ID").argument("<pageId>", "Page ID").option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (id, pageId, opts, command) => {
25779
+ var downloadPageCommand = addDownloadOptions(
25780
+ new Command("download-page").description("Download a single document page (JPEG)").argument("<id>", "Document ID").argument("<pageId>", "Page ID")
25781
+ ).action(async (id, pageId, opts, command) => {
25536
25782
  await runWithClient(command, async ({ client, config }) => {
25537
- const buffer = await withSpinner(
25538
- "Downloading page",
25539
- config,
25540
- () => client.documents.downloadPage(id, pageId)
25541
- );
25542
- const out = writeBinary(opts.output ?? `${id}-page-${pageId}.jpg`, buffer, {
25783
+ await saveDownload(config, {
25784
+ message: "Downloading page",
25785
+ download: () => client.documents.downloadPage(id, pageId),
25786
+ output: opts.output,
25787
+ defaultName: `${id}-page-${pageId}.jpg`,
25543
25788
  force: opts.force
25544
25789
  });
25545
- printSuccess(`Saved ${buffer.byteLength} bytes to ${out}`, config);
25546
- printData(
25547
- { path: out, bytes: buffer.byteLength },
25548
- config,
25549
- (d) => sanitizeTerminalText(d.path)
25550
- );
25551
25790
  });
25552
25791
  });
25553
25792
  var activitiesCommand = new Command("activities").description("Show the activity log for a document").argument("<id>", "Document ID").action(async (id, _opts, command) => {
@@ -25640,7 +25879,7 @@ var createFromTemplateCommand = new Command("create-from-template").description(
25640
25879
  const accountId = requireAccountId(config);
25641
25880
  const signers = parseJsonArray(opts.signers, "--signers");
25642
25881
  const editorFields = parseJsonArray(opts.editorFields, "--editor-fields");
25643
- const options = clean({
25882
+ const options = stripEmpty({
25644
25883
  name: opts.name,
25645
25884
  message: opts.message,
25646
25885
  expires_at: opts.expiresAt,
@@ -25706,14 +25945,14 @@ var publicCommand = new Command("public").description("Public (unauthenticated)
25706
25945
  });
25707
25946
  });
25708
25947
  var sendTokenCommand = new Command("send-token").description("Send a 6-digit verification token to a signer").argument("<id>", "Document ID").addOption(
25709
- new Option("--email <email>", "Email using the current published API payload").conflicts([
25710
- "recipient",
25711
- "channel"
25712
- ])
25948
+ new Option(
25949
+ "--email <email>",
25950
+ "Email address (compatibility overload for older deployments)"
25951
+ ).conflicts(["recipient", "channel"])
25713
25952
  ).addOption(
25714
25953
  new Option(
25715
25954
  "--recipient <value>",
25716
- "Email address or phone number (live legacy payload)"
25955
+ "Email address or phone number (production payload)"
25717
25956
  ).conflicts("email")
25718
25957
  ).addOption(
25719
25958
  new Option("--channel <channel>", "email or whatsapp").default("email").conflicts("email")
@@ -25769,13 +26008,6 @@ function parseSendTokenChannel(value) {
25769
26008
  if (value === "email" || value === "whatsapp") return value;
25770
26009
  throw new CliError("--channel must be email or whatsapp");
25771
26010
  }
25772
- function clean(obj) {
25773
- const out = {};
25774
- for (const [k, v] of Object.entries(obj)) {
25775
- if (v !== void 0 && v !== null) out[k] = v;
25776
- }
25777
- return out;
25778
- }
25779
26011
  var documentsCommand = new Command("documents").description("Upload, list, download, and manage documents").addCommand(uploadCommand).addCommand(listCommand3).addCommand(searchCommand).addCommand(getCommand2).addCommand(renameCommand).addCommand(downloadCommand).addCommand(thumbnailCommand).addCommand(downloadPageCommand).addCommand(activitiesCommand).addCommand(deleteCommand).addCommand(tagsCommand).addCommand(tagsSetCommand).addCommand(tagsAddCommand).addCommand(tagsRemoveCommand).addCommand(createFromTemplateCommand).addCommand(estimateTemplateCostCommand).addCommand(verifyCommand).addCommand(statusesCommand).addCommand(publicCommand).addCommand(sendTokenCommand).addCommand(progressCommand).addCommand(waitCommand);
25780
26012
 
25781
26013
  // src/commands/fields.ts
@@ -25786,6 +26018,9 @@ var fieldColumns = [
25786
26018
  { header: "REQUIRED", value: (r2) => r2.is_required },
25787
26019
  { header: "ACTIVE", value: (r2) => r2.is_active }
25788
26020
  ];
26021
+ var signerAccessCodeOption = () => new Option("--signer-access-code <code>", "Signer access code (for signer-side validation)").env(
26022
+ "ASSINAFY_SIGNER_ACCESS_CODE"
26023
+ );
25789
26024
  var createCommand2 = new Command("create").description("Create a custom field definition").requiredOption("--type <type>", "Field type (see `fields types`)").requiredOption("--name <name>", "Field name").option("--regex <regex>", "Validation regex").option("--required", "Mark the field as required").option("--inactive", "Compatibility: create the field inactive").action(async (opts, command) => {
25790
26025
  await runWithClient(command, async ({ client, config }) => {
25791
26026
  const accountId = requireAccountId(config);
@@ -25857,12 +26092,7 @@ var deleteCommand2 = new Command("delete").alias("rm").description("Delete a fie
25857
26092
  printData({ deleted: id }, config);
25858
26093
  });
25859
26094
  });
25860
- var validateCommand = new Command("validate").description("Validate a value against a field definition").argument("<id>", "Field ID").argument("<value>", "Value to validate").addOption(
25861
- new Option(
25862
- "--signer-access-code <code>",
25863
- "Signer access code (for signer-side validation)"
25864
- ).env("ASSINAFY_SIGNER_ACCESS_CODE")
25865
- ).action(async (id, value, opts, command) => {
26095
+ var validateCommand = new Command("validate").description("Validate a value against a field definition").argument("<id>", "Field ID").argument("<value>", "Value to validate").addOption(signerAccessCodeOption()).action(async (id, value, opts, command) => {
25866
26096
  const run = opts.signerAccessCode ? runWithPublicClient : runWithClient;
25867
26097
  await run(command, async ({ client, config }) => {
25868
26098
  const accountId = requireAccountId(config);
@@ -25878,11 +26108,7 @@ var validateCommand = new Command("validate").description("Validate a value agai
25878
26108
  );
25879
26109
  });
25880
26110
  });
25881
- var validateMultipleCommand = new Command("validate-multiple").description("Validate multiple field values at once").requiredOption("--entries <json>", "JSON array of { field_id, value } entries").addOption(
25882
- new Option("--signer-access-code <code>", "Signer access code").env(
25883
- "ASSINAFY_SIGNER_ACCESS_CODE"
25884
- )
25885
- ).action(async (opts, command) => {
26111
+ var validateMultipleCommand = new Command("validate-multiple").description("Validate multiple field values at once").requiredOption("--entries <json>", "JSON array of { field_id, value } entries").addOption(signerAccessCodeOption()).action(async (opts, command) => {
25886
26112
  const run = opts.signerAccessCode ? runWithPublicClient : runWithClient;
25887
26113
  await run(command, async ({ client, config }) => {
25888
26114
  const accountId = requireAccountId(config);
@@ -25965,178 +26191,6 @@ var logoutCommand = new Command("logout").description("Remove stored credentials
25965
26191
  });
25966
26192
  });
25967
26193
 
25968
- // src/lib/oauth-browser.ts
25969
- var import_node_child_process3 = require("child_process");
25970
- var import_node_crypto4 = require("crypto");
25971
- var import_node_events2 = require("events");
25972
- var import_node_http = require("http");
25973
- var CLI_OAUTH_REDIRECT_URI = "https://integrations.assinafy.com.br/assinafy-cli/oauth-callback";
25974
- var clearHistory = "history.replaceState(null, '', '/');";
25975
- var brandOrigin = "https://integrations.assinafy.com.br";
25976
- var callbackCopy = {
25977
- received: {
25978
- heading: "Volte ao terminal.",
25979
- status: "A resposta de autoriza\xE7\xE3o foi recebida. Confira no terminal se a conex\xE3o foi conclu\xEDda."
25980
- },
25981
- denied: {
25982
- heading: "Conex\xE3o n\xE3o autorizada.",
25983
- status: "A autoriza\xE7\xE3o n\xE3o foi conclu\xEDda. Confira o erro no terminal e inicie uma nova conex\xE3o."
25984
- },
25985
- invalid: {
25986
- heading: "Retorno inv\xE1lido.",
25987
- status: "Continue na janela original de autoriza\xE7\xE3o. Se ela expirou, inicie uma nova conex\xE3o no terminal."
25988
- }
25989
- };
25990
- function callbackPage(status) {
25991
- const copy = callbackCopy[status];
25992
- return `<!doctype html>
25993
- <html lang="pt-BR">
25994
- <head>
25995
- <meta charset="utf-8">
25996
- <meta name="viewport" content="width=device-width,initial-scale=1">
25997
- <meta name="referrer" content="no-referrer">
25998
- <meta name="robots" content="noindex, nofollow, noarchive">
25999
- <title>${copy.heading} | Assinafy CLI</title>
26000
- <script>${clearHistory}</script>
26001
- <link rel="icon" href="${brandOrigin}/brand/assinafy-icon.png">
26002
- <link rel="stylesheet" href="${brandOrigin}/brand/colors.css">
26003
- <link rel="stylesheet" href="${brandOrigin}/brand/site.css">
26004
- <link rel="stylesheet" href="${brandOrigin}/oauth-callback.css">
26005
- </head>
26006
- <body>
26007
- <a class="skip-link" href="#conteudo">Pular para o conte\xFAdo</a>
26008
- <header class="site-header wrap">
26009
- <a class="brand" href="${brandOrigin}" aria-label="Assinafy Integra\xE7\xF5es, in\xEDcio">
26010
- <img src="${brandOrigin}/brand/assinafy-logotype.svg" width="148" height="32" alt="Assinafy">
26011
- <span class="brand-section">integra\xE7\xF5es</span>
26012
- </a>
26013
- </header>
26014
- <main id="conteudo" class="hero wrap">
26015
- <div>
26016
- <p class="eyebrow"><img src="${brandOrigin}/assinafy-cli/cli-icon.svg" width="24" height="24" alt="">Conex\xE3o com a Assinafy CLI</p>
26017
- <h1>${copy.heading}</h1>
26018
- <p class="hero-description" role="status">${copy.status}</p>
26019
- <a class="button button-primary" href="${brandOrigin}/assinafy-cli">Ajuda para conectar<svg width="19" height="19" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 12h16m-7-7 7 7-7 7"/></svg></a>
26020
- </div>
26021
- <figure class="connection-art">
26022
- <div class="connection-map" role="img" aria-label="Retorno de autoriza\xE7\xE3o: Assinafy para Assinafy CLI.">
26023
- <svg class="connection-lines" viewBox="0 0 480 240" preserveAspectRatio="none" fill="none" aria-hidden="true">
26024
- <path class="connection-route" d="M120 106H240"/>
26025
- <path class="connection-complete" d="M240 106H374m-64-5 5 5-5 5"/>
26026
- </svg>
26027
- <div class="connection-node connection-assinafy" aria-hidden="true">
26028
- <span class="connection-tile"><img src="${brandOrigin}/brand/assinafy-icon.png" width="60" height="60" alt=""></span>
26029
- <span class="connection-label">Assinafy</span>
26030
- </div>
26031
- <div class="connection-node connection-application" aria-hidden="true">
26032
- <span class="connection-tile"><img src="${brandOrigin}/assinafy-cli/cli-icon.svg" width="36" height="36" alt=""></span>
26033
- <span class="connection-label">Assinafy CLI</span>
26034
- </div>
26035
- </div>
26036
- <figcaption class="connection-caption">Continue no terminal que iniciou a conex\xE3o.</figcaption>
26037
- </figure>
26038
- </main>
26039
- <footer class="site-footer wrap"><span>Assinafy. Assinaturas que conectam.</span></footer>
26040
- </body>
26041
- </html>`;
26042
- }
26043
- var callbackHeaders = {
26044
- "Content-Type": "text/html; charset=utf-8",
26045
- "Cache-Control": "no-store",
26046
- "Referrer-Policy": "no-referrer",
26047
- "X-Content-Type-Options": "nosniff",
26048
- "X-Robots-Tag": "noindex, nofollow, noarchive",
26049
- "Content-Security-Policy": `default-src 'none'; script-src 'sha256-${(0, import_node_crypto4.createHash)("sha256").update(clearHistory).digest("base64")}'; style-src ${brandOrigin}; img-src ${brandOrigin}; font-src ${brandOrigin}; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
26050
- Connection: "close"
26051
- };
26052
- function openBrowser(url2) {
26053
- const [executable, args] = process.platform === "darwin" ? ["open", [url2]] : process.platform === "win32" ? ["rundll32.exe", ["url.dll,FileProtocolHandler", url2]] : ["xdg-open", [url2]];
26054
- return new Promise((resolve, reject) => {
26055
- const child = (0, import_node_child_process3.spawn)(executable, args, {
26056
- stdio: "ignore",
26057
- detached: true,
26058
- windowsHide: true
26059
- });
26060
- child.once("error", () => reject(new CliError("Could not open the system browser.")));
26061
- child.once("spawn", () => {
26062
- child.unref();
26063
- resolve();
26064
- });
26065
- });
26066
- }
26067
- async function connectOAuth(oauth, options, onAuthorize, timeoutMs = 18e4) {
26068
- if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 6e5) {
26069
- throw new CliError("OAuth connection timeout must be between 1 and 600000 milliseconds.");
26070
- }
26071
- const request = await oauth.authorize(options);
26072
- if (new URL(request.redirect_uri).search) {
26073
- throw new CliError("The browser relay redirect URI must not contain query parameters.");
26074
- }
26075
- const server = (0, import_node_http.createServer)({ maxHeaderSize: 8192, requestTimeout: 5e3, headersTimeout: 5e3 });
26076
- server.maxConnections = 8;
26077
- server.setTimeout(5e3, (socket) => socket.destroy());
26078
- let timer;
26079
- let cancel2;
26080
- let terminate;
26081
- let callbackUrl;
26082
- try {
26083
- server.listen(0, "127.0.0.1");
26084
- await (0, import_node_events2.once)(server, "listening");
26085
- const address = server.address();
26086
- if (!address || typeof address === "string") throw new CliError("No OAuth listener address.");
26087
- const host = `127.0.0.1:${address.port}`;
26088
- request.state += `.${address.port}`;
26089
- const expectedState = Buffer.from(request.state);
26090
- const authorization = new URL(request.authorization_url);
26091
- authorization.searchParams.set("state", request.state);
26092
- request.authorization_url = authorization.toString();
26093
- callbackUrl = await new Promise((resolve, reject) => {
26094
- let consumed = false;
26095
- timer = setTimeout(
26096
- () => reject(new CliError("OAuth connection timed out. Start again.")),
26097
- timeoutMs
26098
- );
26099
- cancel2 = () => reject(new CliError("OAuth connection cancelled.", { exitCode: 130 }));
26100
- terminate = () => reject(new CliError("OAuth connection terminated.", { exitCode: 143 }));
26101
- process.once("SIGINT", cancel2);
26102
- process.once("SIGTERM", terminate);
26103
- server.once("error", reject);
26104
- server.on("request", (incoming, response) => {
26105
- const raw = incoming.url ?? "";
26106
- const url2 = new URL(raw.startsWith("/callback?") ? raw : "/invalid", `http://${host}`);
26107
- const query = url2.searchParams;
26108
- const state = Buffer.from(query.get("state") ?? "");
26109
- const valid = !consumed && incoming.method === "GET" && incoming.headers.host === host && raw.startsWith("/callback?") && raw.length <= 8192 && url2.origin === `http://${host}` && url2.pathname === "/callback" && !url2.hash && [...query.keys()].every((key) => query.getAll(key).length === 1) && state.length === expectedState.length && (0, import_node_crypto4.timingSafeEqual)(state, expectedState) && query.get("iss") === request.issuer && query.has("code") !== query.has("error") && Boolean((query.get("code") ?? query.get("error"))?.trim());
26110
- if (!valid) {
26111
- response.writeHead(400, callbackHeaders);
26112
- response.end(callbackPage("invalid"));
26113
- return;
26114
- }
26115
- consumed = true;
26116
- const callback = new URL(request.redirect_uri);
26117
- for (const key of ["code", "state", "iss", "error"]) {
26118
- if (query.has(key)) callback.searchParams.set(key, query.get(key));
26119
- }
26120
- response.writeHead(200, callbackHeaders);
26121
- response.end(
26122
- callbackPage(query.has("error") ? "denied" : "received"),
26123
- () => resolve(callback.toString())
26124
- );
26125
- });
26126
- void Promise.resolve().then(() => onAuthorize(request.authorization_url)).catch(reject);
26127
- });
26128
- } finally {
26129
- clearTimeout(timer);
26130
- if (cancel2) process.off("SIGINT", cancel2);
26131
- if (terminate) process.off("SIGTERM", terminate);
26132
- await new Promise((resolve) => {
26133
- server.close(() => resolve());
26134
- server.closeAllConnections();
26135
- });
26136
- }
26137
- return oauth.exchangeCode(callbackUrl, request);
26138
- }
26139
-
26140
26194
  // src/commands/oauth.ts
26141
26195
  var clientIdOption = () => new Option("--client-id <id>", "OAuth application client ID").env("ASSINAFY_OAUTH_CLIENT_ID").default("96BZZ0sZTb2NkEXt1GCaIRCTprI2YKHZr8JDHawuXUyCLC88");
26142
26196
  var clientSecretOption = () => new Option(
@@ -26147,8 +26201,8 @@ var connectCommand = new Command("connect").description(
26147
26201
  "Open browser consent for a public OAuth app, receive its loopback return, and print tokens"
26148
26202
  ).addOption(clientIdOption()).option("--redirect-uri <uri>", "Exactly registered HTTPS relay URI", CLI_OAUTH_REDIRECT_URI).option(
26149
26203
  "--scope <scopes>",
26150
- "Space-separated scopes; the default requests every published scope",
26151
- "account:read documents:read documents:write templates:read templates:write webhooks:write openid profile email offline_access"
26204
+ "Space-separated scopes; the default requests the seven registered CLI scopes",
26205
+ "account:read documents:read documents:write templates:read templates:write webhooks:write offline_access"
26152
26206
  ).option("--timeout <seconds>", "Wait for browser consent (1\u2013600 seconds)", "180").option("--no-browser", "Print the authorization URL without opening the system browser").action(async (opts, command) => {
26153
26207
  await runWithPublicClient(command, async ({ client, config }) => {
26154
26208
  const timeout = parseInteger(opts.timeout, "--timeout", { min: 1 });
@@ -26157,7 +26211,7 @@ var connectCommand = new Command("connect").description(
26157
26211
  {
26158
26212
  clientId: opts.clientId,
26159
26213
  redirectUri: opts.redirectUri,
26160
- scopes: opts.scope.trim().split(/\s+/)
26214
+ scopes: opts.scope.trim().split(/\s+/).filter(Boolean)
26161
26215
  },
26162
26216
  async (url2) => {
26163
26217
  process.stderr.write(
@@ -26182,7 +26236,7 @@ function withScopeHint(error) {
26182
26236
  if (!(error instanceof ValidationError) || error.errors.oauthError !== "invalid_scope")
26183
26237
  return error;
26184
26238
  return new ValidationError(
26185
- `${error.message}. The application is not registered for one of the requested scopes: the default requests all ten published scopes, including webhooks:write. Ask the application owner to register them, or pass --scope with the scopes it permits.`,
26239
+ `${error.message}. The application is not registered for one of the requested scopes: the CLI default requests seven registered scopes, including webhooks:write and offline_access. Ask the application owner to register them, or pass --scope with the scopes it permits.`,
26186
26240
  error.errors
26187
26241
  );
26188
26242
  }
@@ -26207,7 +26261,7 @@ var authorizeCommand = new Command("authorize").description(
26207
26261
  await client.oauth.authorize({
26208
26262
  clientId: opts.clientId,
26209
26263
  redirectUri: opts.redirectUri,
26210
- scopes: opts.scope.trim().split(/\s+/)
26264
+ scopes: opts.scope.trim().split(/\s+/).filter(Boolean)
26211
26265
  }),
26212
26266
  config
26213
26267
  );
@@ -26274,6 +26328,7 @@ var userinfoCommand = new Command("userinfo").description("Read OIDC claims usin
26274
26328
  var oauthCommand = new Command("oauth").description("OAuth 2.1 authorization, PKCE, token rotation, and OpenID Connect").addCommand(connectCommand).addCommand(metadataCommand).addCommand(discoveryCommand).addCommand(authorizeCommand).addCommand(exchangeCommand).addCommand(refreshCommand).addCommand(revokeCommand).addCommand(userinfoCommand);
26275
26329
 
26276
26330
  // src/commands/send.ts
26331
+ var phonePattern = /^\+?[\d\s().-]*\d[\d\s().-]*$/;
26277
26332
  function parseSignerSpec(spec) {
26278
26333
  const match = spec.match(/^\s*(.*?)\s*<\s*([^>]*)\s*>\s*$/);
26279
26334
  const name = match?.[1]?.trim();
@@ -26282,12 +26337,17 @@ function parseSignerSpec(spec) {
26282
26337
  throw new CliError(`Invalid --signer "${spec}". Use "Name <email-or-phone>".`);
26283
26338
  }
26284
26339
  const isEmail = contact.includes("@");
26340
+ if (!match && !isEmail && !phonePattern.test(contact)) {
26341
+ throw new CliError(
26342
+ `Invalid --signer "${spec}". A bare contact must be an email or a phone number. Use "Name <email-or-phone>".`
26343
+ );
26344
+ }
26285
26345
  const signer = { name: name || contact };
26286
26346
  if (isEmail) signer.email = contact;
26287
26347
  else signer.whatsapp_phone_number = contact;
26288
26348
  return signer;
26289
26349
  }
26290
- function resolveSigners2(signerSpecs, signersJson) {
26350
+ function resolveSigners(signerSpecs, signersJson) {
26291
26351
  if (signerSpecs.length > 0 && signersJson) {
26292
26352
  throw new CliError("Provide either --signer or --signers, not both.");
26293
26353
  }
@@ -26304,7 +26364,7 @@ var sendCommand = new Command("send").description("Upload a PDF, create signers,
26304
26364
  ).addOption(new Option("--signers <json>", "JSON array of signer objects").conflicts("signer")).option("--message <message>", "Message shown to signers").option("--expires-at <iso8601>", "Expiration timestamp").option("--copy-receivers <csv>", "Comma-separated signer IDs to receive a copy of the document").option("--metadata <json>", "JSON object of metadata to attach to the document").option("--no-wait", "Do not wait for the document to finish processing").action(async (file, opts, command) => {
26305
26365
  await runWithClient(command, async ({ client, config }) => {
26306
26366
  const accountId = requireAccountId(config);
26307
- const signers = resolveSigners2(opts.signer, opts.signers);
26367
+ const signers = resolveSigners(opts.signer, opts.signers);
26308
26368
  const params = {
26309
26369
  source: { filePath: file },
26310
26370
  signers,
@@ -26389,29 +26449,22 @@ var searchCommand2 = new Command("search").description("Search the signer's docu
26389
26449
  );
26390
26450
  });
26391
26451
  });
26392
- var downloadCommand2 = new Command("download").description("Download a signer document artifact").argument("<signerId>", "Signer ID").argument("<documentId>", "Document ID").argument("<artifact>", "original | certificated | certificate-page | pades | bundle").addOption(
26393
- new Option("--access-code <code>", "Optional signer identity preflight code").env(
26394
- "ASSINAFY_SIGNER_ACCESS_CODE"
26452
+ var downloadCommand2 = addDownloadOptions(
26453
+ new Command("download").description("Download a signer document artifact").argument("<signerId>", "Signer ID").argument("<documentId>", "Document ID").argument("<artifact>", "original | certificated | certificate-page | pades | bundle").addOption(
26454
+ new Option("--access-code <code>", "Optional signer identity preflight code").env(
26455
+ "ASSINAFY_SIGNER_ACCESS_CODE"
26456
+ )
26395
26457
  )
26396
- ).option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (signerId, documentId, artifact, opts, command) => {
26458
+ ).action(async (signerId, documentId, artifact, opts, command) => {
26397
26459
  await runWithPublicClient(command, async ({ client, config }) => {
26398
26460
  const artifactName = requireDocumentArtifactName(artifact);
26399
- const buffer = await withSpinner(
26400
- "Downloading",
26401
- config,
26402
- () => client.signerDocuments.download(signerId, documentId, artifactName, opts.accessCode)
26403
- );
26404
- const out = writeBinary(
26405
- opts.output ?? defaultArtifactFilename(documentId, artifactName),
26406
- buffer,
26407
- { force: opts.force }
26408
- );
26409
- printSuccess(`Saved ${buffer.byteLength} bytes to ${out}`, config);
26410
- printData(
26411
- { path: out, bytes: buffer.byteLength },
26412
- config,
26413
- (d) => sanitizeTerminalText(d.path)
26414
- );
26461
+ await saveDownload(config, {
26462
+ message: "Downloading",
26463
+ download: () => client.signerDocuments.download(signerId, documentId, artifactName, opts.accessCode),
26464
+ output: opts.output,
26465
+ defaultName: defaultArtifactFilename(documentId, artifactName),
26466
+ force: opts.force
26467
+ });
26415
26468
  });
26416
26469
  });
26417
26470
  var selfCommand = new Command("self").description("Fetch the signer's own profile").addOption(accessCodeOption()).action(async (opts, command) => {
@@ -26508,23 +26561,18 @@ var uploadSignatureCommand = new Command("upload-signature").description("Upload
26508
26561
  printData(result, config);
26509
26562
  });
26510
26563
  });
26511
- var downloadSignatureCommand = new Command("download-signature").description("Download the signer's signature or initial image").addOption(accessCodeOption()).option("--type <type>", "signature or initial", "signature").option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (opts, command) => {
26564
+ var downloadSignatureCommand = addDownloadOptions(
26565
+ new Command("download-signature").description("Download the signer's signature or initial image").addOption(accessCodeOption()).option("--type <type>", "signature or initial", "signature")
26566
+ ).action(async (opts, command) => {
26512
26567
  await runWithPublicClient(command, async ({ client, config }) => {
26513
26568
  const imageType = requireSignerImageType(opts.type);
26514
- const buffer = await withSpinner(
26515
- "Downloading signature",
26516
- config,
26517
- () => client.signerDocuments.downloadSignature(opts.accessCode, imageType)
26518
- );
26519
- const out = writeBinary(opts.output ?? `signer-${imageType}.png`, buffer, {
26569
+ await saveDownload(config, {
26570
+ message: "Downloading signature",
26571
+ download: () => client.signerDocuments.downloadSignature(opts.accessCode, imageType),
26572
+ output: opts.output,
26573
+ defaultName: `signer-${imageType}.png`,
26520
26574
  force: opts.force
26521
26575
  });
26522
- printSuccess(`Saved ${buffer.byteLength} bytes to ${out}`, config);
26523
- printData(
26524
- { path: out, bytes: buffer.byteLength },
26525
- config,
26526
- (d) => sanitizeTerminalText(d.path)
26527
- );
26528
26576
  });
26529
26577
  });
26530
26578
  var assignmentCommand = new Command("assignment").description("Fetch the assignment as the signer sees it").addOption(accessCodeOption()).option("--accept-terms", "Pass has_accepted_terms=true").action(async (opts, command) => {
@@ -26639,9 +26687,7 @@ var listCommand5 = addListOptions(
26639
26687
  );
26640
26688
  printPaginatedData(result, config, (rows) => {
26641
26689
  const table = renderTable(rows, signerColumns);
26642
- const footer = paginationFooter(result);
26643
- return footer ? `${table}
26644
- ${footer}` : table;
26690
+ return tableWithFooter(table, result);
26645
26691
  });
26646
26692
  });
26647
26693
  });
@@ -26656,7 +26702,7 @@ var getCommand4 = new Command("get").description("Show a signer by ID").argument
26656
26702
  printData(signer, config, (s) => renderKeyValue(s));
26657
26703
  });
26658
26704
  });
26659
- var updateCommand2 = new Command("update").description("Update a signer").argument("<id>", "Signer ID").option("--name <name>", "Signer full name").option("--email <email>", "Email address").option("--phone <number>", "WhatsApp phone number (E.164)").option("--cpf <cpf>", "Brazilian tax ID (CPF)").action(async (id, opts, command) => {
26705
+ var updateCommand2 = new Command("update").description("Update a signer").argument("<id>", "Signer ID").option("--name <name>", "Signer full name").option("--email <email>", "Email address").option("--phone <number>", "WhatsApp phone number (E.164)").option("--cpf <cpf>", "Brazilian tax ID (CPF/CNPJ), sent as government_id").action(async (id, opts, command) => {
26660
26706
  await runWithClient(command, async ({ client, config }) => {
26661
26707
  const accountId = requireAccountId(config);
26662
26708
  const payload = {};
@@ -26787,9 +26833,7 @@ var listCommand7 = addListOptions(
26787
26833
  { header: "STATUS", value: (r2) => r2.status },
26788
26834
  { header: "CREATED", value: (r2) => r2.created_at }
26789
26835
  ]);
26790
- const footer = paginationFooter(result);
26791
- return footer ? `${table}
26792
- ${footer}` : table;
26836
+ return tableWithFooter(table, result);
26793
26837
  });
26794
26838
  });
26795
26839
  });
@@ -26813,23 +26857,18 @@ var getCommand5 = new Command("get").description("Show a template by ID").argume
26813
26857
  );
26814
26858
  });
26815
26859
  });
26816
- var downloadPageCommand2 = new Command("download-page").description("Download a template page as a JPEG").argument("<templateId>", "Template ID").argument("<pageId>", "Page ID").option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (templateId, pageId, opts, command) => {
26860
+ var downloadPageCommand2 = addDownloadOptions(
26861
+ new Command("download-page").description("Download a template page as a JPEG").argument("<templateId>", "Template ID").argument("<pageId>", "Page ID")
26862
+ ).action(async (templateId, pageId, opts, command) => {
26817
26863
  await runWithClient(command, async ({ client, config }) => {
26818
26864
  const accountId = requireAccountId(config);
26819
- const buffer = await withSpinner(
26820
- "Downloading page",
26821
- config,
26822
- () => client.templates.downloadPage(templateId, pageId, accountId)
26823
- );
26824
- const out = writeBinary(opts.output ?? `${templateId}-page-${pageId}.jpg`, buffer, {
26865
+ await saveDownload(config, {
26866
+ message: "Downloading page",
26867
+ download: () => client.templates.downloadPage(templateId, pageId, accountId),
26868
+ output: opts.output,
26869
+ defaultName: `${templateId}-page-${pageId}.jpg`,
26825
26870
  force: opts.force
26826
26871
  });
26827
- printSuccess(`Saved ${buffer.byteLength} bytes to ${out}`, config);
26828
- printData(
26829
- { path: out, bytes: buffer.byteLength },
26830
- config,
26831
- (d) => sanitizeTerminalText(d.path)
26832
- );
26833
26872
  });
26834
26873
  });
26835
26874
  var templatesCommand = new Command("templates").description("List and inspect document templates").addCommand(listCommand7).addCommand(getCommand5).addCommand(downloadPageCommand2);
@@ -26841,7 +26880,9 @@ var selfCommand2 = new Command("self").description("Show the authenticated user'
26841
26880
  printData(user, config);
26842
26881
  });
26843
26882
  });
26844
- var statsCommand = new Command("stats").description("Show document KPIs across the user's accounts").option("--granularity <value>", "monthly or daily", "monthly").option("--month <yyyy-mm>", "Month required for daily granularity").action(async (opts, command) => {
26883
+ var statsCommand = new Command("stats").description("Show document KPIs across the user's accounts").addOption(
26884
+ new Option("--granularity <value>", "monthly or daily").choices(["monthly", "daily"]).default("monthly")
26885
+ ).option("--month <yyyy-mm>", "Month required for daily granularity").action(async (opts, command) => {
26845
26886
  await runWithClient(command, async ({ client, config }) => {
26846
26887
  const params = {
26847
26888
  granularity: opts.granularity,
@@ -26991,9 +27032,7 @@ var dispatchesCommand = addSortableListOptions(
26991
27032
  { header: "STATUS", value: (r2) => r2.http_status },
26992
27033
  { header: "ENDPOINT", value: (r2) => r2.endpoint }
26993
27034
  ]);
26994
- const footer = paginationFooter(result);
26995
- return footer ? `${table}
26996
- ${footer}` : table;
27035
+ return tableWithFooter(table, result);
26997
27036
  });
26998
27037
  });
26999
27038
  });
@@ -27038,7 +27077,12 @@ var whoamiCommand = new Command("whoami").description("Verify credentials and li
27038
27077
 
27039
27078
  // src/commands/workspaces.ts
27040
27079
  var import_node_path6 = __toESM(require("path"), 1);
27041
- var createCommand5 = new Command("create").description("Create a workspace (account)").requiredOption("--name <name>", "Workspace name").option("--notification-sender <type>", "Notification sender: User or Account").option("--primary-color <hex>", "Primary brand color").option("--secondary-color <hex>", "Secondary brand color").action(async (opts, command) => {
27080
+ var createCommand5 = new Command("create").description("Create a workspace (account)").requiredOption("--name <name>", "Workspace name").addOption(
27081
+ new Option("--notification-sender <type>", "Notification sender: User or Account").choices([
27082
+ "User",
27083
+ "Account"
27084
+ ])
27085
+ ).option("--primary-color <hex>", "Primary brand color").option("--secondary-color <hex>", "Secondary brand color").action(async (opts, command) => {
27042
27086
  await runWithClient(command, async ({ client, config }) => {
27043
27087
  const workspace = await withSpinner(
27044
27088
  "Creating workspace",
@@ -27083,12 +27127,16 @@ var getCommand7 = new Command("get").description("Show a workspace by ID").argum
27083
27127
  printData(workspace, config, (w) => renderKeyValue(w));
27084
27128
  });
27085
27129
  });
27086
- var updateCommand4 = new Command("update").description("Update a workspace").argument("<id>", "Account/workspace ID").option("--name <name>", "New name").option("--notification-sender <type>", "Notification sender: User or Account").option("--primary-color <hex>", "Primary brand color (pass empty to clear)").option("--secondary-color <hex>", "Secondary brand color (pass empty to clear)").action(async (id, opts, command) => {
27130
+ var updateCommand4 = new Command("update").description("Update a workspace").argument("<id>", "Account/workspace ID").option("--name <name>", "New name").addOption(
27131
+ new Option("--notification-sender <type>", "Notification sender: User or Account").choices([
27132
+ "User",
27133
+ "Account"
27134
+ ])
27135
+ ).option("--primary-color <hex>", "Primary brand color (pass empty to clear)").option("--secondary-color <hex>", "Secondary brand color (pass empty to clear)").action(async (id, opts, command) => {
27087
27136
  await runWithClient(command, async ({ client, config }) => {
27088
27137
  const payload = {};
27089
27138
  if (opts.name) payload.name = opts.name;
27090
- if (opts.notificationSender)
27091
- payload.notification_sender_type = opts.notificationSender;
27139
+ if (opts.notificationSender) payload.notification_sender_type = opts.notificationSender;
27092
27140
  if (opts.primaryColor !== void 0) payload.primary_color = opts.primaryColor || null;
27093
27141
  if (opts.secondaryColor !== void 0) payload.secondary_color = opts.secondaryColor || null;
27094
27142
  const workspace = await withSpinner(
@@ -27114,7 +27162,9 @@ var themeCommand = new Command("theme").description("Show public branding for a
27114
27162
  );
27115
27163
  });
27116
27164
  });
27117
- var statsCommand2 = new Command("stats").description("Show document KPIs for a workspace").argument("<id>", "Account/workspace ID").option("--granularity <value>", "monthly or daily", "monthly").option("--month <yyyy-mm>", "Month required for daily granularity").action(async (id, opts, command) => {
27165
+ var statsCommand2 = new Command("stats").description("Show document KPIs for a workspace").argument("<id>", "Account/workspace ID").addOption(
27166
+ new Option("--granularity <value>", "monthly or daily").choices(["monthly", "daily"]).default("monthly")
27167
+ ).option("--month <yyyy-mm>", "Month required for daily granularity").action(async (id, opts, command) => {
27118
27168
  await runWithClient(command, async ({ client, config }) => {
27119
27169
  const params = {
27120
27170
  granularity: opts.granularity,
@@ -27128,20 +27178,17 @@ var statsCommand2 = new Command("stats").description("Show document KPIs for a w
27128
27178
  printData(rows, config, renderDocumentStats);
27129
27179
  });
27130
27180
  });
27131
- var logoDownloadCommand = new Command("download").description("Download the workspace logo").argument("<id>", "Account/workspace ID").option("-o, --output <path>", "Output file path").option("--force", "Overwrite the output file if it already exists").action(async (id, opts, command) => {
27181
+ var logoDownloadCommand = addDownloadOptions(
27182
+ new Command("download").description("Download the workspace logo").argument("<id>", "Account/workspace ID")
27183
+ ).action(async (id, opts, command) => {
27132
27184
  await runWithClient(command, async ({ client, config }) => {
27133
- const logo = await withSpinner(
27134
- "Downloading workspace logo",
27135
- config,
27136
- () => client.workspaces.downloadLogo(id)
27137
- );
27138
- const output = writeBinary(opts.output ?? `${id}-logo.png`, logo, { force: opts.force });
27139
- printSuccess(`Saved ${logo.byteLength} bytes to ${output}`, config);
27140
- printData(
27141
- { path: output, bytes: logo.byteLength },
27142
- config,
27143
- (value) => sanitizeTerminalText(value.path)
27144
- );
27185
+ await saveDownload(config, {
27186
+ message: "Downloading workspace logo",
27187
+ download: () => client.workspaces.downloadLogo(id),
27188
+ output: opts.output,
27189
+ defaultName: `${id}-logo.png`,
27190
+ force: opts.force
27191
+ });
27145
27192
  });
27146
27193
  });
27147
27194
  var logoUploadCommand = new Command("upload").description("Upload or replace the workspace logo").argument("<id>", "Account/workspace ID").argument("<file>", "Logo image path").option("--content-type <mime>", "Image MIME type (inferred from extension)").action(async (id, file, opts, command) => {
@@ -27228,7 +27275,7 @@ function handleStreamError(err, fallback, exit = process.exit) {
27228
27275
  // package.json
27229
27276
  var package_default = {
27230
27277
  name: "@assinafy/cli",
27231
- version: "2.4.0",
27278
+ version: "2.4.2",
27232
27279
  description: "The official command-line interface for the Assinafy digital-signature API",
27233
27280
  license: "MIT",
27234
27281
  type: "module",