@truenas/api-client 3.0.4 → 3.0.5

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/index.js CHANGED
@@ -367,775 +367,153 @@ var TrueNasApi = class {
367
367
  }
368
368
  };
369
369
 
370
- // src/enums/truenas-auth-mechanism.enum.ts
371
- var TrueNasAuthMechanism = /* @__PURE__ */ ((TrueNasAuthMechanism2) => {
372
- TrueNasAuthMechanism2["ApiKey"] = "API_KEY_PLAIN";
373
- TrueNasAuthMechanism2["Password"] = "PASSWORD_PLAIN";
374
- TrueNasAuthMechanism2["Otp"] = "OTP_TOKEN";
375
- TrueNasAuthMechanism2["Token"] = "TOKEN_PLAIN";
376
- return TrueNasAuthMechanism2;
377
- })(TrueNasAuthMechanism || {});
370
+ // src/generated/v25_10_0/index.ts
371
+ var v25_10_0_exports = {};
372
+ __export(v25_10_0_exports, {
373
+ ACLTemplateEntryAcltypeInput: () => ACLTemplateEntryAcltypeInput,
374
+ Aclmode: () => Aclmode,
375
+ Acltype: () => Acltype,
376
+ Action: () => Action,
377
+ Advpowermgmt: () => Advpowermgmt,
378
+ Algorithm: () => Algorithm,
379
+ AppContainerDetailsStateInput: () => AppContainerDetailsStateInput,
380
+ Atime: () => Atime,
381
+ Authenticator: () => Authenticator,
382
+ Authmethod: () => Authmethod,
383
+ Autotrim: () => Autotrim,
384
+ Basic: () => Basic,
385
+ Blocksize: () => Blocksize,
386
+ Bootloader: () => Bootloader,
387
+ Casesensitivity: () => Casesensitivity,
388
+ CloudBackupSnapshotItemType: () => CloudBackupSnapshotItemType,
389
+ CloudSyncCreateDirection: () => CloudSyncCreateDirection,
390
+ CloudSyncCreateDirectionInput: () => CloudSyncCreateDirectionInput,
391
+ CloudTaskAttributesEncryptionInput: () => CloudTaskAttributesEncryptionInput,
392
+ Code: () => Code,
393
+ Compression: () => Compression,
394
+ CorePingRemoteTypeInput: () => CorePingRemoteTypeInput,
395
+ Credentials: () => Credentials,
396
+ DeviceGetInfoOtherTypeInput: () => DeviceGetInfoOtherTypeInput,
397
+ DiskDetailsTypeInput: () => DiskDetailsTypeInput,
398
+ DiskWipeModeInput: () => DiskWipeModeInput,
399
+ DockerStatusInfoStatusInput: () => DockerStatusInfoStatusInput,
400
+ Enclosure2SetSlotStatusStatusInput: () => Enclosure2SetSlotStatusStatusInput,
401
+ Encryption: () => Encryption,
402
+ Endpoint: () => Endpoint,
403
+ Exec: () => Exec,
404
+ Feature: () => Feature,
405
+ FilesystemDirEntryType: () => FilesystemDirEntryType,
406
+ Function: () => Function,
407
+ GetDisplayDeviceType: () => GetDisplayDeviceType,
408
+ Hddstandby: () => Hddstandby,
409
+ InitShutdownScriptCreateType: () => InitShutdownScriptCreateType,
410
+ InitShutdownScriptCreateTypeInput: () => InitShutdownScriptCreateTypeInput,
411
+ InterfaceCreateAliasTypeInput: () => InterfaceCreateAliasTypeInput,
412
+ InterfaceCreateTypeInput: () => InterfaceCreateTypeInput,
413
+ Iotype: () => Iotype,
414
+ IpmiChassisIdentifyVerb: () => IpmiChassisIdentifyVerb,
415
+ IscsiExtentCreateType: () => IscsiExtentCreateType,
416
+ IscsiExtentCreateTypeInput: () => IscsiExtentCreateTypeInput,
417
+ IscsiTargetCreateMode: () => IscsiTargetCreateMode,
418
+ IscsiTargetCreateModeInput: () => IscsiTargetCreateModeInput,
419
+ KeychainCredentialEntryType: () => KeychainCredentialEntryType,
420
+ KeychainCredentialEntryTypeInput: () => KeychainCredentialEntryTypeInput,
421
+ Level: () => Level,
422
+ NFS4ACEType: () => NFS4ACEType,
423
+ NFS4ACETypeInput: () => NFS4ACETypeInput,
424
+ Name: () => Name,
425
+ Policy: () => Policy,
426
+ PoolCreateChecksum: () => PoolCreateChecksum,
427
+ PoolCreateDeduplication: () => PoolCreateDeduplication,
428
+ PoolCreateTopologyDataVdevDRAIDTypeInput: () => PoolCreateTopologyDataVdevDRAIDTypeInput,
429
+ PoolDatasetCreateFilesystemAcltypeInput: () => PoolDatasetCreateFilesystemAcltypeInput,
430
+ PoolDatasetCreateFilesystemChecksum: () => PoolDatasetCreateFilesystemChecksum,
431
+ PoolDatasetCreateFilesystemDeduplication: () => PoolDatasetCreateFilesystemDeduplication,
432
+ PoolDatasetCreateFilesystemReadonlyInput: () => PoolDatasetCreateFilesystemReadonlyInput,
433
+ PoolDatasetDeleteResult: () => PoolDatasetDeleteResult,
434
+ PoolScanStateInput: () => PoolScanStateInput,
435
+ Protocol: () => Protocol,
436
+ Purpose: () => Purpose,
437
+ Readonly: () => Readonly,
438
+ ReplicationCountEligibleManualSnapshotsTransportInput: () => ReplicationCountEligibleManualSnapshotsTransportInput,
439
+ ReplicationCreateReadonlyInput: () => ReplicationCreateReadonlyInput,
440
+ Resolution: () => Resolution,
441
+ Rpm: () => Rpm,
442
+ RsyncTaskCreateDirection: () => RsyncTaskCreateDirection,
443
+ RsyncTaskCreateDirectionInput: () => RsyncTaskCreateDirectionInput,
444
+ RsyncTaskCreateMode: () => RsyncTaskCreateMode,
445
+ RsyncTaskCreateModeInput: () => RsyncTaskCreateModeInput,
446
+ SMBEntryEncryptionInput: () => SMBEntryEncryptionInput,
447
+ STIGType: () => STIGType,
448
+ Schema: () => Schema,
449
+ Security: () => Security,
450
+ Serialspeed: () => Serialspeed,
451
+ ServiceControlVerb: () => ServiceControlVerb,
452
+ SharingSMBEntryPurposeInput: () => SharingSMBEntryPurposeInput,
453
+ SharingSMBEntryPurposeInput2: () => SharingSMBEntryPurposeInput2,
454
+ Shutdown: () => Shutdown,
455
+ Snapdev: () => Snapdev,
456
+ Snapdir: () => Snapdir,
457
+ Source: () => Source,
458
+ SourceInput: () => SourceInput,
459
+ State: () => State,
460
+ Status: () => Status,
461
+ SupportNewTicketCommunityTypeInput: () => SupportNewTicketCommunityTypeInput,
462
+ Sync: () => Sync,
463
+ SyslogServerTransportInput: () => SyslogServerTransportInput,
464
+ Sysloglevel: () => Sysloglevel,
465
+ SystemProductTypeResult: () => SystemProductTypeResult,
466
+ SystemStateResult: () => SystemStateResult,
467
+ Tag: () => Tag,
468
+ Target: () => Target,
469
+ Time: () => Time,
470
+ Transport: () => Transport,
471
+ TruecommandConfigChangedEventFieldsStatus: () => TruecommandConfigChangedEventFieldsStatus,
472
+ TruecommandConfigChangedEventFieldsStatusInput: () => TruecommandConfigChangedEventFieldsStatusInput,
473
+ TunableCreateType: () => TunableCreateType,
474
+ TunableCreateTypeInput: () => TunableCreateTypeInput,
475
+ UPSEntryMode: () => UPSEntryMode,
476
+ UPSEntryModeInput: () => UPSEntryModeInput,
477
+ Unixcharset: () => Unixcharset,
478
+ Username: () => Username,
479
+ VMDiskDeviceType: () => VMDiskDeviceType,
480
+ VMDiskDeviceTypeInput: () => VMDiskDeviceTypeInput,
481
+ VMWareEntryStateStateInput: () => VMWareEntryStateStateInput,
482
+ VMWareMatchDatastoresWithDatasetsResultFilesystemType: () => VMWareMatchDatastoresWithDatasetsResultFilesystemType,
483
+ Vendor: () => Vendor,
484
+ Volblocksize: () => Volblocksize,
485
+ When: () => When,
486
+ ZfsTierRewriteJobEntryStatusInput: () => ZfsTierRewriteJobEntryStatusInput
487
+ });
378
488
 
