@opsrev/acculynx-cli 1.6.1 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +5 -719
  2. package/package.json +2 -4
package/dist/index.js CHANGED
@@ -310,724 +310,6 @@ function registerEstimatesCommands(parentCmd, getClient2) {
310
310
  });
311
311
  }
312
312
 
313
- // src/unofficial/session-store.ts
314
- import {
315
- existsSync,
316
- readFileSync as readFileSync2,
317
- writeFileSync,
318
- mkdirSync,
319
- readdirSync,
320
- unlinkSync
321
- } from "fs";
322
- import { join } from "path";
323
- import { homedir } from "os";
324
-
325
- // src/unofficial/cookie-jar.ts
326
- var CookieJar = class _CookieJar {
327
- cookies = /* @__PURE__ */ new Map();
328
- /** Extract and store cookies from a response's Set-Cookie headers. */
329
- capture(url, response) {
330
- const domain = new URL(url).hostname;
331
- const jar = this.cookies.get(domain) ?? /* @__PURE__ */ new Map();
332
- for (const header of response.headers.getSetCookie()) {
333
- const [pair] = header.split(";");
334
- const eqIdx = pair.indexOf("=");
335
- if (eqIdx === -1) continue;
336
- jar.set(pair.slice(0, eqIdx).trim(), pair.slice(eqIdx + 1).trim());
337
- }
338
- this.cookies.set(domain, jar);
339
- }
340
- /** Get a specific cookie value by name for a given URL. */
341
- getCookie(url, name) {
342
- const domain = new URL(url).hostname;
343
- for (const [d, jar] of this.cookies) {
344
- if (domain === d || domain.endsWith("." + d)) {
345
- if (jar.has(name)) return jar.get(name);
346
- }
347
- }
348
- return void 0;
349
- }
350
- /** Build a Cookie header string for a given URL. */
351
- headerFor(url) {
352
- const domain = new URL(url).hostname;
353
- const parts = [];
354
- for (const [d, jar] of this.cookies) {
355
- if (domain === d || domain.endsWith("." + d)) {
356
- for (const [k, v] of jar) parts.push(`${k}=${v}`);
357
- }
358
- }
359
- return parts.join("; ");
360
- }
361
- /** Serialize for disk caching. */
362
- toJSON() {
363
- const out = {};
364
- for (const [d, jar] of this.cookies) {
365
- out[d] = Object.fromEntries(jar);
366
- }
367
- return out;
368
- }
369
- /** Restore from disk cache. */
370
- static fromJSON(data) {
371
- const jar = new _CookieJar();
372
- for (const [d, pairs] of Object.entries(data)) {
373
- jar.cookies.set(d, new Map(Object.entries(pairs)));
374
- }
375
- return jar;
376
- }
377
- };
378
-
379
- // src/unofficial/session-store.ts
380
- var CONFIG_DIR = join(
381
- process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config"),
382
- "acculynx-cli"
383
- );
384
- var SESSIONS_DIR = join(CONFIG_DIR, "sessions");
385
- function sessionKey(email, companyId) {
386
- const slug = email.replace(/[@.]/g, "-").toLowerCase();
387
- const prefix = companyId.slice(0, 8);
388
- return `${slug}--${prefix}.json`;
389
- }
390
- function loadSession(email, companyId) {
391
- const file = join(SESSIONS_DIR, sessionKey(email, companyId));
392
- if (!existsSync(file)) return null;
393
- try {
394
- const data = JSON.parse(readFileSync2(file, "utf-8"));
395
- return {
396
- jar: CookieJar.fromJSON(data.cookies),
397
- companyId: data.companyId,
398
- email: data.email
399
- };
400
- } catch {
401
- return null;
402
- }
403
- }
404
- function saveSession(session) {
405
- mkdirSync(SESSIONS_DIR, { recursive: true, mode: 448 });
406
- writeFileSync(
407
- join(SESSIONS_DIR, sessionKey(session.email, session.companyId)),
408
- JSON.stringify(
409
- {
410
- email: session.email,
411
- companyId: session.companyId,
412
- cookies: session.jar.toJSON()
413
- },
414
- null,
415
- 2
416
- ),
417
- { mode: 384 }
418
- );
419
- }
420
- function deleteSession(email, companyId) {
421
- const file = join(SESSIONS_DIR, sessionKey(email, companyId));
422
- if (!existsSync(file)) return false;
423
- unlinkSync(file);
424
- return true;
425
- }
426
- function listSessions() {
427
- if (!existsSync(SESSIONS_DIR)) return [];
428
- return readdirSync(SESSIONS_DIR).filter((f) => f.endsWith(".json")).map((f) => {
429
- try {
430
- const data = JSON.parse(
431
- readFileSync2(join(SESSIONS_DIR, f), "utf-8")
432
- );
433
- return { email: data.email, companyId: data.companyId, file: f };
434
- } catch {
435
- return null;
436
- }
437
- }).filter(Boolean);
438
- }
439
-
440
- // src/unofficial/unofficial-client.ts
441
- function createUnofficialClient(session) {
442
- const base = "https://my.acculynx.com";
443
- async function doGet(path) {
444
- const url = `${base}${path}`;
445
- const resp = await fetch(url, {
446
- headers: {
447
- Cookie: session.jar.headerFor(url),
448
- Accept: "application/json"
449
- }
450
- });
451
- if (resp.status === 401 || resp.status === 302) {
452
- throw new Error(
453
- "Session expired \u2014 run `acculynx unofficial login` to re-authenticate"
454
- );
455
- }
456
- if (!resp.ok) {
457
- throw new Error(
458
- `Unofficial API error (${resp.status}): ${await resp.text()}`
459
- );
460
- }
461
- return resp.json();
462
- }
463
- async function doPost(path, body) {
464
- const url = `${base}${path}`;
465
- const headers = {
466
- Cookie: session.jar.headerFor(url),
467
- Accept: "application/json",
468
- "Content-Type": "application/json"
469
- };
470
- const xsrf = session.jar.getCookie(url, "XSRF-TOKEN");
471
- if (xsrf) {
472
- headers["X-XSRF-TOKEN"] = xsrf;
473
- }
474
- const resp = await fetch(url, {
475
- method: "POST",
476
- headers,
477
- body: JSON.stringify(body)
478
- });
479
- if (resp.status === 401 || resp.status === 302) {
480
- throw new Error(
481
- "Session expired \u2014 run `acculynx unofficial login` to re-authenticate"
482
- );
483
- }
484
- if (!resp.ok) {
485
- throw new Error(
486
- `Unofficial API error (${resp.status}): ${await resp.text()}`
487
- );
488
- }
489
- const text = await resp.text();
490
- if (!text) return {};
491
- return JSON.parse(text);
492
- }
493
- async function doGetBuffer(url) {
494
- const fullUrl = url.startsWith("http") ? url : `${base}${url}`;
495
- const resp = await fetch(fullUrl, {
496
- headers: { Cookie: session.jar.headerFor(fullUrl) }
497
- });
498
- if (!resp.ok) {
499
- throw new Error(`Download failed (${resp.status}): ${fullUrl}`);
500
- }
501
- return Buffer.from(await resp.arrayBuffer());
502
- }
503
- return { get: doGet, post: doPost, getBuffer: doGetBuffer };
504
- }
505
-
506
- // src/unofficial/session.ts
507
- async function fetchFollowingCookies(jar, url, init) {
508
- let currentUrl = url;
509
- let response;
510
- for (let i = 0; i < 10; i++) {
511
- response = await fetch(currentUrl, {
512
- ...init,
513
- redirect: "manual",
514
- headers: {
515
- ...Object.fromEntries(
516
- Object.entries(init?.headers ?? {})
517
- ),
518
- Cookie: jar.headerFor(currentUrl)
519
- }
520
- });
521
- jar.capture(currentUrl, response);
522
- const location = response.headers.get("Location");
523
- if (!location || response.status < 300 || response.status >= 400) {
524
- return response;
525
- }
526
- currentUrl = new URL(location, currentUrl).href;
527
- init = { redirect: "manual" };
528
- }
529
- throw new Error("Too many redirects");
530
- }
531
- async function authenticate(email, password) {
532
- const jar = new CookieJar();
533
- const signinResp = await fetchFollowingCookies(
534
- jar,
535
- "https://my.acculynx.com/signin/"
536
- );
537
- const html = await signinResp.text();
538
- const actionMatch = html.match(/<form[^>]*action="([^"]*)"/);
539
- if (!actionMatch) throw new Error("Could not find login form action");
540
- const formAction = actionMatch[1].replace(/&amp;/g, "&");
541
- const thumbprint = html.match(/name="DeviceThumbprint"[^>]*value="([^"]*)"/)?.[1] ?? "";
542
- const deviceName = html.match(/name="DeviceName"[^>]*value="([^"]*)"/)?.[1] ?? "Node.js CLI";
543
- const body = new URLSearchParams({
544
- Email: email,
545
- Password: password,
546
- DeviceThumbprint: thumbprint,
547
- DeviceName: deviceName
548
- });
549
- const loginResp = await fetchFollowingCookies(jar, formAction, {
550
- method: "POST",
551
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
552
- body: body.toString()
553
- });
554
- const locationResp = await fetchFollowingCookies(
555
- jar,
556
- "https://my.acculynx.com/signin/LocationSelector"
557
- );
558
- const locationHtml = await locationResp.text();
559
- return { jar, locationHtml };
560
- }
561
- async function listCompanies(email, password) {
562
- const { locationHtml } = await authenticate(email, password);
563
- const companyPattern = /SwitchCompany\?CompanyID=([0-9a-f-]+)"[^>]*>([^<]+)/gi;
564
- const companies = [];
565
- let match;
566
- while ((match = companyPattern.exec(locationHtml)) !== null) {
567
- companies.push({ id: match[1], name: match[2].trim() });
568
- }
569
- return companies;
570
- }
571
- async function login(email, password, companyId) {
572
- const { jar } = await authenticate(email, password);
573
- await fetchFollowingCookies(
574
- jar,
575
- `https://my.acculynx.com/signin/SwitchCompany?CompanyID=${companyId}`
576
- );
577
- return { jar, companyId, email };
578
- }
579
-
580
- // src/unofficial/commands/login.ts
581
- function getCredentials(opts) {
582
- const email = opts.email ?? process.env.ACCULYNX_EMAIL;
583
- const password = opts.password ?? process.env.ACCULYNX_PASSWORD;
584
- const companyId = opts.companyId ?? process.env.ACCULYNX_COMPANY_ID;
585
- if (!email) {
586
- throw new Error(
587
- "Missing email: pass --email or set ACCULYNX_EMAIL"
588
- );
589
- }
590
- if (!password) {
591
- throw new Error(
592
- "Missing password: pass --password or set ACCULYNX_PASSWORD"
593
- );
594
- }
595
- if (!companyId) {
596
- throw new Error(
597
- "Missing company ID: pass --company-id or set ACCULYNX_COMPANY_ID"
598
- );
599
- }
600
- return { email, password, companyId };
601
- }
602
- function registerLoginCommands(parentCmd) {
603
- parentCmd.command("login").description("Authenticate and cache session cookies").option("--email <email>", "AccuLynx email (env: ACCULYNX_EMAIL)").option(
604
- "--password <password>",
605
- "AccuLynx password (env: ACCULYNX_PASSWORD)"
606
- ).option(
607
- "--company-id <id>",
608
- "Company GUID (env: ACCULYNX_COMPANY_ID)"
609
- ).action(async (opts) => {
610
- const { email, password, companyId } = getCredentials(opts);
611
- const session = await login(email, password, companyId);
612
- saveSession(session);
613
- console.log(
614
- JSON.stringify({
615
- status: "ok",
616
- email,
617
- companyId,
618
- message: "Session cached successfully"
619
- })
620
- );
621
- });
622
- parentCmd.command("companies").description(
623
- "List available companies for your account (discovers company IDs)"
624
- ).option("--email <email>", "AccuLynx email (env: ACCULYNX_EMAIL)").option(
625
- "--password <password>",
626
- "AccuLynx password (env: ACCULYNX_PASSWORD)"
627
- ).action(async (opts) => {
628
- const email = opts.email ?? process.env.ACCULYNX_EMAIL;
629
- const password = opts.password ?? process.env.ACCULYNX_PASSWORD;
630
- if (!email) {
631
- throw new Error(
632
- "Missing email: pass --email or set ACCULYNX_EMAIL"
633
- );
634
- }
635
- if (!password) {
636
- throw new Error(
637
- "Missing password: pass --password or set ACCULYNX_PASSWORD"
638
- );
639
- }
640
- const companies = await listCompanies(email, password);
641
- console.log(JSON.stringify(companies));
642
- });
643
- parentCmd.command("sessions").description("List cached sessions").action(() => {
644
- const sessions = listSessions();
645
- console.log(JSON.stringify(sessions));
646
- });
647
- parentCmd.command("logout").description("Remove a cached session").option("--email <email>", "AccuLynx email (env: ACCULYNX_EMAIL)").option(
648
- "--company-id <id>",
649
- "Company GUID (env: ACCULYNX_COMPANY_ID)"
650
- ).action((opts) => {
651
- const email = opts.email ?? process.env.ACCULYNX_EMAIL;
652
- const companyId = opts.companyId ?? process.env.ACCULYNX_COMPANY_ID;
653
- if (!email || !companyId) {
654
- throw new Error(
655
- "Both --email and --company-id are required (or set env vars)"
656
- );
657
- }
658
- const removed = deleteSession(email, companyId);
659
- console.log(
660
- JSON.stringify({
661
- status: removed ? "removed" : "not_found",
662
- email,
663
- companyId
664
- })
665
- );
666
- });
667
- }
668
-
669
- // src/unofficial/commands/documents.ts
670
- import { writeFileSync as writeFileSync2 } from "fs";
671
- function registerDocumentsCommands(parentCmd, getClient2) {
672
- const docs = parentCmd.command("documents").description("Job document operations");
673
- docs.command("list").argument("<jobId>", "Job ID (GUID)").description("List all document folders and files for a job").action(async (jobId) => {
674
- const folders = await getClient2().get(
675
- `/api/v4/job-documents/${jobId}/job-document-folders`
676
- );
677
- const result = folders.map((folder) => ({
678
- folder: folder.Name,
679
- folderId: folder.Id,
680
- fileCount: folder.FileCount,
681
- files: folder.Files.map((f) => ({
682
- id: f.Id,
683
- name: f.Name,
684
- extension: f.Extension,
685
- size: f.Size,
686
- mimeType: f.MIMEType,
687
- href: f.Href,
688
- createdBy: f.CreatedByDisplayName,
689
- modifiedDate: f.ModifiedDateUTC
690
- }))
691
- }));
692
- console.log(JSON.stringify(result));
693
- });
694
- docs.command("download").argument("<jobId>", "Job ID (GUID)").argument("<fileId>", "File ID (GUID)").option("--output <path>", "Write to file instead of stdout").description("Download a document file").action(async (jobId, fileId, opts) => {
695
- const folders = await getClient2().get(
696
- `/api/v4/job-documents/${jobId}/job-document-folders`
697
- );
698
- let targetFile;
699
- for (const folder of folders) {
700
- targetFile = folder.Files.find((f) => f.Id === fileId);
701
- if (targetFile) break;
702
- }
703
- if (!targetFile) {
704
- throw new Error(
705
- `File ${fileId} not found in job ${jobId} documents`
706
- );
707
- }
708
- const buffer = await getClient2().getBuffer(targetFile.Href);
709
- if (opts.output) {
710
- writeFileSync2(opts.output, buffer);
711
- console.error(
712
- JSON.stringify({
713
- status: "ok",
714
- file: targetFile.Name,
715
- size: buffer.length,
716
- output: opts.output
717
- })
718
- );
719
- } else {
720
- process.stdout.write(buffer);
721
- }
722
- });
723
- }
724
-
725
- // src/unofficial/commands/messages.ts
726
- import TurndownService from "turndown";
727
- function createTurndown() {
728
- const td = new TurndownService({
729
- headingStyle: "atx",
730
- bulletListMarker: "-"
731
- });
732
- td.addRule("removeImages", {
733
- filter: "img",
734
- replacement: () => ""
735
- });
736
- td.addRule("removeStyle", {
737
- filter: ["style", "script"],
738
- replacement: () => ""
739
- });
740
- return td;
741
- }
742
- var looksLikeHtml = /<[a-z][\s\S]*?>/i;
743
- function cleanMessage(html) {
744
- if (!looksLikeHtml.test(html)) return html;
745
- const td = createTurndown();
746
- return td.turndown(html).replace(/\n{3,}/g, "\n\n").trim();
747
- }
748
- function registerMessagesCommands(parentCmd, getClient2) {
749
- const messages = parentCmd.command("messages").description("Job message/comment operations");
750
- messages.command("list").argument("<jobId>", "Job ID (GUID)").option(
751
- "--sort <sort>",
752
- "Sort field and direction (field|asc or field|desc)",
753
- "createdDate|desc"
754
- ).option("--count-only", "Return only the total count of messages").option(
755
- "--type <type>",
756
- "Filter by message type: Comment, Email, or Signatures"
757
- ).description("List all messages and comments for a job").action(async (jobId, opts) => {
758
- const params = new URLSearchParams({ sort: opts.sort });
759
- if (opts.countOnly) {
760
- params.set("countOnly", "true");
761
- }
762
- if (opts.type) {
763
- params.append("filters", `type=${opts.type}`);
764
- }
765
- const data = await getClient2().get(
766
- `/api/jobs/${jobId}/JobMessageFeed?${params.toString()}`
767
- );
768
- if (opts.countOnly) {
769
- console.log(JSON.stringify({ totalRecords: data.TotalRecords }));
770
- return;
771
- }
772
- const result = {
773
- totalRecords: data.TotalRecords,
774
- currentPage: data.CurrentPage,
775
- totalPages: data.TotalPages,
776
- messages: data.results.map((msg) => ({
777
- id: msg.id,
778
- jobId: msg.JobId,
779
- type: msg.Type,
780
- messageType: msg.MessageType,
781
- message: cleanMessage(msg.Message),
782
- subject: msg.Subject,
783
- createdBy: msg.CreatedBy,
784
- createdById: msg.CreatedByID,
785
- createdDate: msg.CreatedDate,
786
- latestMessage: msg.LatestMessage,
787
- parentMessageId: msg.ParentMessageId,
788
- attachmentOnly: msg.AttachmentOnly,
789
- replyEmail: msg.ReplyEmail,
790
- sentDate: msg.SentDate,
791
- recipients: msg.Recipients.map((r) => ({
792
- id: r.id,
793
- companyUserId: r.companyUserId,
794
- sent: r.Sent,
795
- sentDate: r.SentDate,
796
- delivered: r.Delivered,
797
- deliveredDate: r.DeliveredDate,
798
- failed: r.Failed,
799
- failedDate: r.FailedDate,
800
- failedDescription: r.FailedDescription
801
- })),
802
- attachments: msg.Attachments,
803
- childMessageCount: msg.ChildMessages.length,
804
- childMessages: msg.ChildMessages.map((child) => ({
805
- id: child.id,
806
- type: child.Type,
807
- message: cleanMessage(child.Message),
808
- createdBy: child.CreatedBy,
809
- createdDate: child.CreatedDate
810
- }))
811
- }))
812
- };
813
- console.log(JSON.stringify(result));
814
- });
815
- messages.command("post").argument("<jobId>", "Job ID (GUID)").argument("<message>", "Message text to post").option(
816
- "--notify <userIds>",
817
- "Comma-separated user IDs (GUIDs) to notify"
818
- ).description("Post a comment/message to a job, optionally notifying users").action(async (jobId, message, opts) => {
819
- const emailRecipients = opts.notify ? opts.notify.split(",").map((id) => id.trim()) : [];
820
- const data = await getClient2().post(
821
- `/api/jobs/${jobId}/Messages`,
822
- {
823
- JobId: jobId,
824
- Message: message,
825
- RoleId: "1111111",
826
- MessageType: "General Comment",
827
- emailRecipients,
828
- index: -1
829
- }
830
- );
831
- console.log(
832
- JSON.stringify({
833
- id: data.JobMessageId,
834
- jobId: data.JobId,
835
- message: data.Message,
836
- messageType: data.MessageType,
837
- createdDate: data.CreatedDate,
838
- notified: emailRecipients.length
839
- })
840
- );
841
- });
842
- }
843
-
844
- // src/unofficial/commands/milestones.ts
845
- function registerMilestonesCommands(parentCmd, getClient2) {
846
- const milestones = parentCmd.command("milestones").description("Job milestone/status operations");
847
- milestones.command("list").argument("<jobId>", "Job ID (GUID)").description("List all milestones and statuses for a job's workflow").action(async (jobId) => {
848
- const data = await getClient2().get(
849
- `/api/v3/job-workflows/${jobId}`
850
- );
851
- const result = data.Milestones.map((m) => ({
852
- milestoneId: m.MilestoneId,
853
- name: m.Name,
854
- isCurrent: m.IsCurrent,
855
- done: m.Done,
856
- statuses: m.Statuses.map((s) => ({
857
- statusId: s.StatusId,
858
- name: s.Name.trim(),
859
- isCurrent: s.IsCurrent,
860
- done: s.Done
861
- }))
862
- }));
863
- console.log(JSON.stringify(result));
864
- });
865
- milestones.command("set").argument("<jobId>", "Job ID (GUID)").argument("<statusName>", "Destination milestone/status name (case-insensitive)").option("--message <message>", "Optional comment when advancing", "").description("Set a job's milestone/status by name").action(async (jobId, statusName, opts) => {
866
- const data = await getClient2().get(
867
- `/api/v3/job-workflows/${jobId}`
868
- );
869
- const needle = statusName.toLowerCase().trim();
870
- let matchedMilestoneId = null;
871
- let matchedStatus = null;
872
- for (const m of data.Milestones) {
873
- if (m.Name.toLowerCase().trim() === needle) {
874
- matchedMilestoneId = m.MilestoneId;
875
- matchedStatus = m.Statuses[0] ?? null;
876
- break;
877
- }
878
- for (const s of m.Statuses) {
879
- if (s.Name.toLowerCase().trim() === needle) {
880
- matchedMilestoneId = m.MilestoneId;
881
- matchedStatus = s;
882
- break;
883
- }
884
- }
885
- if (matchedStatus) break;
886
- }
887
- if (!matchedMilestoneId || !matchedStatus) {
888
- const available = data.Milestones.flatMap(
889
- (m) => m.Statuses.map((s) => s.Name.trim())
890
- );
891
- console.error(
892
- JSON.stringify({
893
- error: `Status "${statusName}" not found`,
894
- available
895
- })
896
- );
897
- process.exitCode = 1;
898
- return;
899
- }
900
- await getClient2().post(
901
- `/api/v3/job-workflows/${jobId}/set-state`,
902
- {
903
- MilestoneId: matchedMilestoneId,
904
- StatusId: matchedStatus.StatusId,
905
- Message: opts.message
906
- }
907
- );
908
- console.log(
909
- JSON.stringify({
910
- jobId,
911
- milestoneId: matchedMilestoneId,
912
- statusId: matchedStatus.StatusId,
913
- statusName: matchedStatus.Name.trim(),
914
- message: opts.message || null
915
- })
916
- );
917
- });
918
- }
919
-
920
- // src/unofficial/commands/jobs.ts
921
- async function resolveStatusId(client, statusName) {
922
- const workflow = await client.get(
923
- "/api/v3/workflows"
924
- );
925
- const needle = statusName.toLowerCase().trim();
926
- for (const m of workflow.Milestones) {
927
- for (const s of m.Statuses) {
928
- if (s.Name.toLowerCase().trim() === needle) {
929
- return { statusId: s.StatusId, milestoneName: m.Name };
930
- }
931
- }
932
- }
933
- return null;
934
- }
935
- async function getAvailableStatuses(client) {
936
- const workflow = await client.get(
937
- "/api/v3/workflows"
938
- );
939
- return workflow.Milestones.flatMap(
940
- (m) => m.Statuses.map((s) => s.Name.trim())
941
- );
942
- }
943
- function registerUnofficialJobsCommands(parentCmd, getClient2) {
944
- const jobs = parentCmd.command("jobs").description("Unofficial job search with workflow status filtering");
945
- jobs.command("list").description("List jobs, optionally filtered by workflow status or milestone").option("--status <name>", "Filter by workflow status name (case-insensitive)").option("--milestone <name>", "Filter by milestone name (e.g. Prospect, Approved)").option("--query <text>", "Search term").option("--sort <field>", "Sort: milestoneStart|desc, lastTouched|desc, createdDate|desc", "milestoneStart|desc").option("--page <n>", "Page number", "1").action(async (opts) => {
946
- const client = getClient2();
947
- const params = new URLSearchParams();
948
- if (opts.status) {
949
- const resolved = await resolveStatusId(client, opts.status);
950
- if (!resolved) {
951
- const available = await getAvailableStatuses(client);
952
- console.error(
953
- JSON.stringify({
954
- error: `Status "${opts.status}" not found`,
955
- available
956
- })
957
- );
958
- process.exitCode = 1;
959
- return;
960
- }
961
- params.append("filters", `currentStatusId=${resolved.statusId}`);
962
- }
963
- if (opts.milestone) {
964
- params.append("filters", `currentMilestoneList=${opts.milestone}`);
965
- }
966
- params.set("sort", opts.sort);
967
- params.set("page", opts.page);
968
- params.set("type", "2");
969
- params.set("loadAll", "false");
970
- if (opts.query) params.set("query", opts.query);
971
- const data = await client.get(
972
- `/api/joblist?${params.toString()}`
973
- );
974
- const result = {
975
- totalRecords: data.TotalRecords,
976
- currentPage: data.CurrentPage,
977
- totalPages: data.TotalPages,
978
- jobs: data.results.map((j) => ({
979
- id: j.Id,
980
- name: j.Name,
981
- address: j.FullAddress,
982
- cityState: j.CityState,
983
- milestone: j.CurrentMilestone,
984
- status: j.CurrentStatus,
985
- salesPerson: j.SalesPerson,
986
- createdDate: j.CreatedDate,
987
- lastTouched: j.LastTouched,
988
- workTypes: j.WorkTypes,
989
- trades: j.Trades
990
- }))
991
- };
992
- console.log(JSON.stringify(result));
993
- });
994
- }
995
-
996
- // src/unofficial/commands/index.ts
997
- function getSessionFromEnv() {
998
- const email = process.env.ACCULYNX_EMAIL;
999
- const companyId = process.env.ACCULYNX_COMPANY_ID;
1000
- if (!email || !companyId) {
1001
- throw new Error(
1002
- "Set ACCULYNX_EMAIL and ACCULYNX_COMPANY_ID (or run `acculynx unofficial login` first)"
1003
- );
1004
- }
1005
- const session = loadSession(email, companyId);
1006
- if (!session) {
1007
- throw new Error(
1008
- `No cached session for ${email} / ${companyId}. Run \`acculynx unofficial login\` first.`
1009
- );
1010
- }
1011
- return session;
1012
- }
1013
- function registerUnofficialCommands(parentCmd) {
1014
- const unofficial = parentCmd.command("unofficial").description(
1015
- "Unofficial web API commands (cookie-based auth, reverse-engineered)"
1016
- );
1017
- registerLoginCommands(unofficial);
1018
- let _client2 = null;
1019
- function getClient2() {
1020
- if (!_client2) {
1021
- _client2 = createUnofficialClient(getSessionFromEnv());
1022
- }
1023
- return _client2;
1024
- }
1025
- registerDocumentsCommands(unofficial, getClient2);
1026
- registerMessagesCommands(unofficial, getClient2);
1027
- registerMilestonesCommands(unofficial, getClient2);
1028
- registerUnofficialJobsCommands(unofficial, getClient2);
1029
- }
1030
-
1031
313
  // src/index.ts
