@mcp-abap-adt/connection 1.10.1 → 2.0.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 (44) hide show
  1. package/CHANGELOG.md +758 -0
  2. package/README.md +42 -11
  3. package/dist/__tests__/helpers/session.d.ts +15 -0
  4. package/dist/__tests__/helpers/session.d.ts.map +1 -0
  5. package/dist/__tests__/helpers/session.js +19 -0
  6. package/dist/auth/ntlm.d.ts +15 -0
  7. package/dist/auth/ntlm.d.ts.map +1 -1
  8. package/dist/auth/ntlm.js +38 -0
  9. package/dist/connection/AbstractAbapConnection.d.ts +163 -11
  10. package/dist/connection/AbstractAbapConnection.d.ts.map +1 -1
  11. package/dist/connection/AbstractAbapConnection.js +351 -14
  12. package/dist/connection/BaseAbapConnection.d.ts +5 -1
  13. package/dist/connection/BaseAbapConnection.d.ts.map +1 -1
  14. package/dist/connection/BaseAbapConnection.js +11 -1
  15. package/dist/connection/CertificateAbapConnection.d.ts +5 -1
  16. package/dist/connection/CertificateAbapConnection.d.ts.map +1 -1
  17. package/dist/connection/CertificateAbapConnection.js +11 -1
  18. package/dist/connection/JwtAbapConnection.d.ts +3 -2
  19. package/dist/connection/JwtAbapConnection.d.ts.map +1 -1
  20. package/dist/connection/JwtAbapConnection.js +19 -8
  21. package/dist/connection/KerberosAbapConnection.d.ts +5 -1
  22. package/dist/connection/KerberosAbapConnection.d.ts.map +1 -1
  23. package/dist/connection/KerberosAbapConnection.js +54 -3
  24. package/dist/connection/SamlAbapConnection.d.ts +5 -1
  25. package/dist/connection/SamlAbapConnection.d.ts.map +1 -1
  26. package/dist/connection/SamlAbapConnection.js +11 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +4 -0
  29. package/dist/session/SessionLifecycle.d.ts +131 -0
  30. package/dist/session/SessionLifecycle.d.ts.map +1 -0
  31. package/dist/session/SessionLifecycle.js +301 -0
  32. package/docs/INDEX.md +106 -0
  33. package/docs/INSTALLATION.md +304 -0
  34. package/docs/JWT_AUTH_TOOLS.md +142 -0
  35. package/docs/MIGRATION-2.0.md +125 -0
  36. package/docs/SCOPE.md +44 -0
  37. package/docs/STATEFUL_SESSION_GUIDE.md +121 -0
  38. package/docs/USAGE.md +749 -0
  39. package/examples/README.md +112 -0
  40. package/examples/basic-connection.js +55 -0
  41. package/examples/jwt-with-token-refresh.js +87 -0
  42. package/examples/saml-connection.js +52 -0
  43. package/examples/websocket-transport.js +87 -0
  44. package/package.json +11 -4
@@ -52,9 +52,10 @@ class JwtAbapConnection extends AbstractAbapConnection_js_1.AbstractAbapConnecti
52
52
  }
53
53
  }
54
54
  /**
55
- * Override connect to handle JWT token refresh on errors
55
+ * Establishes the session for this auth type. Called by
56
+ * AbstractAbapConnection.connect(), which owns the lifecycle around it.
56
57
  */
57
- async connect() {
58
+ async establishSession() {
58
59
  const baseUrl = await this.getBaseUrl();
59
60
  const discoveryUrl = `${baseUrl}/sap/bc/adt/discovery`;
60
61
  this.logger?.debug(`[DEBUG] JwtAbapConnection - Connecting to SAP system: ${discoveryUrl}`);
@@ -85,9 +86,11 @@ class JwtAbapConnection extends AbstractAbapConnection_js_1.AbstractAbapConnecti
85
86
  }
86
87
  // Try to refresh token if tokenRefresher is available
87
88
  if (await this.tryRefreshToken()) {
88
- // Retry connect with new token
89
- this.logger?.debug(`[DEBUG] JwtAbapConnection - Retrying connect after token refresh...`);
90
- return this.connect();
89
+ // Retry the ESTABLISHMENT, not connect(): connect() runs this as a
90
+ // joinable transition, so a nested call joins the transition already
91
+ // in flight — this one — and waits for itself forever.
92
+ this.logger?.debug(`[DEBUG] JwtAbapConnection - Retrying establishment after token refresh...`);
93
+ return this.establishSession();
91
94
  }
92
95
  throw new Error('JWT token has expired. Please re-authenticate.');
93
96
  }
@@ -99,6 +102,9 @@ class JwtAbapConnection extends AbstractAbapConnection_js_1.AbstractAbapConnecti
99
102
  * Override makeAdtRequest to handle JWT auth errors with automatic token refresh
100
103
  */