379
- // src/errors/auth.errors.ts
380
- var AuthErrorCode = /* @__PURE__ */ ((AuthErrorCode2) => {
381
- AuthErrorCode2["PasswordAuthFailed"] = "PASSWORD_AUTH_FAILED";
382
- AuthErrorCode2["OtpAuthFailed"] = "OTP_AUTH_FAILED";
383
- AuthErrorCode2["ApiKeyAuthFailed"] = "API_KEY_AUTH_FAILED";
384
- AuthErrorCode2["FullAdminRequired"] = "FULL_ADMIN_REQUIRED";
385
- return AuthErrorCode2;
386
- })(AuthErrorCode || {});
387
- var AuthError = class _AuthError extends Error {
388
- constructor(code, message) {
389
- super(message);
390
- this.code = code;
391
- this.name = "AuthError";
392
- Object.setPrototypeOf(this, _AuthError.prototype);
393
- }
489
+ // src/generated/v25_10_0/api-types.ts
490
+ var Aclmode = {
491
+ Passthrough: "PASSTHROUGH",
492
+ Restricted: "RESTRICTED",
493
+ Discard: "DISCARD",
494
+ Inherit: "INHERIT"
394
495
  };
395
-
396
- // src/auth/truenas-authenticator.ts
397
- var throwOnAuthenticationFailure = (code, message) => switchMap((response) => {
398
- if (response.response_type === "AUTH_ERR" /* AuthErr */) {
399
- return throwError(() => new AuthError(code, message));
400
- }
401
- return of(response);
402
- });
403
- var TrueNasAuthenticator = class _TrueNasAuthenticator {
404
- constructor(connection) {
405
- this.connection = connection;
406
- // in seconds (5 minutes)
407
- /**
408
- * whether or not the system is currently authenticated and accessible.
409
- * this is a `BehaviorSubject` instead of a signal, since we use its `getValue` method
410
- * throughout a lot of the codebase.
411
- */
412
- this.authenticated$ = new BehaviorSubject(false);
413
- /**
414
- * `true` when the system is currently being authenticated to, and `false` otherwise.
415
- * does not indicate whatsoever if authentication is successful or not, just whether the process
416
- * is ongoing.
417
- */
418
- this.authenticating$ = new BehaviorSubject(false);
419
- this.credentials = { username: "", password: "", key: "" };
420
- this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
421
- this.connection.opened.pipe(
422
- filter(
423
- (isOpen) => !!(isOpen && this.credentials?.username && (this.credentials.password || this.credentials.key))
424
- ),
425
- switchMap(() => {
426
- if (this.credentials.password) {
427
- return this.loginWithUserPass(
428
- this.credentials.username,
429
- this.credentials.password
430
- );
431
- }
432
- return this.loginWithApiKey({
433
- username: this.credentials.username,
434
- key: this.credentials.key
435
- });
436
- })
437
- ).subscribe();
438
- connection.closed.subscribe(() => {
439
- this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
440
- this.authenticated$.next(false);
441
- });
442
- }
443
- static {
444
- this.DefaultSessionLifetime = 300;
445
- }
446
- loginWithUserPass(username, password) {
447
- const message = createJsonRpcMessage("auth.login_ex", [
448
- {
449
- mechanism: "PASSWORD_PLAIN" /* Password */,
450
- username,
451
- password
452
- }
453
- ]);
454
- this.authenticating$.next(true);
455
- this.connection.send(message);
456
- const messageId = message.id ?? "";
457
- return this.connection.messages().pipe(
458
- withId(messageId),
459
- map((msg) => {
460
- if (msg.error) {
461
- const errorMessage = getApiErrorMessage(
462
- msg.error,
463
- "Authentication failed"
464
- );
465
- throw new Error(errorMessage);
466
- }
467
- return msg.result;
468
- }),
469
- throwOnAuthenticationFailure(
470
- "PASSWORD_AUTH_FAILED" /* PasswordAuthFailed */,
471
- "TrueNAS authentication failed. Please verify your TrueNAS user credentials and try again."
472
- ),
473
- tap((res) => {
474
- if (res.response_type === "SUCCESS" /* Success */) {
475
- if (res.user_info?.privilege.roles.$set.includes("FULL_ADMIN" /* FullAdmin */)) {
476
- this.credentials.username = username;
477
- this.credentials.password = password;
478
- this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
479
- this.authenticated$.next(true);
480
- } else {
481
- this.logout();
482
- this.authenticated$.next(false);
483
- throw new AuthError(
484
- "FULL_ADMIN_REQUIRED" /* FullAdminRequired */,
485
- "User account must have full admin privileges"
486
- );
487
- }
488
- }
489
- }),
490
- finalize(() => {
491
- this.authenticating$.next(false);
492
- }),
493
- take(1)
494
- );
495
- }
496
- loginWithOtp(code) {
497
- const message = createJsonRpcMessage("auth.login_ex", [
498
- {
499
- mechanism: "OTP_TOKEN" /* Otp */,
500
- otp_token: code
501
- }
502
- ]);
503
- this.authenticating$.next(true);
504
- this.connection.send(message);
505
- const messageId = message.id ?? "";
506
- return this.connection.messages().pipe(
507
- withId(messageId),
508
- map((msg) => {
509
- if (msg.error) {
510
- const errorMessage = getApiErrorMessage(
511
- msg.error,
512
- "Authentication failed"
513
- );
514
- throw new Error(errorMessage);
515
- }
516
- return msg.result;
517
- }),
518
- tap((res) => {
519
- if (res?.response_type === "SUCCESS" /* Success */) {
520
- this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
521
- this.authenticated$.next(true);
522
- }
523
- }),
524
- throwOnAuthenticationFailure(
525
- "OTP_AUTH_FAILED" /* OtpAuthFailed */,
526
- "TrueNAS authentication failed. Please verify your one-time passcode and try again."
527
- ),
528
- finalize(() => {
529
- this.authenticating$.next(false);
530
- }),
531
- take(1)
532
- );
533
- }
534
- loginWithApiKey(credentials) {
535
- const { username, key } = credentials;
536
- const message = createJsonRpcMessage("auth.login_ex", [
537
- {
538
- mechanism: "API_KEY_PLAIN" /* ApiKey */,
539
- username,
540
- api_key: key
541
- }
542
- ]);
543
- this.authenticating$.next(true);
544
- this.connection.send(message);
545
- const messageId = message.id ?? "";
546
- return this.connection.messages().pipe(
547
- withId(messageId),
548
- map((msg) => {
549
- if (msg.error) {
550
- const errorMessage = getApiErrorMessage(
551
- msg.error,
552
- "Authentication failed"
553
- );
554
- throw new Error(errorMessage);
555
- }
556
- return msg.result;
557
- }),
558
- throwOnAuthenticationFailure(
559
- "API_KEY_AUTH_FAILED" /* ApiKeyAuthFailed */,
560
- "TrueNAS authentication failed. Has the TrueNAS Connect API key been removed from your TrueNAS server?"
561
- ),
562
- tap((res) => {
563
- this.credentials.username = username;
564
- this.credentials.key = key;
565
- this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
566
- this.authenticated$.next(true);
567
- }),
568
- finalize(() => {
569
- this.authenticating$.next(false);
570
- }),
571
- take(1)
572
- );
573
- }
574
- newApiKey(username) {
575
- const message = createJsonRpcMessage("api_key.create", [
576
- { name: `tnc-${randomUUID()}`, username }
577
- ]);
578
- this.connection.send(message);
579
- const messageId = message.id ?? "";
580
- return this.connection.messages().pipe(
581
- withId(messageId),
582
- map((msg) => {
583
- if (msg.error) {
584
- const errorMessage = getApiErrorMessage(
585
- msg.error,
586
- "Failed to create API key"
587
- );
588
- throw new Error(errorMessage);
589
- }
590
- return msg.result;
591
- }),
592
- take(1)
593
- );
594
- }
595
- logout() {
596
- const message = createJsonRpcMessage("auth.logout");
597
- this.connection.send(message);
598
- const messageId = message.id ?? "";
599
- return this.connection.messages().pipe(
600
- withId(messageId),
601
- map((msg) => {
602
- if (msg.error) {
603
- return false;
604
- }
605
- return msg.result;
606
- }),
607
- tap((success) => {
608
- this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
609
- this.authenticated$.next(!success);
610
- }),
611
- take(1)
612
- );
613
- }
496
+ var ACLTemplateEntryAcltypeInput = {
497
+ Nfs4: "NFS4",
498
+ Posix1e: "POSIX1E"
614
499
  };
615
-
616
- // src/logger.ts
617
- var consoleLogger = {
618
- trace: (message, ...args) => console.trace(message, ...args),
619
- debug: (message, ...args) => console.debug(message, ...args),
620
- info: (message, ...args) => console.info(message, ...args),
621
- warn: (message, ...args) => console.warn(message, ...args),
622
- error: (message, ...args) => console.error(message, ...args)
500
+ var Acltype = {
501
+ Nfs4: "NFS4",
502
+ Posix1e: "POSIX1E"
623
503
  };
624
- var noop = () => void 0;
625
- var noopLogger = {
626
- trace: noop,
627
- debug: noop,
628
- info: noop,
629
- warn: noop,
630
- error: noop
504
+ var Action = {
505
+ Start: "START",
506
+ Stop: "STOP",
507
+ Pause: "PAUSE"
631
508
  };
632
-
633
- // src/utils/truenas-connection.utils.ts
634
- function isHttpStatusError(reason) {
635
- return ["404", "502", "503"].some((code) => reason.includes(code));
636
- }
637
- function getHttpError(reason) {
638
- if (reason.includes("404")) {
639
- return "API endpoint not found - System may not support versioned API";
640
- }
641
- if (reason.includes("502")) {
642
- return "Bad Gateway - System may be starting up";
643
- }
644
- if (reason.includes("503")) {
645
- return "Service Unavailable - System may be overloaded";
646
- }
647
- return "";
648
- }
649
- function getWebSocketError(code) {
650
- switch (code) {
651
- case 1e3:
652
- return "Connection closed normally";
653
- case 1001:
654
- return "Server is shutting down or restarting";
655
- case 1002:
656
- return "Protocol error - Invalid WebSocket communication";
657
- case 1003:
658
- return "Unsupported data format received";
659
- case 1006:
660
- return "Connection lost unexpectedly - Check network connectivity";
661
- case 1007:
662
- return "Invalid data received from server";
663
- case 1008:
664
- return "Connection terminated due to policy violation";
665
- case 1009:
666
- return "Message size exceeded server limits";
667
- case 1011:
668
- return "Server encountered an internal error";
669
- case 1012:
670
- return "Service is restarting";
671
- case 1013:
672
- return "Server temporarily overloaded - Try again later";
673
- case 1015:
674
- return "TLS/Certificate error - Certificate may be expired";
675
- default:
676
- return "Network connection failed - Check IP address and connectivity";
677
- }
678
- }
679
- var TrueNasSocket = class {
680
- constructor(config) {
681
- this.config = config;
682
- this.socket = webSocket(this.config);
683
- }
684
- messages() {
685
- return this.socket;
686
- }
687
- next(msg) {
688
- this.socket.next(msg);
689
- }
690
- complete() {
691
- this.socket.complete();
692
- }
693
- };
694
-
695
- // src/types/transport.type.ts
696
- function httpScheme(protocol) {
697
- return protocol === "http:" ? "http:" : "https:";
698
- }
699
- function socketScheme(protocol) {
700
- return protocol === "http:" ? "ws:" : "wss:";
701
- }
702
-
703
- // src/connection/truenas-connection.ts
704
- var tenSeconds = 10 * 1e3;
705
- var twentySeconds = 20 * 1e3;
706
- var TrueNasConnection = class {
707
- constructor(initialEnabled, hostnames, systemUuid, websocketPath, systemName, retryDelay = tenSeconds, maxRetry = 3, logger = noopLogger, protocol = "https:") {
708
- this.hostnames = hostnames;
709
- this.systemUuid = systemUuid;
710
- this.websocketPath = websocketPath;
711
- this.systemName = systemName;
712
- this.retryDelay = retryDelay;
713
- this.maxRetry = maxRetry;
714
- this.logger = logger;
715
- this.protocol = protocol;
716
- // compatibility properties
717
- this.opened = new BehaviorSubject(false);
718
- this.closed = new Subject();
719
- this.hostname = new BehaviorSubject("");
720
- this.connectionAttempts = new BehaviorSubject(0);
721
- this.lastErrorMessage = new BehaviorSubject(null);
722
- /**
723
- * emits when the connection is manually closed.
724
- */
725
- this.closeConnection = new Subject();
726
- /**
727
- * the connection only establishes a socket while this gate is `true`. consumers
728
- * flip it via `setEnabled()` (the app maps `SystemState.Active -> true`).
729
- */
730
- this.enabled$ = new BehaviorSubject(false);
731
- /**
732
- * observable which emits the current gate value and only emits again when it changes.
733
- */
734
- this.enabledChange$ = this.enabled$.pipe(distinctUntilChanged());
735
- /**
736
- * observable that handles the entire connection lifecycle.
737
- */
738
- this.connection$ = this.enabledChange$.pipe(
739
- switchMap((enabled) => {
740
- if (enabled) {
741
- return this.connect().pipe(
742
- map((conn) => makeActiveConnection(conn.ws, conn.hostname))
743
- );
744
- }
745
- return of(closedConnection);
746
- }),
747
- switchMap((connection) => {
748
- if (connection.state !== "active") {
749
- return of(connection);
750
- }
751
- const initMessage = createJsonRpcMessage("core.set_options", [
752
- { legacy_jobs: false }
753
- ]);
754
- connection.ws.next(initMessage);
755
- return connection.ws.messages().pipe(
756
- filter((msg) => msg.id === initMessage.id),
757
- take(1),
758
- map(() => connection)
759
- );
760
- }),
761
- // in the event of an error, do two things:
762
- // 1. emit an errored connection downstream to inform consumers that
763
- // the connection is dead.
764
- // 2. re-throw an error so the downstream `retry` will re-subscribe.
765
- catchError$1((err) => {
766
- this.logger.error("All connections failed - retrying", { message: err?.message, hostname: err?.hostname });
767
- return concat(
768
- of(makeConnectionError(err.message, err.hostname)),
769
- // since this error will immediately get caught by `retry` there's no reason to build a real error.
770
- throwError(() => null)
771
- );
772
- }),
773
- retry(),
774
- // start with a closed connection.
775
- startWith(closedConnection),
776
- // prevent multiple subscriptions from re-evaluating the entire pipeline.
777
- shareReplay$1({ bufferSize: 1, refCount: false }),
778
- takeUntil(this.closeConnection)
779
- );
780
- /**
781
- * observable which is either an instance of the current `TrueNasSocket` used for the connection
782
- * or `null` if the connection is closed or errored for any reason.
783
- */
784
- this.ws$ = this.connection$.pipe(
785
- map((conn) => conn.state === "active" ? conn.ws : null)
786
- );
787
- /**
788
- * current hostname we used to build the URL for this connection.
789
- */
790
- this.hostname$ = this.connection$.pipe(
791
- map((conn) => conn.state === "active" ? conn.hostname : null)
792
- );
793
- /**
794
- * emits error messages from the connection pipeline. this is used to derive the
795
- * corresponding compatibility property.
796
- */
797
- this.lastErrorMessage$ = this.connection$.pipe(
798
- map((conn) => conn.state === "error" ? conn.message : null)
799
- );
800
- /**
801
- * emits when the connection state *changes*, so it'll never emit `true` twice
802
- * in a row nor `false` twice in a row.
803
- */
804
- this.opened$ = this.connection$.pipe(
805
- map((conn) => conn.state),
806
- distinctUntilChanged(),
807
- map((state) => state === "active")
808
- );
809
- /**
810
- * emits when the connection state goes from open to closed.
811
- */
812
- this.closed$ = this.connection$.pipe(
813
- map((conn) => conn.state),
814
- distinctUntilChanged(),
815
- filter((state) => state === "closed" || state === "error"),
816
- map(() => {
817
- })
818
- );
819
- /**
820
- * whether to display a connection error to the user — the **live** signal.
821
- *
822
- * `true` only while `connection$` is currently a `ConnectionError`, meaning the entire race +
823
- * retry cycle has been exhausted for all hostnames right now; it flips back to `false` once a
824
- * connection is re-established. individual socket losses during a race are expected and not surfaced.
825
- *
826
- * NOTE: this is NOT the same as the `hasExhaustedRetries()` method, which is a **cumulative**
827
- * snapshot (see there). The two can disagree — prefer this observable for "is the connection
828
- * errored right now?".
829
- */
830
- this.hasConnectionError$ = this.connection$.pipe(
831
- map((conn) => conn.state === "error"),
832
- takeUntil(this.closeConnection)
833
- );
834
- /**
835
- * observable which always emits messages from the current socket.
836
- */
837
- this.messages$ = this.ws$.pipe(
838
- filter((ws) => ws !== null),
839
- switchMap((ws) => ws.messages().pipe(
840
- catchError$1(() => EMPTY)
841
- ))
842
- );
843
- combineLatest([
844
- interval(twentySeconds),
845
- this.ws$
846
- ]).pipe(
847
- takeUntil(this.closeConnection)
848
- ).subscribe(([, ws]) => {
849
- if (ws) {
850
- const pingMessage = createJsonRpcMessage("core.ping");
851
- ws.next(pingMessage);
852
- }
853
- });
854
- this.opened$.subscribe((val) => this.opened.next(val));
855
- this.closed$.subscribe(() => this.closed.next());
856
- this.hostname$.pipe(filter(Boolean)).subscribe((name) => this.hostname.next(name));
857
- this.ws$.pipe(filter(Boolean)).subscribe((ws) => this.ws = ws);
858
- this.lastErrorMessage$.subscribe((msg) => this.lastErrorMessage.next(msg));
859
- this.enabled$.next(initialEnabled);
860
- }
861
- /**
862
- * whether the connection has exhausted its retries — the **cumulative** snapshot, read
863
- * synchronously. (Formerly `hasConnectionError()`; renamed to disambiguate it from the
864
- * live `hasConnectionError$` observable, with which it can disagree.)
865
- *
866
- * `true` when the lifetime `connectionAttempts` count exceeds `hostnames.length * maxRetry`,
867
- * OR when an error message is currently set. Ported from the source (tncui) behavior.
868
- */
869
- hasExhaustedRetries() {
870
- const attemptsExhausted = this.connectionAttempts.value > this.hostnames.length * this.maxRetry;
871
- const hasErrorMessage = this.lastErrorMessage.value !== null;
872
- return attemptsExhausted || hasErrorMessage;
873
- }
874
- /**
875
- * enables or disables the connection gate. the app calls this when its `SystemState`
876
- * changes (mapping `SystemState.Active -> true`, everything else -> `false`).
877
- */
878
- setEnabled(enabled) {
879
- this.enabled$.next(enabled);
880
- }
881
- /**
882
- * compatibility method which just returns the public `messages$` observable.
883
- * this is used in a few places in the codebase that relied upon the old implementation.
884
- */
885
- messages() {
886
- return this.messages$;
887
- }
888
- /**
889
- * sends a message over the current websocket OR queues it to send once
890
- * the next websocket is opened. messages sent via `send` will not be lost until after
891
- * the next `closed$` emission.
892
- */
893
- send(message) {
894
- return this.ws$.pipe(
895
- filter((ws) => ws !== null),
896
- take(1)
897
- ).subscribe((ws) => ws.next(message));
898
- }
899
- /**
900
- * manually closes this connection and prevents it from retrying/opening any more.
901
- */
902
- close() {
903
- this.closeConnection.next();
904
- this.closeConnection.complete();
905
- }
906
- /**
907
- * helper method which creates an `Observable` which emits an `ActiveConnection`
908
- * after it establishes a connection to the given hostname. the observable will emit an
909
- * error if the connection is never established and will not complete until unsubscribed from or closed.
910
- */
911
- createSocket(hostname) {
912
- const url = `${socketScheme(this.protocol)}//${hostname}${this.websocketPath}`;
913
- let hasOpened = false;
914
- return new Observable((subscriber) => {
915
- const ws = new TrueNasSocket({
916
- url,
917
- openObserver: {
918
- next: () => {
919
- hasOpened = true;
920
- this.connectionAttempts.next(0);
921
- subscriber.next({ ws, hostname });
922
- }
923
- },
924
- closeObserver: {
925
- next: (event) => {
926
- const reason = event.reason || "";
927
- let errorMessage;
928
- if (isHttpStatusError(reason)) {
929
- errorMessage = getHttpError(reason);
930
- } else {
931
- errorMessage = getWebSocketError(event.code);
932
- }
933
- this.connectionAttempts.next(this.connectionAttempts.value + 1);
934
- subscriber.error(makeConnectionError(errorMessage, hostname));
935
- }
936
- }
937
- });
938
- const startupSub = ws.socket.subscribe({
939
- error: () => {
940
- }
941
- });
942
- return () => {
943
- startupSub.unsubscribe();
944
- ws.complete();
945
- };
946
- }).pipe(
947
- // retry logic:
948
- // * if a connection is not established in 10 seconds, consider that an error
949
- timeout({ first: tenSeconds }),
950
- retry({
951
- // * while still *establishing*: wait `retryDelay` before trying again, giving up
952
- // after `maxRetry` retries.
953
- count: this.maxRetry,
954
- // * we use a custom `delay` function here to ensure no retries are performed
955
- // once a socket is *opened*.
956
- // basically: a later death must propagate out rather than being retried
957
- // so it can be handled by the `connection$` observable.
958
- delay: (error) => {
959
- if (hasOpened) {
960
- return throwError(() => error);
961
- }
962
- return timer(this.retryDelay);
963
- }
964
- })
965
- );
966
- }
967
- /**
968
- * helper function which actually performs the parallel connection `race`.
969
- */
970
- connect() {
971
- return race(
972
- this.hostnames.map(this.createSocket.bind(this))
973
- ).pipe(
974
- tap((conn) => this.logger.debug(`TrueNas socket opened to ${conn.hostname}.`)),
975
- takeUntil(this.closeConnection)
976
- );
977
- }
978
- };
979
- var makeActiveConnection = (ws, hostname) => ({
980
- ws,
981
- hostname,
982
- state: "active"
983
- });
984
- var makeConnectionError = (message, hostname) => ({
985
- name: "ConnectionError",
986
- message,
987
- hostname,
988
- state: "error"
989
- });
990
- var closedConnection = { state: "closed" };
991
-
992
- // src/generated/v25_10_0/index.ts
993
- var v25_10_0_exports = {};
994
- __export(v25_10_0_exports, {
995
- ACLTemplateEntryAcltypeInput: () => ACLTemplateEntryAcltypeInput,
996
- Aclmode: () => Aclmode,
997
- Acltype: () => Acltype,
998
- Action: () => Action,
999
- Advpowermgmt: () => Advpowermgmt,
1000
- Algorithm: () => Algorithm,
1001
- AppContainerDetailsStateInput: () => AppContainerDetailsStateInput,
1002
- Atime: () => Atime,
1003
- Authenticator: () => Authenticator,
1004
- Authmethod: () => Authmethod,
1005
- Autotrim: () => Autotrim,
1006
- Basic: () => Basic,
1007
- Blocksize: () => Blocksize,
1008
- Bootloader: () => Bootloader,
1009
- Casesensitivity: () => Casesensitivity,
1010
- CloudBackupSnapshotItemType: () => CloudBackupSnapshotItemType,
1011
- CloudSyncCreateDirection: () => CloudSyncCreateDirection,
1012
- CloudSyncCreateDirectionInput: () => CloudSyncCreateDirectionInput,
1013
- CloudTaskAttributesEncryptionInput: () => CloudTaskAttributesEncryptionInput,
1014
- Code: () => Code,
1015
- Compression: () => Compression,
1016
- CorePingRemoteTypeInput: () => CorePingRemoteTypeInput,
1017
- Credentials: () => Credentials,
1018
- DeviceGetInfoOtherTypeInput: () => DeviceGetInfoOtherTypeInput,
1019
- DiskDetailsTypeInput: () => DiskDetailsTypeInput,
1020
- DiskWipeModeInput: () => DiskWipeModeInput,
1021
- DockerStatusInfoStatusInput: () => DockerStatusInfoStatusInput,
1022
- Enclosure2SetSlotStatusStatusInput: () => Enclosure2SetSlotStatusStatusInput,
1023
- Encryption: () => Encryption,
1024
- Endpoint: () => Endpoint,
1025
- Exec: () => Exec,
1026
- Feature: () => Feature,
1027
- FilesystemDirEntryType: () => FilesystemDirEntryType,
1028
- Function: () => Function,
1029
- GetDisplayDeviceType: () => GetDisplayDeviceType,
1030
- Hddstandby: () => Hddstandby,
1031
- InitShutdownScriptCreateType: () => InitShutdownScriptCreateType,
1032
- InitShutdownScriptCreateTypeInput: () => InitShutdownScriptCreateTypeInput,
1033
- InterfaceCreateAliasTypeInput: () => InterfaceCreateAliasTypeInput,
1034
- InterfaceCreateTypeInput: () => InterfaceCreateTypeInput,
1035
- Iotype: () => Iotype,
1036
- IpmiChassisIdentifyVerb: () => IpmiChassisIdentifyVerb,
1037
- IscsiExtentCreateType: () => IscsiExtentCreateType,
1038
- IscsiExtentCreateTypeInput: () => IscsiExtentCreateTypeInput,
1039
- IscsiTargetCreateMode: () => IscsiTargetCreateMode,
1040
- IscsiTargetCreateModeInput: () => IscsiTargetCreateModeInput,
1041
- KeychainCredentialEntryType: () => KeychainCredentialEntryType,
1042
- KeychainCredentialEntryTypeInput: () => KeychainCredentialEntryTypeInput,
1043
- Level: () => Level,
1044
- NFS4ACEType: () => NFS4ACEType,
1045
- NFS4ACETypeInput: () => NFS4ACETypeInput,
1046
- Name: () => Name,
1047
- Policy: () => Policy,
1048
- PoolCreateChecksum: () => PoolCreateChecksum,
1049
- PoolCreateDeduplication: () => PoolCreateDeduplication,
1050
- PoolCreateTopologyDataVdevDRAIDTypeInput: () => PoolCreateTopologyDataVdevDRAIDTypeInput,
1051
- PoolDatasetCreateFilesystemAcltypeInput: () => PoolDatasetCreateFilesystemAcltypeInput,
1052
- PoolDatasetCreateFilesystemChecksum: () => PoolDatasetCreateFilesystemChecksum,
1053
- PoolDatasetCreateFilesystemDeduplication: () => PoolDatasetCreateFilesystemDeduplication,
1054
- PoolDatasetCreateFilesystemReadonlyInput: () => PoolDatasetCreateFilesystemReadonlyInput,
1055
- PoolDatasetDeleteResult: () => PoolDatasetDeleteResult,
1056
- PoolScanStateInput: () => PoolScanStateInput,
1057
- Protocol: () => Protocol,
1058
- Purpose: () => Purpose,
1059
- Readonly: () => Readonly,
1060
- ReplicationCountEligibleManualSnapshotsTransportInput: () => ReplicationCountEligibleManualSnapshotsTransportInput,
1061
- ReplicationCreateReadonlyInput: () => ReplicationCreateReadonlyInput,
1062
- Resolution: () => Resolution,
1063
- Rpm: () => Rpm,
1064
- RsyncTaskCreateDirection: () => RsyncTaskCreateDirection,
1065
- RsyncTaskCreateDirectionInput: () => RsyncTaskCreateDirectionInput,
1066
- RsyncTaskCreateMode: () => RsyncTaskCreateMode,
1067
- RsyncTaskCreateModeInput: () => RsyncTaskCreateModeInput,
1068
- SMBEntryEncryptionInput: () => SMBEntryEncryptionInput,
1069
- STIGType: () => STIGType,
1070
- Schema: () => Schema,
1071
- Security: () => Security,
1072
- Serialspeed: () => Serialspeed,
1073
- ServiceControlVerb: () => ServiceControlVerb,
1074
- SharingSMBEntryPurposeInput: () => SharingSMBEntryPurposeInput,
1075
- SharingSMBEntryPurposeInput2: () => SharingSMBEntryPurposeInput2,
1076
- Shutdown: () => Shutdown,
1077
- Snapdev: () => Snapdev,
1078
- Snapdir: () => Snapdir,
1079
- Source: () => Source,
1080
- SourceInput: () => SourceInput,
1081
- State: () => State,
1082
- Status: () => Status,
1083
- SupportNewTicketCommunityTypeInput: () => SupportNewTicketCommunityTypeInput,
1084
- Sync: () => Sync,
1085
- SyslogServerTransportInput: () => SyslogServerTransportInput,
1086
- Sysloglevel: () => Sysloglevel,
1087
- SystemProductTypeResult: () => SystemProductTypeResult,
1088
- SystemStateResult: () => SystemStateResult,
1089
- Tag: () => Tag,
1090
- Target: () => Target,
1091
- Time: () => Time,
1092
- Transport: () => Transport,
1093
- TruecommandConfigChangedEventFieldsStatus: () => TruecommandConfigChangedEventFieldsStatus,
1094
- TruecommandConfigChangedEventFieldsStatusInput: () => TruecommandConfigChangedEventFieldsStatusInput,
1095
- TunableCreateType: () => TunableCreateType,
1096
- TunableCreateTypeInput: () => TunableCreateTypeInput,
1097
- UPSEntryMode: () => UPSEntryMode,
1098
- UPSEntryModeInput: () => UPSEntryModeInput,
1099
- Unixcharset: () => Unixcharset,
1100
- Username: () => Username,
1101
- VMDiskDeviceType: () => VMDiskDeviceType,
1102
- VMDiskDeviceTypeInput: () => VMDiskDeviceTypeInput,
1103
- VMWareEntryStateStateInput: () => VMWareEntryStateStateInput,
1104
- VMWareMatchDatastoresWithDatasetsResultFilesystemType: () => VMWareMatchDatastoresWithDatasetsResultFilesystemType,
1105
- Vendor: () => Vendor,
1106
- Volblocksize: () => Volblocksize,
1107
- When: () => When,
1108
- ZfsTierRewriteJobEntryStatusInput: () => ZfsTierRewriteJobEntryStatusInput
1109
- });
1110
-
1111
- // src/generated/v25_10_0/api-types.ts
1112
- var Aclmode = {
1113
- Passthrough: "PASSTHROUGH",
1114
- Restricted: "RESTRICTED",
1115
- Discard: "DISCARD",
1116
- Inherit: "INHERIT"
1117
- };
1118
- var ACLTemplateEntryAcltypeInput = {
1119
- Nfs4: "NFS4",
1120
- Posix1e: "POSIX1E"
1121
- };
1122
- var Acltype = {
1123
- Nfs4: "NFS4",
1124
- Posix1e: "POSIX1E"
1125
- };
1126
- var Action = {
1127
- Start: "START",
1128
- Stop: "STOP",
1129
- Pause: "PAUSE"
1130
- };
1131
- var Advpowermgmt = {
1132
- Disabled: "DISABLED",
1133
- "1": "1",
1134
- "64": "64",
1135
- "127": "127",
1136
- "128": "128",
1137
- "192": "192",
1138
- "254": "254"
509
+ var Advpowermgmt = {
510
+ Disabled: "DISABLED",
511
+ "1": "1",
512
+ "64": "64",
513
+ "127": "127",
514
+ "128": "128",
515
+ "192": "192",
516
+ "254": "254"
1139
517
  };
1140
518
  var Algorithm = {
1141
519
  Aes128Ccm: "AES-128-CCM",
@@ -2870,141 +2248,871 @@ __export(v27_0_0_exports, {
2870
2248
  ZpoolScrubRunAction: () => ZpoolScrubRunAction
2871
2249
  });
2872
2250
 
2873
- // src/generated/index.ts
2874
- var SUPPORTED_API_VERSIONS = [
2875
- "v25.10.0",
2876
- "v25.10.1",
2877
- "v25.10.2",
2878
- "v25.10.3",
2879
- "v25.10.4",
2880
- "v25.10.5",
2881
- "v26.0.0",
2882
- "v27.0.0"
2883
- ];
2251
+ // src/generated/index.ts
2252
+ var SUPPORTED_API_VERSIONS = [
2253
+ "v25.10.0",
2254
+ "v25.10.1",
2255
+ "v25.10.2",
2256
+ "v25.10.3",
2257
+ "v25.10.4",
2258
+ "v25.10.5",
2259
+ "v26.0.0",
2260
+ "v27.0.0"
2261
+ ];
2262
+
2263
+ // src/config/api-version.config.ts
2264
+ var apiVersionConfig = {
2265
+ /**
2266
+ * Minimum supported API version. Systems below it are rejected.
2267
+ *
2268
+ * DERIVED, not declared. The client supports exactly the versions it ships
2269
+ * types for, so the oldest generated version *is* the minimum — there is no
2270
+ * second decision to make, and therefore nothing to keep in sync.
2271
+ *
2272
+ * To move the floor, change `--min-version` in the `generate:api` script in
2273
+ * package.json and regenerate; this follows on its own. Written as a literal
2274
+ * it would duplicate that value with nothing enforcing agreement, so raising
2275
+ * one and forgetting the other would silently keep generating types for
2276
+ * versions the client rejects.
2277
+ */
2278
+ MIN_SUPPORTED_VERSION: SUPPORTED_API_VERSIONS[0],
2279
+ /**
2280
+ * Maximum supported API version. Systems above it are rejected.
2281
+ *
2282
+ * NOT derived, deliberately — and for a different reason than it used to
2283
+ * lag. It sat at v26.0.0 while types for v27 already shipped, because
2284
+ * `CLIENT_BY_VERSION_KEY` had no `27` and a v27 system would have passed the
2285
+ * range check only to throw on client selection. `TrueNasApiClientV27` now
2286
+ * exists, so this moves up with it.
2287
+ *
2288
+ * What it must not become is `SUPPORTED_API_VERSIONS[length - 1]`, the mirror
2289
+ * of how MIN is derived. MIN is safe to derive because the oldest generated
2290
+ * version always has a client — it is the floor the clients were built from.
2291
+ * The ceiling is not symmetric: generating types for v28 does not write a v28
2292
+ * client, so deriving this would re-create the exact gap described above on
2293
+ * the next regeneration, silently. The real invariant is "the newest version
2294
+ * a client can be built for", which lives in `CLIENT_BY_VERSION_KEY`; a
2295
+ * factory test asserts the two agree, which is the check that keeps this
2296
+ * literal honest without importing the factory here.
2297
+ */
2298
+ MAX_SUPPORTED_VERSION: "v27.0.0",
2299
+ /**
2300
+ * Fallback version to use when version discovery fails due to CORS/network errors.
2301
+ * When /api/versions returns HTTP status 0 (CORS block, network down, etc.),
2302
+ * the system will attempt to connect using this version as a best-effort fallback.
2303
+ *
2304
+ * WARNING: Status 0 errors have multiple causes:
2305
+ * - CORS policy blocking the request
2306
+ * - Network disconnected
2307
+ * - DNS lookup failure
2308
+ * - Server unreachable
2309
+ *
2310
+ * Using this fallback means systems with genuine network issues will still
2311
+ * attempt connection (and fail during WebSocket handshake instead of immediately).
2312
+ */
2313
+ FALLBACK_VERSION: "v25.10.0"
2314
+ };
2315
+
2316
+ // src/types/api-version.type.ts
2317
+ var VersionCompatibility = /* @__PURE__ */ ((VersionCompatibility2) => {
2318
+ VersionCompatibility2["Compatible"] = "compatible";
2319
+ VersionCompatibility2["TooOld"] = "too-old";
2320
+ VersionCompatibility2["TooNew"] = "too-new";
2321
+ VersionCompatibility2["Invalid"] = "invalid";
2322
+ return VersionCompatibility2;
2323
+ })(VersionCompatibility || {});
2324
+
2325
+ // src/utils/api-version.utils.ts
2326
+ var legacyCutoffYear = 25;
2327
+ function parseApiVersion(versionString) {
2328
+ const regex = /^v(\d{2})\.(\d+)\.(\d+)$/;
2329
+ const match = versionString.match(regex);
2330
+ if (!match) {
2331
+ return null;
2332
+ }
2333
+ const [, yearStr, minorStr, patchStr] = match;
2334
+ const year = parseInt(yearStr, 10);
2335
+ const minor = parseInt(minorStr, 10);
2336
+ const patch = parseInt(patchStr, 10);
2337
+ if (year <= legacyCutoffYear) {
2338
+ if (minor < 1 || minor > 12) {
2339
+ return null;
2340
+ }
2341
+ } else if (year >= 26) {
2342
+ if (minor < 0 || minor > 99) {
2343
+ return null;
2344
+ }
2345
+ }
2346
+ return {
2347
+ version: versionString,
2348
+ year,
2349
+ minor,
2350
+ patch,
2351
+ websocketPath: `/api/${versionString}`
2352
+ };
2353
+ }
2354
+ function compareVersions(a, b) {
2355
+ if (a.year !== b.year) {
2356
+ return a.year - b.year;
2357
+ }
2358
+ if (a.minor !== b.minor) {
2359
+ return a.minor - b.minor;
2360
+ }
2361
+ return a.patch - b.patch;
2362
+ }
2363
+ function checkVersionCompatibility(version) {
2364
+ const minVersion = parseApiVersion(apiVersionConfig.MIN_SUPPORTED_VERSION);
2365
+ const maxVersion = parseApiVersion(apiVersionConfig.MAX_SUPPORTED_VERSION);
2366
+ if (!minVersion || !maxVersion) {
2367
+ return "invalid" /* Invalid */;
2368
+ }
2369
+ if (compareVersions(version, minVersion) < 0) {
2370
+ return "too-old" /* TooOld */;
2371
+ }
2372
+ if (compareVersions(version, maxVersion) > 0) {
2373
+ return "too-new" /* TooNew */;
2374
+ }
2375
+ return "compatible" /* Compatible */;
2376
+ }
2377
+ function isVersionSupported(version) {
2378
+ return checkVersionCompatibility(version) === "compatible" /* Compatible */;
2379
+ }
2380
+ function filterCompatibleVersions(versions) {
2381
+ return versions.filter(isVersionSupported);
2382
+ }
2383
+ function getWebSocketPath(version) {
2384
+ return version.websocketPath;
2385
+ }
2386
+
2387
+ // src/enums/truenas-auth-mechanism.enum.ts
2388
+ var TrueNasAuthMechanism = /* @__PURE__ */ ((TrueNasAuthMechanism2) => {
2389
+ TrueNasAuthMechanism2["ApiKey"] = "API_KEY_PLAIN";
2390
+ TrueNasAuthMechanism2["Password"] = "PASSWORD_PLAIN";
2391
+ TrueNasAuthMechanism2["Otp"] = "OTP_TOKEN";
2392
+ TrueNasAuthMechanism2["Token"] = "TOKEN_PLAIN";
2393
+ return TrueNasAuthMechanism2;
2394
+ })(TrueNasAuthMechanism || {});
2395
+
2396
+ // src/errors/auth.errors.ts
2397
+ var AuthErrorCode = /* @__PURE__ */ ((AuthErrorCode2) => {
2398
+ AuthErrorCode2["PasswordAuthFailed"] = "PASSWORD_AUTH_FAILED";
2399
+ AuthErrorCode2["OtpAuthFailed"] = "OTP_AUTH_FAILED";
2400
+ AuthErrorCode2["ApiKeyAuthFailed"] = "API_KEY_AUTH_FAILED";
2401
+ AuthErrorCode2["TokenAuthFailed"] = "TOKEN_AUTH_FAILED";
2402
+ AuthErrorCode2["FullAdminRequired"] = "FULL_ADMIN_REQUIRED";
2403
+ return AuthErrorCode2;
2404
+ })(AuthErrorCode || {});
2405
+ var AuthError = class _AuthError extends Error {
2406
+ constructor(code, message) {
2407
+ super(message);
2408
+ this.code = code;
2409
+ this.name = "AuthError";
2410
+ Object.setPrototypeOf(this, _AuthError.prototype);
2411
+ }
2412
+ };
2413
+
2414
+ // src/auth/truenas-authenticator.ts
2415
+ var throwOnAuthenticationFailure = (code, message) => switchMap((response) => {
2416
+ if (response.response_type === "AUTH_ERR" /* AuthErr */) {
2417
+ return throwError(() => new AuthError(code, message));
2418
+ }
2419
+ return of(response);
2420
+ });
2421
+ var TrueNasAuthenticator = class _TrueNasAuthenticator {
2422
+ constructor(connection, version) {
2423
+ this.connection = connection;
2424
+ this.version = version;
2425
+ // in seconds (5 minutes)
2426
+ /**
2427
+ * whether or not the system is currently authenticated and accessible.
2428
+ * this is a `BehaviorSubject` instead of a signal, since we use its `getValue` method
2429
+ * throughout a lot of the codebase.
2430
+ */
2431
+ this.authenticated$ = new BehaviorSubject(false);
2432
+ /**
2433
+ * `true` when the system is currently being authenticated to, and `false` otherwise.
2434
+ * does not indicate whatsoever if authentication is successful or not, just whether the process
2435
+ * is ongoing.
2436
+ */
2437
+ this.authenticating$ = new BehaviorSubject(false);
2438
+ this.credentials = { username: "", password: "", key: "" };
2439
+ this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
2440
+ this.connection.opened.pipe(
2441
+ filter(
2442
+ (isOpen) => !!(isOpen && this.credentials?.username && (this.credentials.password || this.credentials.key))
2443
+ ),
2444
+ switchMap(() => {
2445
+ if (this.credentials.password) {
2446
+ return this.loginWithUserPass(
2447
+ this.credentials.username,
2448
+ this.credentials.password
2449
+ );
2450
+ }
2451
+ return this.loginWithApiKey({
2452
+ username: this.credentials.username,
2453
+ key: this.credentials.key
2454
+ });
2455
+ })
2456
+ ).subscribe();
2457
+ connection.closed.subscribe(() => {
2458
+ this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
2459
+ this.authenticated$.next(false);
2460
+ });
2461
+ }
2462
+ static {
2463
+ this.DefaultSessionLifetime = 300;
2464
+ }
2465
+ /**
2466
+ * `login_options` asking for a reconnect token, when the server understands it.
2467
+ *
2468
+ * Omitted below v26. `AuthCommonOptions` is `additionalProperties: false`
2469
+ * there and has only `user_info`, so sending the member is a validation
2470
+ * error, not an ignored field — it would fail login outright on the oldest
2471
+ * version this client supports.
2472
+ */
2473
+ /**
2474
+ * Two things this does not do, both deliberate and both worth knowing.
2475
+ *
2476
+ * There is no way for a consumer to decline: every v26+ password login now
2477
+ * mints a single-use credential carrying that session's roles, whether or not
2478
+ * the caller wants one. And the auto-relogin in the constructor subscribes
2479
+ * with no observer, so the token it mints is dropped — a caller reconnecting
2480
+ * repeatedly holds an ageing token while the appliance mints fresh ones
2481
+ * nobody reads. Tokens are single-use with a 600s TTL, so that is the
2482
+ * reconnect case the feature is named for.
2483
+ */
2484
+ reconnectTokenOption() {
2485
+ if (!this.version || this.version.year <= legacyCutoffYear) return void 0;
2486
+ return { login_options: { reconnect_token: true } };
2487
+ }
2488
+ loginWithUserPass(username, password) {
2489
+ const message = createJsonRpcMessage("auth.login_ex", [
2490
+ {
2491
+ mechanism: "PASSWORD_PLAIN" /* Password */,
2492
+ username,
2493
+ password,
2494
+ ...this.reconnectTokenOption()
2495
+ }
2496
+ ]);
2497
+ this.authenticating$.next(true);
2498
+ this.connection.send(message);
2499
+ const messageId = message.id ?? "";
2500
+ return this.connection.messages().pipe(
2501
+ withId(messageId),
2502
+ map((msg) => {
2503
+ if (msg.error) {
2504
+ const errorMessage = getApiErrorMessage(
2505
+ msg.error,
2506
+ "Authentication failed"
2507
+ );
2508
+ throw new Error(errorMessage);
2509
+ }
2510
+ return msg.result;
2511
+ }),
2512
+ throwOnAuthenticationFailure(
2513
+ "PASSWORD_AUTH_FAILED" /* PasswordAuthFailed */,
2514
+ "TrueNAS authentication failed. Please verify your TrueNAS user credentials and try again."
2515
+ ),
2516
+ tap((res) => {
2517
+ if (res.response_type === "SUCCESS" /* Success */) {
2518
+ if (res.user_info?.privilege.roles.$set.includes("FULL_ADMIN" /* FullAdmin */)) {
2519
+ this.credentials.username = username;
2520
+ this.credentials.password = password;
2521
+ this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
2522
+ this.authenticated$.next(true);
2523
+ } else {
2524
+ this.logout();
2525
+ this.authenticated$.next(false);
2526
+ throw new AuthError(
2527
+ "FULL_ADMIN_REQUIRED" /* FullAdminRequired */,
2528
+ "User account must have full admin privileges"
2529
+ );
2530
+ }
2531
+ }
2532
+ }),
2533
+ finalize(() => {
2534
+ this.authenticating$.next(false);
2535
+ }),
2536
+ take(1)
2537
+ );
2538
+ }
2539
+ loginWithOtp(code) {
2540
+ const message = createJsonRpcMessage("auth.login_ex", [
2541
+ {
2542
+ mechanism: "OTP_TOKEN" /* Otp */,
2543
+ otp_token: code
2544
+ }
2545
+ ]);
2546
+ this.authenticating$.next(true);
2547
+ this.connection.send(message);
2548
+ const messageId = message.id ?? "";
2549
+ return this.connection.messages().pipe(
2550
+ withId(messageId),
2551
+ map((msg) => {
2552
+ if (msg.error) {
2553
+ const errorMessage = getApiErrorMessage(
2554
+ msg.error,
2555
+ "Authentication failed"
2556
+ );
2557
+ throw new Error(errorMessage);
2558
+ }
2559
+ return msg.result;
2560
+ }),
2561
+ tap((res) => {
2562
+ if (res?.response_type === "SUCCESS" /* Success */) {
2563
+ this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
2564
+ this.authenticated$.next(true);
2565
+ }
2566
+ }),
2567
+ throwOnAuthenticationFailure(
2568
+ "OTP_AUTH_FAILED" /* OtpAuthFailed */,
2569
+ "TrueNAS authentication failed. Please verify your one-time passcode and try again."
2570
+ ),
2571
+ finalize(() => {
2572
+ this.authenticating$.next(false);
2573
+ }),
2574
+ take(1)
2575
+ );
2576
+ }
2577
+ /**
2578
+ * Re-authenticate with a token from a previous login's `reconnect_token`.
2579
+ *
2580
+ * This is what lets a second connection to the same appliance authenticate
2581
+ * without asking the user for a password again — middleware sessions are
2582
+ * per-connection, so a second socket has its own to establish.
2583
+ *
2584
+ * The token is single-use and short-lived. On v26+ a successful login mints
2585
+ * another on the response, so a caller keeping a session alive across
2586
+ * reconnects stores the newest each time; below v26 nothing is minted and
2587
+ * there is no chain to keep.
2588
+ *
2589
+ * Re-login is the caller's to drive. A token session is not covered by the
2590
+ * automatic reconnect this class does for password and api-key sessions,
2591
+ * which is deliberate — the token is single-use — but it means a dropped
2592
+ * socket needs the stored token spending explicitly. Middleware holds tokens
2593
+ * in memory, so a `middlewared` restart voids them, and that is a common
2594
+ * reason the socket dropped in the first place.
2595
+ */
2596
+ loginWithToken(token) {
2597
+ const message = createJsonRpcMessage("auth.login_ex", [
2598
+ {
2599
+ mechanism: "TOKEN_PLAIN" /* Token */,
2600
+ token,
2601
+ ...this.reconnectTokenOption()
2602
+ }
2603
+ ]);
2604
+ this.authenticating$.next(true);
2605
+ this.connection.send(message);
2606
+ const messageId = message.id ?? "";
2607
+ return this.connection.messages().pipe(
2608
+ withId(messageId),
2609
+ map((msg) => {
2610
+ if (msg.error) {
2611
+ const errorMessage = getApiErrorMessage(
2612
+ msg.error,
2613
+ "Authentication failed"
2614
+ );
2615
+ throw new Error(errorMessage);
2616
+ }
2617
+ return msg.result;
2618
+ }),
2619
+ // Password login lets non-`AUTH_ERR` answers through because it has to
2620
+ // hand `OTP_REQUIRED` back to the caller. Token login has no such case:
2621
+ // middleware answers `EXPIRED` for an account locked or expired between
2622
+ // minting and spending, and `DENIED` for a permission refusal, so letting
2623
+ // those reach `next` would report a failed login as a successful one.
2624
+ map((res) => {
2625
+ if (res.response_type !== "SUCCESS" /* Success */) {
2626
+ throw new AuthError(
2627
+ "TOKEN_AUTH_FAILED" /* TokenAuthFailed */,
2628
+ `TrueNAS token authentication failed (${res.response_type}). The token may have expired or been used, or the account may no longer be permitted to log in.`
2629
+ );
2630
+ }
2631
+ return res;
2632
+ }),
2633
+ tap((res) => {
2634
+ if (res.response_type === "SUCCESS" /* Success */) {
2635
+ if (res.user_info?.privilege.roles.$set.includes("FULL_ADMIN" /* FullAdmin */)) {
2636
+ this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
2637
+ this.authenticated$.next(true);
2638
+ } else {
2639
+ this.logout();
2640
+ this.authenticated$.next(false);
2641
+ throw new AuthError(
2642
+ "FULL_ADMIN_REQUIRED" /* FullAdminRequired */,
2643
+ "User account must have full admin privileges"
2644
+ );
2645
+ }
2646
+ }
2647
+ }),
2648
+ finalize(() => {
2649
+ this.authenticating$.next(false);
2650
+ }),
2651
+ take(1)
2652
+ );
2653
+ }
2654
+ /**
2655
+ * No reconnect token is requested here, though v26+ would mint one: an
2656
+ * api-key session already reconnects without a prompt, since the key is held
2657
+ * and replayed. The token exists for the credential that cannot be.
2658
+ */
2659
+ loginWithApiKey(credentials) {
2660
+ const { username, key } = credentials;
2661
+ const message = createJsonRpcMessage("auth.login_ex", [
2662
+ {
2663
+ mechanism: "API_KEY_PLAIN" /* ApiKey */,
2664
+ username,
2665
+ api_key: key
2666
+ }
2667
+ ]);
2668
+ this.authenticating$.next(true);
2669
+ this.connection.send(message);
2670
+ const messageId = message.id ?? "";
2671
+ return this.connection.messages().pipe(
2672
+ withId(messageId),
2673
+ map((msg) => {
2674
+ if (msg.error) {
2675
+ const errorMessage = getApiErrorMessage(
2676
+ msg.error,
2677
+ "Authentication failed"
2678
+ );
2679
+ throw new Error(errorMessage);
2680
+ }
2681
+ return msg.result;
2682
+ }),
2683
+ throwOnAuthenticationFailure(
2684
+ "API_KEY_AUTH_FAILED" /* ApiKeyAuthFailed */,
2685
+ "TrueNAS authentication failed. Has the TrueNAS Connect API key been removed from your TrueNAS server?"
2686
+ ),
2687
+ tap((res) => {
2688
+ this.credentials.username = username;
2689
+ this.credentials.key = key;
2690
+ this.sessionLifetime = res.user_info?.attributes?.preferences?.lifetime ?? _TrueNasAuthenticator.DefaultSessionLifetime;
2691
+ this.authenticated$.next(true);
2692
+ }),
2693
+ finalize(() => {
2694
+ this.authenticating$.next(false);
2695
+ }),
2696
+ take(1)
2697
+ );
2698
+ }
2699
+ newApiKey(username) {
2700
+ const message = createJsonRpcMessage("api_key.create", [
2701
+ { name: `tnc-${randomUUID()}`, username }
2702
+ ]);
2703
+ this.connection.send(message);
2704
+ const messageId = message.id ?? "";
2705
+ return this.connection.messages().pipe(
2706
+ withId(messageId),
2707
+ map((msg) => {
2708
+ if (msg.error) {
2709
+ const errorMessage = getApiErrorMessage(
2710
+ msg.error,
2711
+ "Failed to create API key"
2712
+ );
2713
+ throw new Error(errorMessage);
2714
+ }
2715
+ return msg.result;
2716
+ }),
2717
+ take(1)
2718
+ );
2719
+ }
2720
+ logout() {
2721
+ const message = createJsonRpcMessage("auth.logout");
2722
+ this.connection.send(message);
2723
+ const messageId = message.id ?? "";
2724
+ return this.connection.messages().pipe(
2725
+ withId(messageId),
2726
+ map((msg) => {
2727
+ if (msg.error) {
2728
+ return false;
2729
+ }
2730
+ return msg.result;
2731
+ }),
2732
+ tap((success) => {
2733
+ this.sessionLifetime = _TrueNasAuthenticator.DefaultSessionLifetime;
2734
+ this.authenticated$.next(!success);
2735
+ }),
2736
+ take(1)
2737
+ );
2738
+ }
2739
+ };
2740
+
2741
+ // src/logger.ts
2742
+ var consoleLogger = {
2743
+ trace: (message, ...args) => console.trace(message, ...args),
2744
+ debug: (message, ...args) => console.debug(message, ...args),
2745
+ info: (message, ...args) => console.info(message, ...args),
2746
+ warn: (message, ...args) => console.warn(message, ...args),
2747
+ error: (message, ...args) => console.error(message, ...args)
2748
+ };
2749
+ var noop = () => void 0;
2750
+ var noopLogger = {
2751
+ trace: noop,
2752
+ debug: noop,
2753
+ info: noop,
2754
+ warn: noop,
2755
+ error: noop
2756
+ };
2884
2757
 
2885
- // src/config/api-version.config.ts
2886
- var apiVersionConfig = {
2758
+ // src/utils/truenas-connection.utils.ts
2759
+ function isHttpStatusError(reason) {
2760
+ return ["404", "502", "503"].some((code) => reason.includes(code));
2761
+ }
2762
+ function getHttpError(reason) {
2763
+ if (reason.includes("404")) {
2764
+ return "API endpoint not found - System may not support versioned API";
2765
+ }
2766
+ if (reason.includes("502")) {
2767
+ return "Bad Gateway - System may be starting up";
2768
+ }
2769
+ if (reason.includes("503")) {
2770
+ return "Service Unavailable - System may be overloaded";
2771
+ }
2772
+ return "";
2773
+ }
2774
+ function getWebSocketError(code) {
2775
+ switch (code) {
2776
+ case 1e3:
2777
+ return "Connection closed normally";
2778
+ case 1001:
2779
+ return "Server is shutting down or restarting";
2780
+ case 1002:
2781
+ return "Protocol error - Invalid WebSocket communication";
2782
+ case 1003:
2783
+ return "Unsupported data format received";
2784
+ case 1006:
2785
+ return "Connection lost unexpectedly - Check network connectivity";
2786
+ case 1007:
2787
+ return "Invalid data received from server";
2788
+ case 1008:
2789
+ return "Connection terminated due to policy violation";
2790
+ case 1009:
2791
+ return "Message size exceeded server limits";
2792
+ case 1011:
2793
+ return "Server encountered an internal error";
2794
+ case 1012:
2795
+ return "Service is restarting";
2796
+ case 1013:
2797
+ return "Server temporarily overloaded - Try again later";
2798
+ case 1015:
2799
+ return "TLS/Certificate error - Certificate may be expired";
2800
+ default:
2801
+ return "Network connection failed - Check IP address and connectivity";
2802
+ }
2803
+ }
2804
+ var TrueNasSocket = class {
2805
+ constructor(config) {
2806
+ this.config = config;
2807
+ this.socket = webSocket(this.config);
2808
+ }
2809
+ messages() {
2810
+ return this.socket;
2811
+ }
2812
+ next(msg) {
2813
+ this.socket.next(msg);
2814
+ }
2815
+ complete() {
2816
+ this.socket.complete();
2817
+ }
2818
+ };
2819
+
2820
+ // src/types/transport.type.ts
2821
+ function httpScheme(protocol) {
2822
+ return protocol === "http:" ? "http:" : "https:";
2823
+ }
2824
+ function socketScheme(protocol) {
2825
+ return protocol === "http:" ? "ws:" : "wss:";
2826
+ }
2827
+
2828
+ // src/connection/truenas-connection.ts
2829
+ var tenSeconds = 10 * 1e3;
2830
+ var twentySeconds = 20 * 1e3;
2831
+ var TrueNasConnection = class {
2832
+ constructor(initialEnabled, hostnames, systemUuid, websocketPath, systemName, retryDelay = tenSeconds, maxRetry = 3, logger = noopLogger, protocol = "https:") {
2833
+ this.hostnames = hostnames;
2834
+ this.systemUuid = systemUuid;
2835
+ this.websocketPath = websocketPath;
2836
+ this.systemName = systemName;
2837
+ this.retryDelay = retryDelay;
2838
+ this.maxRetry = maxRetry;
2839
+ this.logger = logger;
2840
+ this.protocol = protocol;
2841
+ // compatibility properties
2842
+ this.opened = new BehaviorSubject(false);
2843
+ this.closed = new Subject();
2844
+ this.hostname = new BehaviorSubject("");
2845
+ this.connectionAttempts = new BehaviorSubject(0);
2846
+ this.lastErrorMessage = new BehaviorSubject(null);
2847
+ /**
2848
+ * emits when the connection is manually closed.
2849
+ */
2850
+ this.closeConnection = new Subject();
2851
+ /**
2852
+ * the connection only establishes a socket while this gate is `true`. consumers
2853
+ * flip it via `setEnabled()` (the app maps `SystemState.Active -> true`).
2854
+ */
2855
+ this.enabled$ = new BehaviorSubject(false);
2856
+ /**
2857
+ * observable which emits the current gate value and only emits again when it changes.
2858
+ */
2859
+ this.enabledChange$ = this.enabled$.pipe(distinctUntilChanged());
2860
+ /**
2861
+ * observable that handles the entire connection lifecycle.
2862
+ */
2863
+ this.connection$ = this.enabledChange$.pipe(
2864
+ switchMap((enabled) => {
2865
+ if (enabled) {
2866
+ return this.connect().pipe(
2867
+ map((conn) => makeActiveConnection(conn.ws, conn.hostname))
2868
+ );
2869
+ }
2870
+ return of(closedConnection);
2871
+ }),
2872
+ switchMap((connection) => {
2873
+ if (connection.state !== "active") {
2874
+ return of(connection);
2875
+ }
2876
+ const initMessage = createJsonRpcMessage("core.set_options", [
2877
+ { legacy_jobs: false }
2878
+ ]);
2879
+ connection.ws.next(initMessage);
2880
+ return connection.ws.messages().pipe(
2881
+ filter((msg) => msg.id === initMessage.id),
2882
+ take(1),
2883
+ map(() => connection)
2884
+ );
2885
+ }),
2886
+ // in the event of an error, do two things:
2887
+ // 1. emit an errored connection downstream to inform consumers that
2888
+ // the connection is dead.
2889
+ // 2. re-throw an error so the downstream `retry` will re-subscribe.
2890
+ catchError$1((err) => {
2891
+ this.logger.error("All connections failed - retrying", { message: err?.message, hostname: err?.hostname });
2892
+ return concat(
2893
+ of(makeConnectionError(err.message, err.hostname)),
2894
+ // since this error will immediately get caught by `retry` there's no reason to build a real error.
2895
+ throwError(() => null)
2896
+ );
2897
+ }),
2898
+ retry(),
2899
+ // start with a closed connection.
2900
+ startWith(closedConnection),
2901
+ // prevent multiple subscriptions from re-evaluating the entire pipeline.
2902
+ shareReplay$1({ bufferSize: 1, refCount: false }),
2903
+ takeUntil(this.closeConnection)
2904
+ );
2905
+ /**
2906
+ * observable which is either an instance of the current `TrueNasSocket` used for the connection
2907
+ * or `null` if the connection is closed or errored for any reason.
2908
+ */
2909
+ this.ws$ = this.connection$.pipe(
2910
+ map((conn) => conn.state === "active" ? conn.ws : null)
2911
+ );
2912
+ /**
2913
+ * current hostname we used to build the URL for this connection.
2914
+ */
2915
+ this.hostname$ = this.connection$.pipe(
2916
+ map((conn) => conn.state === "active" ? conn.hostname : null)
2917
+ );
2918
+ /**
2919
+ * emits error messages from the connection pipeline. this is used to derive the
2920
+ * corresponding compatibility property.
2921
+ */
2922
+ this.lastErrorMessage$ = this.connection$.pipe(
2923
+ map((conn) => conn.state === "error" ? conn.message : null)
2924
+ );
2925
+ /**
2926
+ * emits when the connection state *changes*, so it'll never emit `true` twice
2927
+ * in a row nor `false` twice in a row.
2928
+ */
2929
+ this.opened$ = this.connection$.pipe(
2930
+ map((conn) => conn.state),
2931
+ distinctUntilChanged(),
2932
+ map((state) => state === "active")
2933
+ );
2934
+ /**
2935
+ * emits when the connection state goes from open to closed.
2936
+ */
2937
+ this.closed$ = this.connection$.pipe(
2938
+ map((conn) => conn.state),
2939
+ distinctUntilChanged(),
2940
+ filter((state) => state === "closed" || state === "error"),
2941
+ map(() => {
2942
+ })
2943
+ );
2944
+ /**
2945
+ * whether to display a connection error to the user — the **live** signal.
2946
+ *
2947
+ * `true` only while `connection$` is currently a `ConnectionError`, meaning the entire race +
2948
+ * retry cycle has been exhausted for all hostnames right now; it flips back to `false` once a
2949
+ * connection is re-established. individual socket losses during a race are expected and not surfaced.
2950
+ *
2951
+ * NOTE: this is NOT the same as the `hasExhaustedRetries()` method, which is a **cumulative**
2952
+ * snapshot (see there). The two can disagree — prefer this observable for "is the connection
2953
+ * errored right now?".
2954
+ */
2955
+ this.hasConnectionError$ = this.connection$.pipe(
2956
+ map((conn) => conn.state === "error"),
2957
+ takeUntil(this.closeConnection)
2958
+ );
2959
+ /**
2960
+ * observable which always emits messages from the current socket.
2961
+ */
2962
+ this.messages$ = this.ws$.pipe(
2963
+ filter((ws) => ws !== null),
2964
+ switchMap((ws) => ws.messages().pipe(
2965
+ catchError$1(() => EMPTY)
2966
+ ))
2967
+ );
2968
+ combineLatest([
2969
+ interval(twentySeconds),
2970
+ this.ws$
2971
+ ]).pipe(
2972
+ takeUntil(this.closeConnection)
2973
+ ).subscribe(([, ws]) => {
2974
+ if (ws) {
2975
+ const pingMessage = createJsonRpcMessage("core.ping");
2976
+ ws.next(pingMessage);
2977
+ }
2978
+ });
2979
+ this.opened$.subscribe((val) => this.opened.next(val));
2980
+ this.closed$.subscribe(() => this.closed.next());
2981
+ this.hostname$.pipe(filter(Boolean)).subscribe((name) => this.hostname.next(name));
2982
+ this.ws$.pipe(filter(Boolean)).subscribe((ws) => this.ws = ws);
2983
+ this.lastErrorMessage$.subscribe((msg) => this.lastErrorMessage.next(msg));
2984
+ this.enabled$.next(initialEnabled);
2985
+ }
2887
2986
  /**
2888
- * Minimum supported API version. Systems below it are rejected.
2889
- *
2890
- * DERIVED, not declared. The client supports exactly the versions it ships
2891
- * types for, so the oldest generated version *is* the minimum — there is no
2892
- * second decision to make, and therefore nothing to keep in sync.
2987
+ * whether the connection has exhausted its retries the **cumulative** snapshot, read
2988
+ * synchronously. (Formerly `hasConnectionError()`; renamed to disambiguate it from the
2989
+ * live `hasConnectionError$` observable, with which it can disagree.)
2893
2990
  *
2894
- * To move the floor, change `--min-version` in the `generate:api` script in
2895
- * package.json and regenerate; this follows on its own. Written as a literal
2896
- * it would duplicate that value with nothing enforcing agreement, so raising
2897
- * one and forgetting the other would silently keep generating types for
2898
- * versions the client rejects.
2991
+ * `true` when the lifetime `connectionAttempts` count exceeds `hostnames.length * maxRetry`,
2992
+ * OR when an error message is currently set. Ported from the source (tncui) behavior.
2899
2993
  */
2900
- MIN_SUPPORTED_VERSION: SUPPORTED_API_VERSIONS[0],
2994
+ hasExhaustedRetries() {
2995
+ const attemptsExhausted = this.connectionAttempts.value > this.hostnames.length * this.maxRetry;
2996
+ const hasErrorMessage = this.lastErrorMessage.value !== null;
2997
+ return attemptsExhausted || hasErrorMessage;
2998
+ }
2901
2999
  /**
2902
- * Maximum supported API version. Systems above it are rejected.
2903
- *
2904
- * NOT derived, deliberately — and for a different reason than it used to
2905
- * lag. It sat at v26.0.0 while types for v27 already shipped, because
2906
- * `CLIENT_BY_VERSION_KEY` had no `27` and a v27 system would have passed the
2907
- * range check only to throw on client selection. `TrueNasApiClientV27` now
2908
- * exists, so this moves up with it.
2909
- *
2910
- * What it must not become is `SUPPORTED_API_VERSIONS[length - 1]`, the mirror
2911
- * of how MIN is derived. MIN is safe to derive because the oldest generated
2912
- * version always has a client — it is the floor the clients were built from.
2913
- * The ceiling is not symmetric: generating types for v28 does not write a v28
2914
- * client, so deriving this would re-create the exact gap described above on
2915
- * the next regeneration, silently. The real invariant is "the newest version
2916
- * a client can be built for", which lives in `CLIENT_BY_VERSION_KEY`; a
2917
- * factory test asserts the two agree, which is the check that keeps this
2918
- * literal honest without importing the factory here.
3000
+ * enables or disables the connection gate. the app calls this when its `SystemState`
3001
+ * changes (mapping `SystemState.Active -> true`, everything else -> `false`).
2919
3002
  */
2920
- MAX_SUPPORTED_VERSION: "v27.0.0",
3003
+ setEnabled(enabled) {
3004
+ this.enabled$.next(enabled);
3005
+ }
2921
3006
  /**
2922
- * Fallback version to use when version discovery fails due to CORS/network errors.
2923
- * When /api/versions returns HTTP status 0 (CORS block, network down, etc.),
2924
- * the system will attempt to connect using this version as a best-effort fallback.
2925
- *
2926
- * WARNING: Status 0 errors have multiple causes:
2927
- * - CORS policy blocking the request
2928
- * - Network disconnected
2929
- * - DNS lookup failure
2930
- * - Server unreachable
2931
- *
2932
- * Using this fallback means systems with genuine network issues will still
2933
- * attempt connection (and fail during WebSocket handshake instead of immediately).
3007
+ * compatibility method which just returns the public `messages$` observable.
3008
+ * this is used in a few places in the codebase that relied upon the old implementation.
2934
3009
  */
2935
- FALLBACK_VERSION: "v25.10.0"
2936
- };
2937
-
2938
- // src/types/api-version.type.ts
2939
- var VersionCompatibility = /* @__PURE__ */ ((VersionCompatibility2) => {
2940
- VersionCompatibility2["Compatible"] = "compatible";
2941
- VersionCompatibility2["TooOld"] = "too-old";
2942
- VersionCompatibility2["TooNew"] = "too-new";
2943
- VersionCompatibility2["Invalid"] = "invalid";
2944
- return VersionCompatibility2;
2945
- })(VersionCompatibility || {});
2946
-
2947
- // src/utils/api-version.utils.ts
2948
- var legacyCutoffYear = 25;
2949
- function parseApiVersion(versionString) {
2950
- const regex = /^v(\d{2})\.(\d+)\.(\d+)$/;
2951
- const match = versionString.match(regex);
2952
- if (!match) {
2953
- return null;
2954
- }
2955
- const [, yearStr, minorStr, patchStr] = match;
2956
- const year = parseInt(yearStr, 10);
2957
- const minor = parseInt(minorStr, 10);
2958
- const patch = parseInt(patchStr, 10);
2959
- if (year <= legacyCutoffYear) {
2960
- if (minor < 1 || minor > 12) {
2961
- return null;
2962
- }
2963
- } else if (year >= 26) {
2964
- if (minor < 0 || minor > 99) {
2965
- return null;
2966
- }
2967
- }
2968
- return {
2969
- version: versionString,
2970
- year,
2971
- minor,
2972
- patch,
2973
- websocketPath: `/api/${versionString}`
2974
- };
2975
- }
2976
- function compareVersions(a, b) {
2977
- if (a.year !== b.year) {
2978
- return a.year - b.year;
3010
+ messages() {
3011
+ return this.messages$;
2979
3012
  }
2980
- if (a.minor !== b.minor) {
2981
- return a.minor - b.minor;
3013
+ /**
3014
+ * sends a message over the current websocket OR queues it to send once
3015
+ * the next websocket is opened. messages sent via `send` will not be lost until after
3016
+ * the next `closed$` emission.
3017
+ */
3018
+ send(message) {
3019
+ return this.ws$.pipe(
3020
+ filter((ws) => ws !== null),
3021
+ take(1)
3022
+ ).subscribe((ws) => ws.next(message));
2982
3023
  }
2983
- return a.patch - b.patch;
2984
- }
2985
- function checkVersionCompatibility(version) {
2986
- const minVersion = parseApiVersion(apiVersionConfig.MIN_SUPPORTED_VERSION);
2987
- const maxVersion = parseApiVersion(apiVersionConfig.MAX_SUPPORTED_VERSION);
2988
- if (!minVersion || !maxVersion) {
2989
- return "invalid" /* Invalid */;
3024
+ /**
3025
+ * manually closes this connection and prevents it from retrying/opening any more.
3026
+ */
3027
+ close() {
3028
+ this.closeConnection.next();
3029
+ this.closeConnection.complete();
2990
3030
  }
2991
- if (compareVersions(version, minVersion) < 0) {
2992
- return "too-old" /* TooOld */;
3031
+ /**
3032
+ * helper method which creates an `Observable` which emits an `ActiveConnection`
3033
+ * after it establishes a connection to the given hostname. the observable will emit an
3034
+ * error if the connection is never established and will not complete until unsubscribed from or closed.
3035
+ */
3036
+ createSocket(hostname) {
3037
+ const url = `${socketScheme(this.protocol)}//${hostname}${this.websocketPath}`;
3038
+ let hasOpened = false;
3039
+ return new Observable((subscriber) => {
3040
+ const ws = new TrueNasSocket({
3041
+ url,
3042
+ openObserver: {
3043
+ next: () => {
3044
+ hasOpened = true;
3045
+ this.connectionAttempts.next(0);
3046
+ subscriber.next({ ws, hostname });
3047
+ }
3048
+ },
3049
+ closeObserver: {
3050
+ next: (event) => {
3051
+ const reason = event.reason || "";
3052
+ let errorMessage;
3053
+ if (isHttpStatusError(reason)) {
3054
+ errorMessage = getHttpError(reason);
3055
+ } else {
3056
+ errorMessage = getWebSocketError(event.code);
3057
+ }
3058
+ this.connectionAttempts.next(this.connectionAttempts.value + 1);
3059
+ subscriber.error(makeConnectionError(errorMessage, hostname));
3060
+ }
3061
+ }
3062
+ });
3063
+ const startupSub = ws.socket.subscribe({
3064
+ error: () => {
3065
+ }
3066
+ });
3067
+ return () => {
3068
+ startupSub.unsubscribe();
3069
+ ws.complete();
3070
+ };
3071
+ }).pipe(
3072
+ // retry logic:
3073
+ // * if a connection is not established in 10 seconds, consider that an error
3074
+ timeout({ first: tenSeconds }),
3075
+ retry({
3076
+ // * while still *establishing*: wait `retryDelay` before trying again, giving up
3077
+ // after `maxRetry` retries.
3078
+ count: this.maxRetry,
3079
+ // * we use a custom `delay` function here to ensure no retries are performed
3080
+ // once a socket is *opened*.
3081
+ // basically: a later death must propagate out rather than being retried
3082
+ // so it can be handled by the `connection$` observable.
3083
+ delay: (error) => {
3084
+ if (hasOpened) {
3085
+ return throwError(() => error);
3086
+ }
3087
+ return timer(this.retryDelay);
3088
+ }
3089
+ })
3090
+ );
2993
3091
  }
2994
- if (compareVersions(version, maxVersion) > 0) {
2995
- return "too-new" /* TooNew */;
3092
+ /**
3093
+ * helper function which actually performs the parallel connection `race`.
3094
+ */
3095
+ connect() {
3096
+ return race(
3097
+ this.hostnames.map(this.createSocket.bind(this))
3098
+ ).pipe(
3099
+ tap((conn) => this.logger.debug(`TrueNas socket opened to ${conn.hostname}.`)),
3100
+ takeUntil(this.closeConnection)
3101
+ );
2996
3102
  }
2997
- return "compatible" /* Compatible */;
2998
- }
2999
- function isVersionSupported(version) {
3000
- return checkVersionCompatibility(version) === "compatible" /* Compatible */;
3001
- }
3002
- function filterCompatibleVersions(versions) {
3003
- return versions.filter(isVersionSupported);
3004
- }
3005
- function getWebSocketPath(version) {
3006
- return version.websocketPath;
3007
- }
3103
+ };
3104
+ var makeActiveConnection = (ws, hostname) => ({
3105
+ ws,
3106
+ hostname,
3107
+ state: "active"
3108
+ });
3109
+ var makeConnectionError = (message, hostname) => ({
3110
+ name: "ConnectionError",
3111
+ message,
3112
+ hostname,
3113
+ state: "error"
3114
+ });
3115
+ var closedConnection = { state: "closed" };
3008
3116
 
3009
3117
  // src/client/truenas-api-client.ts
3010
3118
  var TrueNasApiClient = class {
@@ -3074,7 +3182,7 @@ var TrueNasApiClient = class {
3074
3182
  * Override in subclasses to provide version-specific authentication.
3075
3183
  */
3076
3184
  createAuthenticator() {
3077
- return new TrueNasAuthenticator(this.connection);
3185
+ return new TrueNasAuthenticator(this.connection, this.version);
3078
3186
  }
3079
3187
  };
3080
3188