1032
314
  var require2 = createRequire(import.meta.url);
1033
315
  var { version } = require2("../package.json");
@@ -1060,7 +342,11 @@ registerPingCommand(program, getClient);
1060
342
  registerJobsCommands(program, getClient);
1061
343
  registerContactsCommands(program, getClient);
1062
344
  registerEstimatesCommands(program, getClient);
1063
- registerUnofficialCommands(program);
345
+ try {
346
+ const mod = await import("@opsrev/acculynx-cli-unofficial");
347
+ mod.registerUnofficialCommands(program);
348
+ } catch {
349
+ }
1064
350
  program.parseAsync().catch((err) => {
1065
351
  if (err.message === "(outputHelp)" || err.message === "(version)") {
1066
352
  return;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opsrev/acculynx-cli",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "description": "CLI for the AccuLynx roofing CRM API",
5
5
  "type": "module",
6
6
  "bin": {
@@ -28,12 +28,10 @@
28
28
  "dist"
29
29
  ],
30
30
  "dependencies": {
31
- "commander": "^14.0.3",
32
- "turndown": "^7.2.2"
31
+ "commander": "^14.0.3"
33
32
  },
34
33
  "devDependencies": {
35
34
  "@types/node": "^25.4.0",
36
- "@types/turndown": "^5.0.6",
37
35
  "tsup": "^8.5.1",
38
36
  "tsx": "^4.21.0",
39
37
  "typescript": "^5.9.3",