101
104
  async makeAdtRequest(options) {
105
+ // Captured before the attempt: a recovery asks "has the caller asked to
106
+ // stop since this request began", not since some later bookkeeping step.
107
+ const baselineEpoch = this.teardownEpoch;
102
108
  this.logger?.debug(`[DEBUG] JwtAbapConnection.makeAdtRequest - Starting request: ${options.method} ${options.url}`);
103
109
  try {
104
110
  const response = await super.makeAdtRequest(options);
@@ -124,9 +130,14 @@ class JwtAbapConnection extends AbstractAbapConnection_js_1.AbstractAbapConnecti
124
130
  }
125
131
  // Try to refresh token if tokenRefresher is available
126
132
  if (await this.tryRefreshToken()) {
127
- // Reset connection state and retry request with new token
128
- this.logger?.debug(`[DEBUG] JwtAbapConnection.makeAdtRequest - Retrying request after token refresh...`);
129
- this.reset();
133
+ this.logger?.debug(`[DEBUG] JwtAbapConnection.makeAdtRequest - Recovering session after token refresh...`);
134
+ // The renewed credential cannot keep the old ABAP session, so this is
135
+ // a session-lost teardown — internal, or it would cancel the very
136
+ // recovery it is setting up. reset() would be the caller-origin one.
137
+ this.discardSession();
138
+ // Re-establish before retrying: the retry goes through admission, and
139
+ // a discarded session admits nothing.
140
+ await this.recoverSession(baselineEpoch);
130
141
  return super.makeAdtRequest(options);
131
142
  }
132
143
  throw new Error('JWT token has expired. Please re-authenticate.');
@@ -14,7 +14,11 @@ export declare class KerberosAbapConnection extends AbstractAbapConnection {
14
14
  * request — the first request carries the Negotiate header; SAP then issues a session
15
15
  * cookie which is reused for subsequent requests.
16
16
  */
17
- connect(): Promise<void>;
17
+ /**
18
+ * Establishes the session for this auth type. Called by
19
+ * AbstractAbapConnection.connect(), which owns the lifecycle around it.
20
+ */
21
+ protected establishSession(): Promise<void>;
18
22
  protected buildAuthorizationHeader(): string;
19
23
  }
20
24
  //# sourceMappingURL=KerberosAbapConnection.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"KerberosAbapConnection.d.ts","sourceRoot":"","sources":["../../src/connection/KerberosAbapConnection.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,SAAS,EAAE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 -34,16 +34,38 @@ class KerberosAbapConnection extends AbstractAbapConnection_js_1.AbstractAbapCon
34
34
  * request — the first request carries the Negotiate header; SAP then issues a session
35
35
  * cookie which is reused for subsequent requests.
36
36
  */
37
- async connect() {
37
+ /**
38
+ * Establishes the session for this auth type. Called by
39
+ * AbstractAbapConnection.connect(), which owns the lifecycle around it.
40
+ */
41
+ async establishSession() {
38
42
  await this.ensureToken();
39
43
  const baseUrl = await this.getBaseUrl();
40
44
  const discoveryUrl = `${baseUrl}/sap/bc/adt/discovery`;
41
45
  this.logger?.debug(`[DEBUG] KerberosAbapConnection - Connecting to SAP system: ${discoveryUrl}`);
42
46
  try {
43
- const token = await this.fetchCsrfToken(discoveryUrl, 3, 1000);
47
+ // ONE attempt, deliberately — the shared default is 3 retries a second
48
+ // apart, and every one of them corrupts this exchange:
49
+ //
50
+ // - A GSS token is one-shot. Replaying it is meaningless at best, and
51
+ // replay protection may answer it differently than the original.
52
+ // - Worse, a 401 that sets a cookie silences buildAuthorizationHeader()
53
+ // (a cookie carries auth after the first round trip), so the retry
54
+ // goes out with NO Authorization at all and draws the server's plain
55
+ // opening challenge.
56
+ //
57
+ // Either way the classifier below would read the LAST response and name
58
+ // the wrong cause. The retry cannot help here anyway: nothing about a
59
+ // rejected token changes by waiting a second. Retrying a transient
60
+ // network failure is the caller's business now that connect() is
61
+ // explicit, and a fresh connect() mints a fresh token.
62
+ const token = await this.fetchCsrfToken(discoveryUrl, 0, 0);
44
63
  this.setCsrfToken(token);
45
64
  }
46
65
  catch (error) {
66
+ // The token went out and was not accepted, so it is spent. Keeping it
67
+ // would make every later connect() replay a token already known to fail.
68
+ this.currentToken = '';
47
69
  if (error instanceof axios_1.AxiosError && error.response?.headers) {
48
70
  const wwwAuth = error.response.headers['www-authenticate'];
49
71
  if ((0, ntlm_js_1.isNtlmChallenge)(wwwAuth)) {
@@ -53,8 +75,37 @@ class KerberosAbapConnection extends AbstractAbapConnection_js_1.AbstractAbapCon
53
75
  if (this.getCookies()) {
54
76
  this.logger?.debug('[DEBUG] KerberosAbapConnection - cookies captured from error response during connect');
55
77
  }
78
+ // A 401 carrying a Negotiate token is a CONTINUATION, not a success.
79
+ //
80
+ // Per RFC 4559 the server is handing back gssapi-data for the client to
81
+ // feed into its GSS context and retry. This client cannot do that:
82
+ // generateSpnegoToken() calls step('') once and discards the context,
83
+ // so there is nothing to continue with. The token it holds is the
84
+ // initial one, and sending it again produces the same 401.
85
+ //
86
+ // So this fails, and says why — resolving here would claim a readiness
87
+ // that does not exist and move the failure to the first real request,
88
+ // where it reads as an unrelated auth error.
89
+ if ((0, ntlm_js_1.isNegotiateContinuation)(wwwAuth)) {
90
+ throw new Error('KerberosAbapConnection: the server continued the SPNEGO exchange ' +
91
+ '(401 with a Negotiate token), which requires feeding that token ' +
92
+ 'back into the GSS context and retrying. This client performs a ' +
93
+ 'single-leg exchange only — the context is discarded after the ' +
94
+ 'first step — so multi-leg SPNEGO is not supported. See ' +
95
+ 'https://www.rfc-editor.org/rfc/rfc4559');
96
+ }
97
+ // A BARE Negotiate is a different problem with a different fix: the
98
+ // initial Authorization has already gone out, so an empty challenge is
99
+ // the server declining it. No token came back, so there is nothing to
100
+ // step even for a client that supports multi-leg.
101
+ if ((0, ntlm_js_1.isBareNegotiateChallenge)(wwwAuth)) {
102
+ throw new Error('KerberosAbapConnection: the server rejected the SPNEGO token ' +
103
+ '(401 with a bare Negotiate challenge, no token returned). The ' +
104
+ 'credentials were not accepted — check the SPN, the ticket ' +
105
+ '(klist / kinit), and that the user is permitted Kerberos logon.');
106
+ }
56
107
  }
57
- this.logger?.warn(`[WARN] KerberosAbapConnection - connect deferred: ${error instanceof Error ? error.message : String(error)}`);
108
+ throw error;
58
109
  }
59
110
  }
60
111
  buildAuthorizationHeader() {
@@ -13,7 +13,11 @@ export declare class SamlAbapConnection extends AbstractAbapConnection {
13
13
  * Connect to SAP system using existing session cookies
14
14
  * Fetches CSRF token to establish session context
15
15
  */
16
- connect(): Promise<void>;
16
+ /**
17
+ * Establishes the session for this auth type. Called by
18
+ * AbstractAbapConnection.connect(), which owns the lifecycle around it.
19
+ */
20
+ protected establishSession(): Promise<void>;
17
21
  protected buildAuthorizationHeader(): string;
18
22
  getAuthHeaders(): Promise<Record<string, string>>;
19
23
  private static validateConfig;
@@ -1 +1 @@
1
- {"version":3,"file":"SamlAbapConnection.d.ts","sourceRoot":"","sources":["../../src/connection/SamlAbapConnection.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAErE;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,sBAAsB;IAC5D,OAAO,CAAC,cAAc,CAAS;gBAG7B,MAAM,EAAE,SAAS,EACjB,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,EACvB,SAAS,CAAC,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;KAAE;IAUzC;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAiC9B,SAAS,CAAC,wBAAwB,IAAI,MAAM;IAItC,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAQvD,OAAO,CAAC,MAAM,CAAC,cAAc;CAW9B"}
1
+ {"version":3,"file":"SamlAbapConnection.d.ts","sourceRoot":"","sources":["../../src/connection/SamlAbapConnection.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAC5C,OAAO,EAAE,sBAAsB,EAAE,MAAM,6BAA6B,CAAC;AAErE;;GAEG;AACH,qBAAa,kBAAmB,SAAQ,sBAAsB;IAC5D,OAAO,CAAC,cAAc,CAAS;gBAG7B,MAAM,EAAE,SAAS,EACjB,MAAM,CAAC,EAAE,OAAO,GAAG,IAAI,EACvB,SAAS,CAAC,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE;QAAE,eAAe,CAAC,EAAE,OAAO,CAAA;KAAE;IAUzC;;;OAGG;IACH;;;OAGG;cACa,gBAAgB,IAAI,OAAO,CAAC,IAAI,CAAC;IAwCjD,SAAS,CAAC,wBAAwB,IAAI,MAAM;IAItC,cAAc,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IAQvD,OAAO,CAAC,MAAM,CAAC,cAAc;CAW9B"}
@@ -20,7 +20,11 @@ class SamlAbapConnection extends AbstractAbapConnection_js_1.AbstractAbapConnect
20
20
  * Connect to SAP system using existing session cookies
21
21
  * Fetches CSRF token to establish session context
22
22
  */
23
- async connect() {
23
+ /**
24
+ * Establishes the session for this auth type. Called by
25
+ * AbstractAbapConnection.connect(), which owns the lifecycle around it.
26
+ */
27
+ async establishSession() {
24
28
  const baseUrl = await this.getBaseUrl();
25
29
  const discoveryUrl = `${baseUrl}/sap/bc/adt/discovery`;
26
30
  this.logger?.debug(`[DEBUG] SamlAbapConnection - Connecting to SAP system: ${discoveryUrl}`);
@@ -41,6 +45,12 @@ class SamlAbapConnection extends AbstractAbapConnection_js_1.AbstractAbapConnect
41
45
  this.logger?.debug(`[DEBUG] SamlAbapConnection - Cookies extracted from error response during connect (first 100 chars): ${this.getCookies()?.substring(0, 100)}...`);
42
46
  }
43
47
  }
48
+ // Rethrow: a resolved connect() must mean a usable session exists. This
49
+ // used to swallow and resolve anyway, deferring establishment to the
50
+ // first request — coherent only while that lazy path existed. Without it,
51
+ // swallowing would leave a connection that reports success, holds
52
+ // nothing, and refuses every request.
53
+ throw error;
44
54
  }
45
55
  }
46
56
  buildAuthorizationHeader() {
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA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BAA0B,CAAC;AAClC,OAAO,EAAE,6BAA6B,EAAE,MAAM,yCAAyC,CAAC;AACxF,YAAY,EACV,WAAW,EACX,SAAS,EACT,iBAAiB,GAClB,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,YAAY,EACV,cAAc,EACd,kBAAkB,GACnB,MAAM,gCAAgC,CAAC;AAOxC,OAAO,EACL,kBAAkB,EAClB,kBAAkB,IAAI,oBAAoB,GAC3C,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAE,yBAAyB,EAAE,MAAM,2CAA2C,CAAC;AAEtF,OAAO,EAAE,oBAAoB,EAAE,MAAM,mCAAmC,CAAC;AAEzE,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,MAAM,4BAA4B,CAAC;AAC9E,OAAO,EACL,yBAAyB,EACzB,KAAK,iBAAiB,EACtB,KAAK,cAAc,GACpB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EACL,iBAAiB,EACjB,iBAAiB,IAAI,mBAAmB,GACzC,MAAM,mCAAmC,CAAC;AAC3C,OAAO,EAAE,sBAAsB,EAAE,MAAM,wCAAwC,CAAC;AAChF,OAAO,EAAE,iBAAiB,EAAE,MAAM,mCAAmC,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AACxE,YAAY,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AAE3C,OAAO,EACL,UAAU,EACV,gBAAgB,EAChB,KAAK,aAAa,GACnB,MAAM,qBAAqB,CAAC"}
package/dist/index.js CHANGED
@@ -7,6 +7,10 @@ Object.defineProperty(exports, "FileCertificateMaterialLoader", { enumerable: tr
7
7
  // Config utilities
8
8
  var sapConfig_js_1 = require("./config/sapConfig.js");
9
9
  Object.defineProperty(exports, "sapConfigSignature", { enumerable: true, get: function () { return sapConfig_js_1.sapConfigSignature; } });
10
+ // The session lifecycle vocabulary — ISessionLifecycleAware, ILockWindowAware,
11
+ // ITeardownReport, WindowToken, ADT_SESSION_ERROR — is deliberately NOT exported
12
+ // here. It lives in @mcp-abap-adt/interfaces, and a consumer imports it from
13
+ // there: re-exporting a contract type gives it two names and lets the two drift.
10
14
  // Connection classes - only final implementations
11
15
  // Deprecated aliases for backward compatibility
12
16
  var BaseAbapConnection_js_1 = require("./connection/BaseAbapConnection.js");
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Owns the session lifecycle: what state the session is in, who may use it, and
3
+ * when it is safe to tear it down.
4
+ *
5
+ * Deliberately knows nothing about SAP, HTTP, RFC, cookies or ADT. Identities
6
+ * are opaque maps of name → value that someone else computed; windows are
7
+ * opaque labels. That is what makes this unit testable without a server, and it
8
+ * is where the hard part of the design lives: ordering, admission, deadlines.
9
+ *
10
+ * Design: docs/superpowers/specs/2026-07-27-session-lifecycle-design.md in
11
+ * @mcp-abap-adt/adt-clients.
12
+ */
13
+ import { type AdtSessionErrorCode, type WindowToken } from '@mcp-abap-adt/interfaces';
14
+ export type TransitionKind = 'connect' | 'disconnect' | 'recover' | 'cleanup';
15
+ export interface RequestLease {
16
+ /** Teardown epoch at admission — the baseline a recovery compares against. */
17
+ readonly epoch: number;
18
+ /** Call once the request settles. Safe to call twice. */
19
+ release(): void;
20
+ }
21
+ export interface DrainResult {
22
+ /** Labels of windows still open when the wait gave up, deduplicated. */
23
+ abandonedWindows: string[];
24
+ }
25
+ export interface BeginTeardownOptions {
26
+ /** Decides the epoch: a caller's request cancels recoveries, an internal one must not. */
27
+ origin: 'caller' | 'internal';
28
+ /** Decides admission: a lost session cannot let an open window finish. */
29
+ sessionLost: boolean;
30
+ }
31
+ export declare function sessionError(code: AdtSessionErrorCode, message?: string): Error & {
32
+ code: AdtSessionErrorCode;
33
+ };
34
+ export interface SessionLifecycleOptions {
35
+ /** Ceiling for the window wait, from the moment a teardown is requested. */
36
+ ceilingMs?: number;
37
+ /** Injected clock, so tests need no real time. */
38
+ now?: () => number;
39
+ }
40
+ export declare class SessionLifecycle {
41
+ private state;
42
+ private fingerprint;
43
+ private epoch;
44
+ private teardownPending;
45
+ private teardownLostSession;
46
+ private teardownAt;
47
+ /** Set at expiry: admission is shut regardless of open windows. */
48
+ private admissionForcedShut;
49
+ private readonly windows;
50
+ private inFlight;
51
+ private tail;
52
+ private tailKind;
53
+ private tailPromise;
54
+ private waiters;
55
+ private readonly ceilingMs;
56
+ private readonly now;
57
+ constructor(options?: SessionLifecycleOptions);
58
+ /**
59
+ * Whether a caller may start work. False throughout a teardown, including
60
+ * while a grandfathered window is still finishing: finishing is not starting.
61
+ */
62
+ get connected(): boolean;
63
+ /** Derived from the tracked fingerprint; null when nothing is tracked. */
64
+ get identity(): string | null;
65
+ get teardownEpoch(): number;
66
+ /** One entry per open window, abandoned ones included. */
67
+ get openWindows(): readonly string[];
68
+ /**
69
+ * Publishes a freshly established session, which also ENDS any teardown that
70
+ * was pending: the flags describe the session being torn down, and this is a
71
+ * different one. Without this, `connect()` after `disconnect()` — which the
72
+ * design allows explicitly — leaves the lifecycle permanently unusable.
73
+ *
74
+ * Windows are dropped for the same reason: they belonged to the old session,
75
+ * nothing here can close them, and a teardown that gave up on them has
76
+ * already carried their labels out in its report. Keeping them would make
77
+ * every future drain re-report locks from a session that no longer exists.
78
+ */
79
+ markConnected(fingerprint?: ReadonlyMap<string, string>): void;
80
+ markDisconnected(): void;
81
+ /**
82
+ * Classifies a freshly observed fingerprint.
83
+ *
84
+ * Additive: a name appearing where none was tracked is `established`, never
85
+ * `replaced` — otherwise the identifier a LOCK response adds would read as a
86
+ * new session and blow up the window it just opened.
87
+ */
88
+ observe(fingerprint: ReadonlyMap<string, string>): 'unchanged' | 'established' | 'replaced';
89
+ /** True while an already-open window is allowed to finish its work. */
90
+ private get finishingWindowOpen();
91
+ private get admits();
92
+ assertUsable(): void;
93
+ /** Asserts usability and counts the request in, in one synchronous step. */
94
+ admitRequest(): RequestLease;
95
+ /**
96
+ * A lock outlives the request that takes it, so it is the one thing a pending
97
+ * teardown refuses outright.
98
+ */
99
+ beginWindow(label: string): WindowToken;
100
+ /** A token matching no open window is ignored: double close, foreign token. */
101
+ endWindow(token: WindowToken): void;
102
+ beginTeardown({ origin, sessionLost }: BeginTeardownOptions): void;
103
+ get teardownRequested(): boolean;
104
+ /**
105
+ * Resolves when nothing is in flight and no window is still worth waiting
106
+ * for. Bounded by the ceiling measured from the teardown request — absolute,
107
+ * never extended by request activity.
108
+ *
109
+ * On expiry, before resolving and without yielding in between: shuts
110
+ * admission, gives up on the remaining windows, then waits once more for the
111
+ * already-admitted requests to settle.
112
+ */
113
+ drain(): Promise<DrainResult>;
114
+ private get liveWindows();
115
+ private abandonedLabels;
116
+ /**
117
+ * Runs a transition on the serializing tail.
118
+ *
119
+ * `connect` and `disconnect` join the tail of their own kind — two callers
120
+ * wanting the same thing get one execution and the same answer — but only
121
+ * when nothing is queued behind it, so a join can never overtake a queued
122
+ * transition of another kind. `recover` and `cleanup` never join and are
123
+ * never joined: a recovery carries its own request's baseline, and an
124
+ * internal cleanup owes its result to nobody while a caller's teardown owes a
125
+ * report.
126
+ */
127
+ transition<T>(kind: TransitionKind, run: () => Promise<T>): Promise<T>;
128
+ private wake;
129
+ private changed;
130
+ }
131
+ //# sourceMappingURL=SessionLifecycle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SessionLifecycle.d.ts","sourceRoot":"","sources":["../../src/session/SessionLifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,OAAO,EAEL,KAAK,mBAAmB,EACxB,KAAK,WAAW,EACjB,MAAM,0BAA0B,CAAC;AAElC,MAAM,MAAM,cAAc,GAAG,SAAS,GAAG,YAAY,GAAG,SAAS,GAAG,SAAS,CAAC;AAE9E,MAAM,WAAW,YAAY;IAC3B,8EAA8E;IAC9E,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,yDAAyD;IACzD,OAAO,IAAI,IAAI,CAAC;CACjB;AAED,MAAM,WAAW,WAAW;IAC1B,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AW,IAAI,SAAS,MAAM,EAAE,CAEnC;IAED;;;;;;;;;;OAUG;IACH,aAAa,CAAC,WAAW,GAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAa,GAAG,IAAI;IAWzE,gBAAgB,IAAI,IAAI;IAMxB;;;;;;OAMG;IACH,OAAO,CACL,WAAW,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,GACvC,WAAW,GAAG,aAAa,GAAG,UAAU;IAiB3C,uEAAuE;IACvE,OAAO,KAAK,mBAAmB,GAO9B;IAED,OAAO,KAAK,MAAM,GAIjB;IAED,YAAY,IAAI,IAAI;IAMpB,4EAA4E;IAC5E,YAAY,IAAI,YAAY;IAkB5B;;;OAGG;IACH,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,WAAW;IASvC,+EAA+E;IAC/E,SAAS,CAAC,KAAK,EAAE,WAAW,GAAG,IAAI;IAOnC,aAAa,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,oBAAoB,GAAG,IAAI;IAkBlE,IAAI,iBAAiB,IAAI,OAAO,CAE/B;IAED;;;;;;;;OAQG;IACG,KAAK,IAAI,OAAO,CAAC,WAAW,CAAC;IA2BnC,OAAO,KAAK,WAAW,GAItB;IAED,OAAO,CAAC,eAAe;IAUvB;;;;;;;;;;OAUG;IACH,UAAU,CAAC,CAAC,EAAE,IAAI,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IA8BtE,OAAO,CAAC,IAAI;IAMZ,OAAO,CAAC,OAAO;CAehB"}
@@ -0,0 +1,301 @@
1
+ "use strict";
2
+ /**
3
+ * Owns the session lifecycle: what state the session is in, who may use it, and
4
+ * when it is safe to tear it down.
5
+ *
6
+ * Deliberately knows nothing about SAP, HTTP, RFC, cookies or ADT. Identities
7
+ * are opaque maps of name → value that someone else computed; windows are
8
+ * opaque labels. That is what makes this unit testable without a server, and it
9
+ * is where the hard part of the design lives: ordering, admission, deadlines.
10
+ *
11
+ * Design: docs/superpowers/specs/2026-07-27-session-lifecycle-design.md in
12
+ * @mcp-abap-adt/adt-clients.
13
+ */
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.SessionLifecycle = void 0;
16
+ exports.sessionError = sessionError;
17
+ const interfaces_1 = require("@mcp-abap-adt/interfaces");
18
+ function sessionError(code, message) {
19
+ const error = new Error(message ?? code);
20
+ error.code = code;
21
+ return error;
22
+ }
23
+ class SessionLifecycle {
24
+ state = 'disconnected';
25
+ fingerprint = new Map();
26
+ epoch = 0;
27
+ teardownPending = false;
28
+ teardownLostSession = false;
29
+ teardownAt = null;
30
+ /** Set at expiry: admission is shut regardless of open windows. */
31
+ admissionForcedShut = false;
32
+ windows = new Map();
33
+ inFlight = 0;
34
+ tail = Promise.resolve();
35
+ tailKind = null;
36
+ tailPromise = null;
37
+ waiters = [];
38
+ ceilingMs;
39
+ now;
40
+ constructor(options = {}) {
41
+ this.ceilingMs = options.ceilingMs ?? 600_000;
42
+ this.now = options.now ?? (() => Date.now());
43
+ }
44
+ // ---------------------------------------------------------------- state ---
45
+ /**
46
+ * Whether a caller may start work. False throughout a teardown, including
47
+ * while a grandfathered window is still finishing: finishing is not starting.
48
+ */
49
+ get connected() {
50
+ return this.state === 'connected' && !this.teardownPending;
51
+ }
52
+ /** Derived from the tracked fingerprint; null when nothing is tracked. */
53
+ get identity() {
54
+ if (this.fingerprint.size === 0)
55
+ return null;
56
+ return [...this.fingerprint.entries()]
57
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
58
+ .map(([name, value]) => `${name}=${value}`)
59
+ .join('; ');
60
+ }
61
+ get teardownEpoch() {
62
+ return this.epoch;
63
+ }
64
+ /** One entry per open window, abandoned ones included. */
65
+ get openWindows() {
66
+ return [...this.windows.values()].map((w) => w.label);
67
+ }
68
+ /**
69
+ * Publishes a freshly established session, which also ENDS any teardown that
70
+ * was pending: the flags describe the session being torn down, and this is a
71
+ * different one. Without this, `connect()` after `disconnect()` — which the
72
+ * design allows explicitly — leaves the lifecycle permanently unusable.
73
+ *
74
+ * Windows are dropped for the same reason: they belonged to the old session,
75
+ * nothing here can close them, and a teardown that gave up on them has
76
+ * already carried their labels out in its report. Keeping them would make
77
+ * every future drain re-report locks from a session that no longer exists.
78
+ */
79
+ markConnected(fingerprint = new Map()) {
80
+ this.state = 'connected';
81
+ this.fingerprint = new Map(fingerprint);
82
+ this.teardownPending = false;
83
+ this.teardownLostSession = false;
84
+ this.admissionForcedShut = false;
85
+ this.teardownAt = null;
86
+ this.windows.clear();
87
+ this.wake();
88
+ }
89
+ markDisconnected() {
90
+ this.state = 'disconnected';
91
+ this.fingerprint.clear();
92
+ this.wake();
93
+ }
94
+ /**
95
+ * Classifies a freshly observed fingerprint.
96
+ *
97
+ * Additive: a name appearing where none was tracked is `established`, never
98
+ * `replaced` — otherwise the identifier a LOCK response adds would read as a
99
+ * new session and blow up the window it just opened.
100
+ */
101
+ observe(fingerprint) {
102
+ let established = false;
103
+ for (const [name, value] of fingerprint) {
104
+ const known = this.fingerprint.get(name);
105
+ if (known === undefined) {
106
+ established = true;
107
+ this.fingerprint.set(name, value);
108
+ }
109
+ else if (known !== value) {
110
+ this.fingerprint.set(name, value);
111
+ return 'replaced';
112
+ }
113
+ }
114
+ return established ? 'established' : 'unchanged';
115
+ }
116
+ // ------------------------------------------------------------ admission ---
117
+ /** True while an already-open window is allowed to finish its work. */
118
+ get finishingWindowOpen() {
119
+ return (this.teardownPending &&
120
+ !this.teardownLostSession &&
121
+ !this.admissionForcedShut &&
122
+ this.windows.size > 0);
123
+ }
124
+ get admits() {
125
+ if (this.state !== 'connected')
126
+ return false;
127
+ if (!this.teardownPending)
128
+ return true;
129
+ return this.finishingWindowOpen;
130
+ }
131
+ assertUsable() {
132
+ if (!this.admits) {
133
+ throw sessionError(interfaces_1.ADT_SESSION_ERROR.NOT_CONNECTED);
134
+ }
135
+ }
136
+ /** Asserts usability and counts the request in, in one synchronous step. */
137
+ admitRequest() {
138
+ this.assertUsable();
139
+ this.inFlight += 1;
140
+ const epoch = this.epoch;
141
+ let released = false;
142
+ return {
143
+ epoch,
144
+ release: () => {
145
+ if (released)
146
+ return;
147
+ released = true;
148
+ this.inFlight -= 1;
149
+ this.wake();
150
+ },
151
+ };
152
+ }
153
+ // -------------------------------------------------------------- windows ---
154
+ /**
155
+ * A lock outlives the request that takes it, so it is the one thing a pending
156
+ * teardown refuses outright.
157
+ */
158
+ beginWindow(label) {
159
+ if (this.state !== 'connected' || this.teardownPending) {
160
+ throw sessionError(interfaces_1.ADT_SESSION_ERROR.NOT_CONNECTED);
161
+ }
162
+ const token = Symbol(label);
163
+ this.windows.set(token, { label, abandoned: false });
164
+ return token;
165
+ }
166
+ /** A token matching no open window is ignored: double close, foreign token. */
167
+ endWindow(token) {
168
+ if (!this.windows.delete(token))
169
+ return;
170
+ this.wake();
171
+ }
172
+ // ------------------------------------------------------------- teardown ---
173
+ beginTeardown({ origin, sessionLost }) {
174
+ if (!this.teardownPending) {
175
+ this.teardownAt = this.now();
176
+ }
177
+ this.teardownPending = true;
178
+ if (origin === 'caller') {
179
+ this.epoch += 1;
180
+ }
181
+ if (sessionLost) {
182
+ this.teardownLostSession = true;
183
+ // Nothing can finish over a session that is gone: give up on every window
184
+ // now, and drop the identity so a later comparison sees the change.
185
+ for (const entry of this.windows.values())
186
+ entry.abandoned = true;
187
+ this.fingerprint.clear();
188
+ }
189
+ this.wake();
190
+ }
191
+ get teardownRequested() {
192
+ return this.teardownPending;
193
+ }
194
+ /**
195
+ * Resolves when nothing is in flight and no window is still worth waiting
196
+ * for. Bounded by the ceiling measured from the teardown request — absolute,
197
+ * never extended by request activity.
198
+ *
199
+ * On expiry, before resolving and without yielding in between: shuts
200
+ * admission, gives up on the remaining windows, then waits once more for the
201
+ * already-admitted requests to settle.
202
+ */
203
+ async drain() {
204
+ // `??`, not `||`: a teardown requested at timestamp 0 is a real teardown,
205
+ // and treating it as absent would restart the ceiling from drain() — making
206
+ // the deadline relative to the wrong event, which is the sliding behaviour
207
+ // this design rejects.
208
+ const deadline = (this.teardownAt ?? this.now()) + this.ceilingMs;
209
+ while (this.inFlight > 0 || this.liveWindows > 0) {
210
+ const remaining = deadline - this.now();
211
+ if (remaining <= 0)
212
+ break;
213
+ await this.changed(remaining);
214
+ }
215
+ if (this.inFlight === 0 && this.liveWindows === 0) {
216
+ return { abandonedWindows: this.abandonedLabels() };
217
+ }
218
+ // Expiry. Synchronous, before any await: no request may enter after this.
219
+ this.admissionForcedShut = true;
220
+ for (const entry of this.windows.values())
221
+ entry.abandoned = true;
222
+ while (this.inFlight > 0) {
223
+ await this.changed();
224
+ }
225
+ return { abandonedWindows: this.abandonedLabels() };
226
+ }
227
+ get liveWindows() {
228
+ let live = 0;
229
+ for (const entry of this.windows.values())
230
+ if (!entry.abandoned)
231
+ live += 1;
232
+ return live;
233
+ }
234
+ abandonedLabels() {
235
+ const labels = new Set();
236
+ for (const entry of this.windows.values()) {
237
+ if (entry.abandoned)
238
+ labels.add(entry.label);
239
+ }
240
+ return [...labels];
241
+ }
242
+ // ---------------------------------------------------------- transitions ---
243
+ /**
244
+ * Runs a transition on the serializing tail.
245
+ *
246
+ * `connect` and `disconnect` join the tail of their own kind — two callers
247
+ * wanting the same thing get one execution and the same answer — but only
248
+ * when nothing is queued behind it, so a join can never overtake a queued
249
+ * transition of another kind. `recover` and `cleanup` never join and are
250
+ * never joined: a recovery carries its own request's baseline, and an
251
+ * internal cleanup owes its result to nobody while a caller's teardown owes a
252
+ * report.
253
+ */
254
+ transition(kind, run) {
255
+ const joinable = kind === 'connect' || kind === 'disconnect';
256
+ if (joinable && this.tailKind === kind && this.tailPromise) {
257
+ // Joining shares the ANSWER, not just the execution: a joiner that got a
258
+ // resolved promise carrying nothing would have to invent a result, and
259
+ // for a teardown that means reporting no abandoned locks when there were
260
+ // some. Callers of one kind ask the same question, so they get one reply.
261
+ return this.tailPromise;
262
+ }
263
+ const queued = this.tail.then(run, run);
264
+ this.tail = queued.then(() => undefined, () => undefined);
265
+ this.tailKind = kind;
266
+ this.tailPromise = queued;
267
+ const settle = () => {
268
+ if (this.tailPromise === queued) {
269
+ this.tailKind = null;
270
+ this.tailPromise = null;
271
+ }
272
+ };
273
+ queued.then(settle, settle);
274
+ return queued;
275
+ }
276
+ // ----------------------------------------------------------- internals ---
277
+ wake() {
278
+ const waiters = this.waiters;
279
+ this.waiters = [];
280
+ for (const resolve of waiters)
281
+ resolve();
282
+ }
283
+ changed(timeoutMs) {
284
+ return new Promise((resolve) => {
285
+ let done = false;
286
+ const finish = () => {
287
+ if (done)
288
+ return;
289
+ done = true;
290
+ resolve();
291
+ };
292
+ this.waiters.push(finish);
293
+ if (timeoutMs !== undefined) {
294
+ const timer = setTimeout(finish, timeoutMs);
295
+ if (typeof timer.unref === 'function')
296
+ timer.unref();
297
+ }
298
+ });
299
+ }
300
+ }
301
+ exports.SessionLifecycle = SessionLifecycle;