@sasjs/adapter 5.1.3 → 5.2.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.
package/SASjs.js CHANGED
@@ -629,19 +629,27 @@ class SASjs {
629
629
  */
630
630
  startComputeJob(sasJob_1, data_1) {
631
631
  return __awaiter(this, arguments, void 0, function* (sasJob, data, config = {}, authConfig, waitForResult, pollOptions, printPid = false, variables, verboseMode, onTokensRefreshed) {
632
- var _a, _b, _c, _d;
632
+ var _a, _b, _c, _d, _e;
633
633
  config = Object.assign(Object.assign({}, this.sasjsConfig), config);
634
- this.isMethodSupported('startComputeJob', [types_2.ServerType.SasViya]);
635
- if (!config.contextName) {
636
- throw new Error('Context name is undefined. Please set a `contextName` in your SASjs or override config.');
637
- }
634
+ this.isMethodSupported('startComputeJob', [
635
+ types_2.ServerType.SasViya,
636
+ types_2.ServerType.Sasjs
637
+ ]);
638
638
  if (verboseMode) {
639
639
  (_a = this.requestClient) === null || _a === void 0 ? void 0 : _a.setVerboseMode(verboseMode);
640
640
  (_b = this.requestClient) === null || _b === void 0 ? void 0 : _b.enableVerboseMode();
641
641
  }
642
642
  else if (verboseMode === false)
643
643
  (_c = this.requestClient) === null || _c === void 0 ? void 0 : _c.disableVerboseMode();
644
- return (_d = this.sasViyaApiClient) === null || _d === void 0 ? void 0 : _d.executeComputeJob(sasJob, config.contextName, config.debug, data, authConfig, !!waitForResult, false, pollOptions, printPid, variables, onTokensRefreshed);
644
+ // A SASjs Server has no compute contexts and no job definitions: the program
645
+ // is a file in the drive, triggered by path. The result carries the same
646
+ // `links` a Viya compute job does, so polling and log retrieval are shared.
647
+ if (this.sasjsConfig.serverType === types_2.ServerType.Sasjs)
648
+ return (_d = this.sasJSApiClient) === null || _d === void 0 ? void 0 : _d.startComputeJob(sasJob, data, config, authConfig, !!waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
649
+ if (!config.contextName) {
650
+ throw new Error('Context name is undefined. Please set a `contextName` in your SASjs or override config.');
651
+ }
652
+ return (_e = this.sasViyaApiClient) === null || _e === void 0 ? void 0 : _e.executeComputeJob(sasJob, config.contextName, config.debug, data, authConfig, !!waitForResult, false, pollOptions, printPid, variables, onTokensRefreshed);
645
653
  });
646
654
  }
647
655
  /**
@@ -1,5 +1,7 @@
1
- import { AuthConfig, ServicePackSASjs } from '@sasjs/utils/types';
2
- import { ExecutionQuery } from './types';
1
+ import { AuthConfig, MacroVar, ServicePackSASjs } from '@sasjs/utils/types';
2
+ import { ExecutionQuery, Job, PollOptions } from './types';
3
+ import { OnTokensRefreshed } from './auth/getTokens';
4
+ import { StateReader } from './api/viya/pollJobState';
3
5
  import { RequestClient } from './request/RequestClient';
4
6
  export interface SASjsAuthResponse {
5
7
  access_token: string;
@@ -10,6 +12,15 @@ export interface ScriptExecutionResult {
10
12
  webout?: string;
11
13
  printOutput?: string;
12
14
  }
15
+ /**
16
+ * How SASjs Server reports the state of a triggered program.
17
+ *
18
+ * Two differences from Viya, both its own to know: the body is JSON with a
19
+ * `state` member (`{ "state": "running" }`) rather than plain text, and
20
+ * `initialising` - a session that exists before the program has started - has
21
+ * no Viya equivalent and is not a terminal state.
22
+ */
23
+ export declare const readSasjsState: StateReader;
13
24
  export declare class SASjsApiClient {
14
25
  private requestClient;
15
26
  constructor(requestClient: RequestClient);
@@ -58,6 +69,29 @@ export declare class SASjsApiClient {
58
69
  * @param authCode - the auth code received from the server.
59
70
  */
60
71
  getAccessToken(clientId: string, authCode: string): Promise<SASjsAuthResponse>;
72
+ /**
73
+ * Starts a stored program and returns the job it runs in.
74
+ *
75
+ * The result is the shape a Viya compute job has - an id and `links` with
76
+ * `state` and `log` relations - because that is what `pollJobState`,
77
+ * `fetchLogFileContent` and everything written against them already follow.
78
+ * A caller therefore does not need to know which of the two servers it is
79
+ * talking to.
80
+ *
81
+ * @param sasJob - the path of the program, relative to `appLoc` unless it starts with `/`.
82
+ * @param data - values passed to the program as macro variables.
83
+ * @param config - the SASjs config for this call; `debug` turns on `_debug`.
84
+ * @param authConfig - an access token, or the tokens to mint one from.
85
+ * @param waitForResult - poll until the program finishes before resolving.
86
+ * @param pollOptions - poll interval and maximum attempts, see `pollJobState`.
87
+ * @param printPid - include the OS process id in the job, while it is running.
88
+ * @param variables - macro variables, merged with `data`.
89
+ * @param onTokensRefreshed - called with the rotated token pair after a refresh.
90
+ */
91
+ startComputeJob(sasJob: string, data: any, config: any, authConfig?: AuthConfig, waitForResult?: boolean, pollOptions?: PollOptions, printPid?: boolean, variables?: MacroVar, onTokensRefreshed?: OnTokensRefreshed): Promise<{
92
+ job: Job;
93
+ log: string;
94
+ }>;
61
95
  /**
62
96
  * Exchanges the refresh token for an access token.
63
97
  * @param refreshToken - the refresh token received from the server.
package/SASjsApiClient.js CHANGED
@@ -12,14 +12,31 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.SASjsApiClient = void 0;
15
+ exports.SASjsApiClient = exports.readSasjsState = void 0;
16
16
  const form_data_1 = __importDefault(require("form-data"));
17
17
  const types_1 = require("@sasjs/utils/types");
18
18
  const error_1 = require("@sasjs/utils/error");
19
+ const pollJobState_1 = require("./api/viya/pollJobState");
20
+ const errors_1 = require("./types/errors");
19
21
  const getAccessTokenForSasjs_1 = require("./auth/getAccessTokenForSasjs");
20
22
  const refreshTokensForSasjs_1 = require("./auth/refreshTokensForSasjs");
21
23
  const getTokens_1 = require("./auth/getTokens");
22
24
  const isNode_1 = require("./utils/isNode");
25
+ /**
26
+ * How SASjs Server reports the state of a triggered program.
27
+ *
28
+ * Two differences from Viya, both its own to know: the body is JSON with a
29
+ * `state` member (`{ "state": "running" }`) rather than plain text, and
30
+ * `initialising` - a session that exists before the program has started - has
31
+ * no Viya equivalent and is not a terminal state.
32
+ */
33
+ const readSasjsState = (body) => {
34
+ const state = typeof body === 'string' ? body.trim() : body === null || body === void 0 ? void 0 : body.state;
35
+ if (state === 'initialising')
36
+ return pollJobState_1.JobState.Pending;
37
+ return (state !== null && state !== void 0 ? state : '');
38
+ };
39
+ exports.readSasjsState = readSasjsState;
23
40
  class SASjsApiClient {
24
41
  constructor(requestClient) {
25
42
  this.requestClient = requestClient;
@@ -119,6 +136,89 @@ class SASjsApiClient {
119
136
  return (0, getAccessTokenForSasjs_1.getAccessTokenForSasjs)(this.requestClient, clientId, authCode);
120
137
  });
121
138
  }
139
+ /**
140
+ * Starts a stored program and returns the job it runs in.
141
+ *
142
+ * The result is the shape a Viya compute job has - an id and `links` with
143
+ * `state` and `log` relations - because that is what `pollJobState`,
144
+ * `fetchLogFileContent` and everything written against them already follow.
145
+ * A caller therefore does not need to know which of the two servers it is
146
+ * talking to.
147
+ *
148
+ * @param sasJob - the path of the program, relative to `appLoc` unless it starts with `/`.
149
+ * @param data - values passed to the program as macro variables.
150
+ * @param config - the SASjs config for this call; `debug` turns on `_debug`.
151
+ * @param authConfig - an access token, or the tokens to mint one from.
152
+ * @param waitForResult - poll until the program finishes before resolving.
153
+ * @param pollOptions - poll interval and maximum attempts, see `pollJobState`.
154
+ * @param printPid - include the OS process id in the job, while it is running.
155
+ * @param variables - macro variables, merged with `data`.
156
+ * @param onTokensRefreshed - called with the rotated token pair after a refresh.
157
+ */
158
+ startComputeJob(sasJob_1, data_1, config_1, authConfig_1) {
159
+ return __awaiter(this, arguments, void 0, function* (sasJob, data, config, authConfig, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
160
+ var _a, _b, _c;
161
+ const access_token = yield this.getAccessTokenForRequest(authConfig);
162
+ const _program = sasJob.startsWith('/')
163
+ ? sasJob
164
+ : `${(_a = config.appLoc) !== null && _a !== void 0 ? _a : ''}/${sasJob}`;
165
+ // Every query parameter becomes a macro variable, the same way the
166
+ // synchronous execute endpoint builds them. `_program` and `_debug` are
167
+ // reserved: they are set below from the arguments, so a payload or a macro
168
+ // variable set that happens to carry either key cannot redirect the call to
169
+ // a different program.
170
+ const query = new URLSearchParams();
171
+ const reserved = new Set(['_program', '_debug']);
172
+ for (const [key, value] of Object.entries(Object.assign(Object.assign({}, (data !== null && data !== void 0 ? data : {})), (variables !== null && variables !== void 0 ? variables : {}))))
173
+ if (!reserved.has(key) && value !== undefined && value !== null)
174
+ query.set(key, String(value));
175
+ query.set('_program', _program);
176
+ if (config.debug)
177
+ query.set('_debug', '131');
178
+ const { result } = yield this.requestClient
179
+ .post(`SASjsApi/stp/trigger?${query.toString()}`, {}, access_token)
180
+ .catch((err) => {
181
+ throw (0, error_1.prefixMessage)(err, 'Error while triggering the program. ');
182
+ });
183
+ // The trigger answers 200 with a failure body when the program cannot be
184
+ // found or the runtime refuses it, so a missing session id is the only
185
+ // signal that the call did not start anything. Without this the caller gets
186
+ // links built from `undefined` and the failure surfaces later as a 404 on a
187
+ // state URL.
188
+ if (!(result === null || result === void 0 ? void 0 : result.sessionId))
189
+ throw new Error(`Error while triggering the program. ${(_c = (_b = result === null || result === void 0 ? void 0 : result.error) !== null && _b !== void 0 ? _b : result === null || result === void 0 ? void 0 : result.message) !== null && _c !== void 0 ? _c : 'No session id was returned.'}`);
190
+ // absolute paths, as Viya job links are: a caller composes `${serverUrl}${href}`
191
+ // to fetch a log, so a relative href turns into `https://hostsasjsapi/...`
192
+ const links = [
193
+ {
194
+ rel: 'state',
195
+ href: `/SASjsApi/session/${result.sessionId}/state`,
196
+ method: 'GET'
197
+ },
198
+ {
199
+ rel: 'log',
200
+ href: `/SASjsApi/session/${result.sessionId}/log`,
201
+ method: 'GET'
202
+ },
203
+ {
204
+ rel: 'self',
205
+ href: `/SASjsApi/session/${result.sessionId}`,
206
+ method: 'GET'
207
+ }
208
+ ];
209
+ const job = Object.assign({ id: result.sessionId, links }, (printPid && result.pid !== undefined ? { pid: result.pid } : {}));
210
+ if (!waitForResult)
211
+ return { job, log: '' };
212
+ const state = yield (0, pollJobState_1.pollJobState)(this.requestClient, job, !!config.debug, authConfig, pollOptions, undefined, onTokensRefreshed, types_1.ServerType.Sasjs, exports.readSasjsState);
213
+ const { result: log } = yield this.requestClient
214
+ .get(`SASjsApi/session/${result.sessionId}/log`, access_token, 'text/plain')
215
+ .catch(() => ({ result: '' }));
216
+ const finished = Object.assign(Object.assign({}, job), { state });
217
+ if (state === pollJobState_1.JobState.Failed || state === pollJobState_1.JobState.Error)
218
+ throw new errors_1.ComputeJobExecutionError(finished, log !== null && log !== void 0 ? log : '');
219
+ return { job: finished, log: log !== null && log !== void 0 ? log : '' };
220
+ });
221
+ }
122
222
  /**
123
223
  * Exchanges the refresh token for an access token.
124
224
  * @param refreshToken - the refresh token received from the server.
@@ -1,8 +1,21 @@
1
- import { AuthConfig } from '@sasjs/utils/types';
1
+ import { AuthConfig, ServerType } from '@sasjs/utils/types';
2
2
  import { Job, PollOptions } from '../..';
3
3
  import { OnTokensRefreshed } from '../../auth/getTokens';
4
4
  import { RequestClient } from '../../request/RequestClient';
5
5
  import { WriteStream, JobSessionManager } from '../../types';
6
+ /**
7
+ * How a caller's server reports the state of a job.
8
+ *
9
+ * The poller follows a job's `state` link and hands the body to this function,
10
+ * so a server that answers differently - or has states of its own - says so at
11
+ * the call site rather than teaching this module about itself.
12
+ */
13
+ export type StateReader = (body: unknown) => JobState;
14
+ /**
15
+ * The Viya compute API answers the state link with plain text: the state name,
16
+ * padded with a newline.
17
+ */
18
+ export declare const readViyaState: StateReader;
6
19
  export declare enum JobState {
7
20
  Completed = "completed",
8
21
  Running = "running",
@@ -13,6 +26,16 @@ export declare enum JobState {
13
26
  Error = "error"
14
27
  }
15
28
  /**
29
+ * Polls a job that carries `links`, following the one with `rel === 'state'`
30
+ * until it stops being running, pending or unavailable.
31
+ *
32
+ * The shape it follows is the Viya compute API's - that is where the `state`
33
+ * link, the `?_action=wait` query and the parent-session health check come from
34
+ * - but the shape itself is now a contract two servers answer: SASjs Server
35
+ * returns the same links for a triggered program, so the same poll loop drives
36
+ * both. What differs between them is how the state body is read, and that is a
37
+ * `StateReader` the caller supplies rather than something this module decides.
38
+ *
16
39
  * Polls job status using default or provided poll options.
17
40
  * @param requestClient - the pre-configured HTTP request client.
18
41
  * @param postedJob - the relative or absolute path to the job.
@@ -36,7 +59,7 @@ export declare enum JobState {
36
59
  * @param jobSessionManager - job session object containing session object and an instance of Session Manager. Job session object is used to periodically (every 10th job state poll) check parent session state.
37
60
  * @returns - a promise which resolves with a job state
38
61
  */
39
- export declare function pollJobState(requestClient: RequestClient, postedJob: Job, debug: boolean, authConfig?: AuthConfig, pollOptions?: PollOptions, jobSessionManager?: JobSessionManager, onTokensRefreshed?: OnTokensRefreshed): Promise<JobState>;
62
+ export declare function pollJobState(requestClient: RequestClient, postedJob: Job, debug: boolean, authConfig?: AuthConfig, pollOptions?: PollOptions, jobSessionManager?: JobSessionManager, onTokensRefreshed?: OnTokensRefreshed, serverType?: ServerType, readState?: StateReader): Promise<JobState>;
40
63
  /**
41
64
  * Polls job state.
42
65
  * @param requestClient - the pre-configured HTTP request client.
@@ -51,7 +74,7 @@ export declare function pollJobState(requestClient: RequestClient, postedJob: Jo
51
74
  * @param jobSessionManager - job session object containing session object and an instance of Session Manager. Job session object is used to periodically (every 10th job state poll) check parent session state. Session state is considered healthy if it is equal to 'running' or 'idle'.
52
75
  * @returns - a promise which resolves with a job state
53
76
  */
54
- export declare const doPoll: (requestClient: RequestClient, postedJob: Job, currentState: JobState, debug: boolean, pollCount: number, pollOptions: PollOptions, authConfig?: AuthConfig, streamLog?: boolean, logStream?: WriteStream, jobSessionManager?: JobSessionManager, onTokensRefreshed?: OnTokensRefreshed) => Promise<{
77
+ export declare const doPoll: (requestClient: RequestClient, postedJob: Job, currentState: JobState, debug: boolean, pollCount: number, pollOptions: PollOptions, authConfig?: AuthConfig, streamLog?: boolean, logStream?: WriteStream, jobSessionManager?: JobSessionManager, onTokensRefreshed?: OnTokensRefreshed, serverType?: ServerType, readState?: StateReader) => Promise<{
55
78
  state: JobState;
56
79
  pollCount: number;
57
80
  }>;
@@ -9,7 +9,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.doPoll = exports.JobState = void 0;
12
+ exports.doPoll = exports.JobState = exports.readViyaState = void 0;
13
13
  exports.pollJobState = pollJobState;
14
14
  const types_1 = require("@sasjs/utils/types");
15
15
  const getTokens_1 = require("../../auth/getTokens");
@@ -17,6 +17,12 @@ const errors_1 = require("../../types/errors");
17
17
  const types_2 = require("../../types");
18
18
  const utils_1 = require("../../utils");
19
19
  const host_1 = require("../../utils/host");
20
+ /**
21
+ * The Viya compute API answers the state link with plain text: the state name,
22
+ * padded with a newline.
23
+ */
24
+ const readViyaState = (body) => String(body !== null && body !== void 0 ? body : '').trim();
25
+ exports.readViyaState = readViyaState;
20
26
  var JobState;
21
27
  (function (JobState) {
22
28
  JobState["Completed"] = "completed";
@@ -28,6 +34,16 @@ var JobState;
28
34
  JobState["Error"] = "error";
29
35
  })(JobState || (exports.JobState = JobState = {}));
30
36
  /**
37
+ * Polls a job that carries `links`, following the one with `rel === 'state'`
38
+ * until it stops being running, pending or unavailable.
39
+ *
40
+ * The shape it follows is the Viya compute API's - that is where the `state`
41
+ * link, the `?_action=wait` query and the parent-session health check come from
42
+ * - but the shape itself is now a contract two servers answer: SASjs Server
43
+ * returns the same links for a triggered program, so the same poll loop drives
44
+ * both. What differs between them is how the state body is read, and that is a
45
+ * `StateReader` the caller supplies rather than something this module decides.
46
+ *
31
47
  * Polls job status using default or provided poll options.
32
48
  * @param requestClient - the pre-configured HTTP request client.
33
49
  * @param postedJob - the relative or absolute path to the job.
@@ -51,8 +67,8 @@ var JobState;
51
67
  * @param jobSessionManager - job session object containing session object and an instance of Session Manager. Job session object is used to periodically (every 10th job state poll) check parent session state.
52
68
  * @returns - a promise which resolves with a job state
53
69
  */
54
- function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions, jobSessionManager, onTokensRefreshed) {
55
- return __awaiter(this, void 0, void 0, function* () {
70
+ function pollJobState(requestClient_1, postedJob_1, debug_1, authConfig_1, pollOptions_1, jobSessionManager_1, onTokensRefreshed_1) {
71
+ return __awaiter(this, arguments, void 0, function* (requestClient, postedJob, debug, authConfig, pollOptions, jobSessionManager, onTokensRefreshed, serverType = types_1.ServerType.SasViya, readState = exports.readViyaState) {
56
72
  const logger = (0, host_1.getLogger)();
57
73
  const streamLog = (pollOptions === null || pollOptions === void 0 ? void 0 : pollOptions.streamLog) || false;
58
74
  const defaultPollStrategy = [
@@ -84,7 +100,7 @@ function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions,
84
100
  if (!stateLink) {
85
101
  throw new Error(`Job state link was not found.`);
86
102
  }
87
- let currentState = yield getJobState(requestClient, postedJob, JobState.NoState, debug, authConfig).catch((err) => {
103
+ let currentState = yield getJobState(requestClient, postedJob, JobState.NoState, debug, authConfig, serverType, readState).catch((err) => {
88
104
  logger.error(`Error fetching job state from ${stateLink.href}. Starting poll, assuming job to be running.`, err);
89
105
  return JobState.Unavailable;
90
106
  });
@@ -97,7 +113,7 @@ function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions,
97
113
  const { getFileStream } = require('./getFileStream');
98
114
  logFileStream = yield getFileStream(postedJob, pollOptions.logFolderPath);
99
115
  }
100
- let result = yield (0, exports.doPoll)(requestClient, postedJob, currentState, debug, pollCount, pollOptions, authConfig, streamLog, logFileStream, jobSessionManager, onTokensRefreshed);
116
+ let result = yield (0, exports.doPoll)(requestClient, postedJob, currentState, debug, pollCount, pollOptions, authConfig, streamLog, logFileStream, jobSessionManager, onTokensRefreshed, serverType, readState);
101
117
  currentState = result.state;
102
118
  pollCount = result.pollCount;
103
119
  if (!needsRetry(currentState) ||
@@ -111,7 +127,7 @@ function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions,
111
127
  if (pollOptions) {
112
128
  defaultPollOptions.logFolderPath = pollOptions.logFolderPath;
113
129
  }
114
- result = yield (0, exports.doPoll)(requestClient, postedJob, currentState, debug, pollCount, defaultPollOptions, authConfig, streamLog, logFileStream, jobSessionManager, onTokensRefreshed);
130
+ result = yield (0, exports.doPoll)(requestClient, postedJob, currentState, debug, pollCount, defaultPollOptions, authConfig, streamLog, logFileStream, jobSessionManager, onTokensRefreshed, serverType, readState);
115
131
  currentState = result.state;
116
132
  pollCount = result.pollCount;
117
133
  }
@@ -120,18 +136,18 @@ function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions,
120
136
  return currentState;
121
137
  });
122
138
  }
123
- const getJobState = (requestClient, job, currentState, debug, authConfig, onTokensRefreshed) => __awaiter(void 0, void 0, void 0, function* () {
139
+ const getJobState = (requestClient_1, job_1, currentState_1, debug_1, authConfig_1, ...args_1) => __awaiter(void 0, [requestClient_1, job_1, currentState_1, debug_1, authConfig_1, ...args_1], void 0, function* (requestClient, job, currentState, debug, authConfig, serverType = types_1.ServerType.SasViya, readState = exports.readViyaState, onTokensRefreshed) {
124
140
  const stateLink = job.links.find((l) => l.rel === 'state');
125
141
  if (needsRetry(currentState)) {
126
142
  let tokens;
127
143
  if (authConfig)
128
- tokens = yield (0, getTokens_1.getTokens)(requestClient, authConfig, types_1.ServerType.SasViya, onTokensRefreshed);
144
+ tokens = yield (0, getTokens_1.getTokens)(requestClient, authConfig, serverType, onTokensRefreshed);
129
145
  const { result: jobState } = yield requestClient
130
146
  .get(`${stateLink.href}?_action=wait&wait=300`, tokens === null || tokens === void 0 ? void 0 : tokens.access_token, 'text/plain', {}, debug)
131
147
  .catch((err) => {
132
148
  throw new errors_1.JobStatePollError(job.id, err);
133
149
  });
134
- return jobState.trim();
150
+ return readState(jobState);
135
151
  }
136
152
  else {
137
153
  return currentState;
@@ -155,7 +171,7 @@ const needsRetry = (state) => state === JobState.Running ||
155
171
  * @param jobSessionManager - job session object containing session object and an instance of Session Manager. Job session object is used to periodically (every 10th job state poll) check parent session state. Session state is considered healthy if it is equal to 'running' or 'idle'.
156
172
  * @returns - a promise which resolves with a job state
157
173
  */
158
- const doPoll = (requestClient, postedJob, currentState, debug, pollCount, pollOptions, authConfig, streamLog, logStream, jobSessionManager, onTokensRefreshed) => __awaiter(void 0, void 0, void 0, function* () {
174
+ const doPoll = (requestClient_1, postedJob_1, currentState_1, debug_1, pollCount_1, pollOptions_1, authConfig_1, streamLog_1, logStream_1, jobSessionManager_1, onTokensRefreshed_1, ...args_1) => __awaiter(void 0, [requestClient_1, postedJob_1, currentState_1, debug_1, pollCount_1, pollOptions_1, authConfig_1, streamLog_1, logStream_1, jobSessionManager_1, onTokensRefreshed_1, ...args_1], void 0, function* (requestClient, postedJob, currentState, debug, pollCount, pollOptions, authConfig, streamLog, logStream, jobSessionManager, onTokensRefreshed, serverType = types_1.ServerType.SasViya, readState = exports.readViyaState) {
159
175
  var _a, _b;
160
176
  const { maxPollCount, pollInterval } = pollOptions;
161
177
  const logger = (0, host_1.getLogger)();
@@ -189,7 +205,7 @@ const doPoll = (requestClient, postedJob, currentState, debug, pollCount, pollOp
189
205
  throw new errors_1.JobStatePollError(jobId, new Error(sessionError));
190
206
  }
191
207
  }
192
- state = yield getJobState(requestClient, postedJob, state, debug, authConfig, onTokensRefreshed).catch((err) => {
208
+ state = yield getJobState(requestClient, postedJob, state, debug, authConfig, serverType, readState, onTokensRefreshed).catch((err) => {
193
209
  errorCount++;
194
210
  if (pollCount >= maxPollCount || errorCount >= maxErrorCount) {
195
211
  throw err;
@@ -4523,19 +4523,27 @@ class SASjs {
4523
4523
  */
4524
4524
  startComputeJob(sasJob_1, data_1) {
4525
4525
  return __awaiter(this, arguments, void 0, function* (sasJob, data, config = {}, authConfig, waitForResult, pollOptions, printPid = false, variables, verboseMode, onTokensRefreshed) {
4526
- var _a, _b, _c, _d;
4526
+ var _a, _b, _c, _d, _e;
4527
4527
  config = Object.assign(Object.assign({}, this.sasjsConfig), config);
4528
- this.isMethodSupported('startComputeJob', [types_2.ServerType.SasViya]);
4529
- if (!config.contextName) {
4530
- throw new Error('Context name is undefined. Please set a `contextName` in your SASjs or override config.');
4531
- }
4528
+ this.isMethodSupported('startComputeJob', [
4529
+ types_2.ServerType.SasViya,
4530
+ types_2.ServerType.Sasjs
4531
+ ]);
4532
4532
  if (verboseMode) {
4533
4533
  (_a = this.requestClient) === null || _a === void 0 ? void 0 : _a.setVerboseMode(verboseMode);
4534
4534
  (_b = this.requestClient) === null || _b === void 0 ? void 0 : _b.enableVerboseMode();
4535
4535
  }
4536
4536
  else if (verboseMode === false)
4537
4537
  (_c = this.requestClient) === null || _c === void 0 ? void 0 : _c.disableVerboseMode();
4538
- return (_d = this.sasViyaApiClient) === null || _d === void 0 ? void 0 : _d.executeComputeJob(sasJob, config.contextName, config.debug, data, authConfig, !!waitForResult, false, pollOptions, printPid, variables, onTokensRefreshed);
4538
+ // A SASjs Server has no compute contexts and no job definitions: the program
4539
+ // is a file in the drive, triggered by path. The result carries the same
4540
+ // `links` a Viya compute job does, so polling and log retrieval are shared.
4541
+ if (this.sasjsConfig.serverType === types_2.ServerType.Sasjs)
4542
+ return (_d = this.sasJSApiClient) === null || _d === void 0 ? void 0 : _d.startComputeJob(sasJob, data, config, authConfig, !!waitForResult, pollOptions, printPid, variables, onTokensRefreshed);
4543
+ if (!config.contextName) {
4544
+ throw new Error('Context name is undefined. Please set a `contextName` in your SASjs or override config.');
4545
+ }
4546
+ return (_e = this.sasViyaApiClient) === null || _e === void 0 ? void 0 : _e.executeComputeJob(sasJob, config.contextName, config.debug, data, authConfig, !!waitForResult, false, pollOptions, printPid, variables, onTokensRefreshed);
4539
4547
  });
4540
4548
  }
4541
4549
  /**
@@ -4708,14 +4716,31 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4708
4716
  return (mod && mod.__esModule) ? mod : { "default": mod };
4709
4717
  };
4710
4718
  Object.defineProperty(exports, "__esModule", ({ value: true }));
4711
- exports.SASjsApiClient = void 0;
4719
+ exports.SASjsApiClient = exports.readSasjsState = void 0;
4712
4720
  const form_data_1 = __importDefault(__webpack_require__(1894));
4713
4721
  const types_1 = __webpack_require__(3631);
4714
4722
  const error_1 = __webpack_require__(6340);
4723
+ const pollJobState_1 = __webpack_require__(1514);
4724
+ const errors_1 = __webpack_require__(7388);
4715
4725
  const getAccessTokenForSasjs_1 = __webpack_require__(9239);
4716
4726
  const refreshTokensForSasjs_1 = __webpack_require__(6725);
4717
4727
  const getTokens_1 = __webpack_require__(9609);
4718
4728
  const isNode_1 = __webpack_require__(6308);
4729
+ /**
4730
+ * How SASjs Server reports the state of a triggered program.
4731
+ *
4732
+ * Two differences from Viya, both its own to know: the body is JSON with a
4733
+ * `state` member (`{ "state": "running" }`) rather than plain text, and
4734
+ * `initialising` - a session that exists before the program has started - has
4735
+ * no Viya equivalent and is not a terminal state.
4736
+ */
4737
+ const readSasjsState = (body) => {
4738
+ const state = typeof body === 'string' ? body.trim() : body === null || body === void 0 ? void 0 : body.state;
4739
+ if (state === 'initialising')
4740
+ return pollJobState_1.JobState.Pending;
4741
+ return (state !== null && state !== void 0 ? state : '');
4742
+ };
4743
+ exports.readSasjsState = readSasjsState;
4719
4744
  class SASjsApiClient {
4720
4745
  constructor(requestClient) {
4721
4746
  this.requestClient = requestClient;
@@ -4815,6 +4840,89 @@ class SASjsApiClient {
4815
4840
  return (0, getAccessTokenForSasjs_1.getAccessTokenForSasjs)(this.requestClient, clientId, authCode);
4816
4841
  });
4817
4842
  }
4843
+ /**
4844
+ * Starts a stored program and returns the job it runs in.
4845
+ *
4846
+ * The result is the shape a Viya compute job has - an id and `links` with
4847
+ * `state` and `log` relations - because that is what `pollJobState`,
4848
+ * `fetchLogFileContent` and everything written against them already follow.
4849
+ * A caller therefore does not need to know which of the two servers it is
4850
+ * talking to.
4851
+ *
4852
+ * @param sasJob - the path of the program, relative to `appLoc` unless it starts with `/`.
4853
+ * @param data - values passed to the program as macro variables.
4854
+ * @param config - the SASjs config for this call; `debug` turns on `_debug`.
4855
+ * @param authConfig - an access token, or the tokens to mint one from.
4856
+ * @param waitForResult - poll until the program finishes before resolving.
4857
+ * @param pollOptions - poll interval and maximum attempts, see `pollJobState`.
4858
+ * @param printPid - include the OS process id in the job, while it is running.
4859
+ * @param variables - macro variables, merged with `data`.
4860
+ * @param onTokensRefreshed - called with the rotated token pair after a refresh.
4861
+ */
4862
+ startComputeJob(sasJob_1, data_1, config_1, authConfig_1) {
4863
+ return __awaiter(this, arguments, void 0, function* (sasJob, data, config, authConfig, waitForResult = true, pollOptions, printPid = false, variables, onTokensRefreshed) {
4864
+ var _a, _b, _c;
4865
+ const access_token = yield this.getAccessTokenForRequest(authConfig);
4866
+ const _program = sasJob.startsWith('/')
4867
+ ? sasJob
4868
+ : `${(_a = config.appLoc) !== null && _a !== void 0 ? _a : ''}/${sasJob}`;
4869
+ // Every query parameter becomes a macro variable, the same way the
4870
+ // synchronous execute endpoint builds them. `_program` and `_debug` are
4871
+ // reserved: they are set below from the arguments, so a payload or a macro
4872
+ // variable set that happens to carry either key cannot redirect the call to
4873
+ // a different program.
4874
+ const query = new URLSearchParams();
4875
+ const reserved = new Set(['_program', '_debug']);
4876
+ for (const [key, value] of Object.entries(Object.assign(Object.assign({}, (data !== null && data !== void 0 ? data : {})), (variables !== null && variables !== void 0 ? variables : {}))))
4877
+ if (!reserved.has(key) && value !== undefined && value !== null)
4878
+ query.set(key, String(value));
4879
+ query.set('_program', _program);
4880
+ if (config.debug)
4881
+ query.set('_debug', '131');
4882
+ const { result } = yield this.requestClient
4883
+ .post(`SASjsApi/stp/trigger?${query.toString()}`, {}, access_token)
4884
+ .catch((err) => {
4885
+ throw (0, error_1.prefixMessage)(err, 'Error while triggering the program. ');
4886
+ });
4887
+ // The trigger answers 200 with a failure body when the program cannot be
4888
+ // found or the runtime refuses it, so a missing session id is the only
4889
+ // signal that the call did not start anything. Without this the caller gets
4890
+ // links built from `undefined` and the failure surfaces later as a 404 on a
4891
+ // state URL.
4892
+ if (!(result === null || result === void 0 ? void 0 : result.sessionId))
4893
+ throw new Error(`Error while triggering the program. ${(_c = (_b = result === null || result === void 0 ? void 0 : result.error) !== null && _b !== void 0 ? _b : result === null || result === void 0 ? void 0 : result.message) !== null && _c !== void 0 ? _c : 'No session id was returned.'}`);
4894
+ // absolute paths, as Viya job links are: a caller composes `${serverUrl}${href}`
4895
+ // to fetch a log, so a relative href turns into `https://hostsasjsapi/...`
4896
+ const links = [
4897
+ {
4898
+ rel: 'state',
4899
+ href: `/SASjsApi/session/${result.sessionId}/state`,
4900
+ method: 'GET'
4901
+ },
4902
+ {
4903
+ rel: 'log',
4904
+ href: `/SASjsApi/session/${result.sessionId}/log`,
4905
+ method: 'GET'
4906
+ },
4907
+ {
4908
+ rel: 'self',
4909
+ href: `/SASjsApi/session/${result.sessionId}`,
4910
+ method: 'GET'
4911
+ }
4912
+ ];
4913
+ const job = Object.assign({ id: result.sessionId, links }, (printPid && result.pid !== undefined ? { pid: result.pid } : {}));
4914
+ if (!waitForResult)
4915
+ return { job, log: '' };
4916
+ const state = yield (0, pollJobState_1.pollJobState)(this.requestClient, job, !!config.debug, authConfig, pollOptions, undefined, onTokensRefreshed, types_1.ServerType.Sasjs, exports.readSasjsState);
4917
+ const { result: log } = yield this.requestClient
4918
+ .get(`SASjsApi/session/${result.sessionId}/log`, access_token, 'text/plain')
4919
+ .catch(() => ({ result: '' }));
4920
+ const finished = Object.assign(Object.assign({}, job), { state });
4921
+ if (state === pollJobState_1.JobState.Failed || state === pollJobState_1.JobState.Error)
4922
+ throw new errors_1.ComputeJobExecutionError(finished, log !== null && log !== void 0 ? log : '');
4923
+ return { job: finished, log: log !== null && log !== void 0 ? log : '' };
4924
+ });
4925
+ }
4818
4926
  /**
4819
4927
  * Exchanges the refresh token for an access token.
4820
4928
  * @param refreshToken - the refresh token received from the server.
@@ -5451,7 +5559,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
5451
5559
  });
5452
5560
  };
5453
5561
  Object.defineProperty(exports, "__esModule", ({ value: true }));
5454
- exports.doPoll = exports.JobState = void 0;
5562
+ exports.doPoll = exports.JobState = exports.readViyaState = void 0;
5455
5563
  exports.pollJobState = pollJobState;
5456
5564
  const types_1 = __webpack_require__(3631);
5457
5565
  const getTokens_1 = __webpack_require__(9609);
@@ -5459,6 +5567,12 @@ const errors_1 = __webpack_require__(7388);
5459
5567
  const types_2 = __webpack_require__(3574);
5460
5568
  const utils_1 = __webpack_require__(9266);
5461
5569
  const host_1 = __webpack_require__(5334);
5570
+ /**
5571
+ * The Viya compute API answers the state link with plain text: the state name,
5572
+ * padded with a newline.
5573
+ */
5574
+ const readViyaState = (body) => String(body !== null && body !== void 0 ? body : '').trim();
5575
+ exports.readViyaState = readViyaState;
5462
5576
  var JobState;
5463
5577
  (function (JobState) {
5464
5578
  JobState["Completed"] = "completed";
@@ -5470,6 +5584,16 @@ var JobState;
5470
5584
  JobState["Error"] = "error";
5471
5585
  })(JobState || (exports.JobState = JobState = {}));
5472
5586
  /**
5587
+ * Polls a job that carries `links`, following the one with `rel === 'state'`
5588
+ * until it stops being running, pending or unavailable.
5589
+ *
5590
+ * The shape it follows is the Viya compute API's - that is where the `state`
5591
+ * link, the `?_action=wait` query and the parent-session health check come from
5592
+ * - but the shape itself is now a contract two servers answer: SASjs Server
5593
+ * returns the same links for a triggered program, so the same poll loop drives
5594
+ * both. What differs between them is how the state body is read, and that is a
5595
+ * `StateReader` the caller supplies rather than something this module decides.
5596
+ *
5473
5597
  * Polls job status using default or provided poll options.
5474
5598
  * @param requestClient - the pre-configured HTTP request client.
5475
5599
  * @param postedJob - the relative or absolute path to the job.
@@ -5493,8 +5617,8 @@ var JobState;
5493
5617
  * @param jobSessionManager - job session object containing session object and an instance of Session Manager. Job session object is used to periodically (every 10th job state poll) check parent session state.
5494
5618
  * @returns - a promise which resolves with a job state
5495
5619
  */
5496
- function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions, jobSessionManager, onTokensRefreshed) {
5497
- return __awaiter(this, void 0, void 0, function* () {
5620
+ function pollJobState(requestClient_1, postedJob_1, debug_1, authConfig_1, pollOptions_1, jobSessionManager_1, onTokensRefreshed_1) {
5621
+ return __awaiter(this, arguments, void 0, function* (requestClient, postedJob, debug, authConfig, pollOptions, jobSessionManager, onTokensRefreshed, serverType = types_1.ServerType.SasViya, readState = exports.readViyaState) {
5498
5622
  const logger = (0, host_1.getLogger)();
5499
5623
  const streamLog = (pollOptions === null || pollOptions === void 0 ? void 0 : pollOptions.streamLog) || false;
5500
5624
  const defaultPollStrategy = [
@@ -5526,7 +5650,7 @@ function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions,
5526
5650
  if (!stateLink) {
5527
5651
  throw new Error(`Job state link was not found.`);
5528
5652
  }
5529
- let currentState = yield getJobState(requestClient, postedJob, JobState.NoState, debug, authConfig).catch((err) => {
5653
+ let currentState = yield getJobState(requestClient, postedJob, JobState.NoState, debug, authConfig, serverType, readState).catch((err) => {
5530
5654
  logger.error(`Error fetching job state from ${stateLink.href}. Starting poll, assuming job to be running.`, err);
5531
5655
  return JobState.Unavailable;
5532
5656
  });
@@ -5539,7 +5663,7 @@ function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions,
5539
5663
  const { getFileStream } = __webpack_require__(2573);
5540
5664
  logFileStream = yield getFileStream(postedJob, pollOptions.logFolderPath);
5541
5665
  }
5542
- let result = yield (0, exports.doPoll)(requestClient, postedJob, currentState, debug, pollCount, pollOptions, authConfig, streamLog, logFileStream, jobSessionManager, onTokensRefreshed);
5666
+ let result = yield (0, exports.doPoll)(requestClient, postedJob, currentState, debug, pollCount, pollOptions, authConfig, streamLog, logFileStream, jobSessionManager, onTokensRefreshed, serverType, readState);
5543
5667
  currentState = result.state;
5544
5668
  pollCount = result.pollCount;
5545
5669
  if (!needsRetry(currentState) ||
@@ -5553,7 +5677,7 @@ function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions,
5553
5677
  if (pollOptions) {
5554
5678
  defaultPollOptions.logFolderPath = pollOptions.logFolderPath;
5555
5679
  }
5556
- result = yield (0, exports.doPoll)(requestClient, postedJob, currentState, debug, pollCount, defaultPollOptions, authConfig, streamLog, logFileStream, jobSessionManager, onTokensRefreshed);
5680
+ result = yield (0, exports.doPoll)(requestClient, postedJob, currentState, debug, pollCount, defaultPollOptions, authConfig, streamLog, logFileStream, jobSessionManager, onTokensRefreshed, serverType, readState);
5557
5681
  currentState = result.state;
5558
5682
  pollCount = result.pollCount;
5559
5683
  }
@@ -5562,18 +5686,18 @@ function pollJobState(requestClient, postedJob, debug, authConfig, pollOptions,
5562
5686
  return currentState;
5563
5687
  });
5564
5688
  }
5565
- const getJobState = (requestClient, job, currentState, debug, authConfig, onTokensRefreshed) => __awaiter(void 0, void 0, void 0, function* () {
5689
+ const getJobState = (requestClient_1, job_1, currentState_1, debug_1, authConfig_1, ...args_1) => __awaiter(void 0, [requestClient_1, job_1, currentState_1, debug_1, authConfig_1, ...args_1], void 0, function* (requestClient, job, currentState, debug, authConfig, serverType = types_1.ServerType.SasViya, readState = exports.readViyaState, onTokensRefreshed) {
5566
5690
  const stateLink = job.links.find((l) => l.rel === 'state');
5567
5691
  if (needsRetry(currentState)) {
5568
5692
  let tokens;
5569
5693
  if (authConfig)
5570
- tokens = yield (0, getTokens_1.getTokens)(requestClient, authConfig, types_1.ServerType.SasViya, onTokensRefreshed);
5694
+ tokens = yield (0, getTokens_1.getTokens)(requestClient, authConfig, serverType, onTokensRefreshed);
5571
5695
  const { result: jobState } = yield requestClient
5572
5696
  .get(`${stateLink.href}?_action=wait&wait=300`, tokens === null || tokens === void 0 ? void 0 : tokens.access_token, 'text/plain', {}, debug)
5573
5697
  .catch((err) => {
5574
5698
  throw new errors_1.JobStatePollError(job.id, err);
5575
5699
  });
5576
- return jobState.trim();
5700
+ return readState(jobState);
5577
5701
  }
5578
5702
  else {
5579
5703
  return currentState;
@@ -5597,7 +5721,7 @@ const needsRetry = (state) => state === JobState.Running ||
5597
5721
  * @param jobSessionManager - job session object containing session object and an instance of Session Manager. Job session object is used to periodically (every 10th job state poll) check parent session state. Session state is considered healthy if it is equal to 'running' or 'idle'.
5598
5722
  * @returns - a promise which resolves with a job state
5599
5723
  */
5600
- const doPoll = (requestClient, postedJob, currentState, debug, pollCount, pollOptions, authConfig, streamLog, logStream, jobSessionManager, onTokensRefreshed) => __awaiter(void 0, void 0, void 0, function* () {
5724
+ const doPoll = (requestClient_1, postedJob_1, currentState_1, debug_1, pollCount_1, pollOptions_1, authConfig_1, streamLog_1, logStream_1, jobSessionManager_1, onTokensRefreshed_1, ...args_1) => __awaiter(void 0, [requestClient_1, postedJob_1, currentState_1, debug_1, pollCount_1, pollOptions_1, authConfig_1, streamLog_1, logStream_1, jobSessionManager_1, onTokensRefreshed_1, ...args_1], void 0, function* (requestClient, postedJob, currentState, debug, pollCount, pollOptions, authConfig, streamLog, logStream, jobSessionManager, onTokensRefreshed, serverType = types_1.ServerType.SasViya, readState = exports.readViyaState) {
5601
5725
  var _a, _b;
5602
5726
  const { maxPollCount, pollInterval } = pollOptions;
5603
5727
  const logger = (0, host_1.getLogger)();
@@ -5631,7 +5755,7 @@ const doPoll = (requestClient, postedJob, currentState, debug, pollCount, pollOp
5631
5755
  throw new errors_1.JobStatePollError(jobId, new Error(sessionError));
5632
5756
  }
5633
5757
  }
5634
- state = yield getJobState(requestClient, postedJob, state, debug, authConfig, onTokensRefreshed).catch((err) => {
5758
+ state = yield getJobState(requestClient, postedJob, state, debug, authConfig, serverType, readState, onTokensRefreshed).catch((err) => {
5635
5759
  errorCount++;
5636
5760
  if (pollCount >= maxPollCount || errorCount >= maxErrorCount) {
5637
5761
  throw err;
package/package.json CHANGED
@@ -119,7 +119,7 @@
119
119
  "form-data": "4.0.6",
120
120
  "tough-cookie": "6.0.2"
121
121
  },
122
- "version": "5.1.3",
122
+ "version": "5.2.0",
123
123
  "engines": {
124
124
  "node": ">=22"
125
125
  },