@sasjs/adapter 6.1.0 → 6.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,7 @@ export declare class RequestClient implements HttpClient {
12
12
  protected fileUploadCsrfToken: CsrfToken | undefined;
13
13
  protected httpClient: AxiosInstance;
14
14
  private isRecoveringFromNetworkError;
15
+ private mockReadiness;
15
16
  constructor(baseUrl: string, httpsAgentOptions?: https.AgentOptions, requestsLimit?: number, verboseMode?: VerboseMode);
16
17
  setConfig(baseUrl: string, httpsAgentOptions?: https.AgentOptions): void;
17
18
  saveLocalStorageToken(accessToken: string, refreshToken: string): void;
@@ -19,6 +19,8 @@ const utils_1 = require("../utils");
19
19
  const InvalidSASjsCsrfError_1 = require("../types/errors/InvalidSASjsCsrfError");
20
20
  const host_1 = require("../utils/host");
21
21
  const isNode_1 = require("../utils/isNode");
22
+ const mockReadiness_1 = require("./mockReadiness");
23
+ const MockReadinessError_1 = require("../types/errors/MockReadinessError");
22
24
  class RequestClient {
23
25
  constructor(baseUrl, httpsAgentOptions, requestsLimit, verboseMode) {
24
26
  this.baseUrl = baseUrl;
@@ -27,6 +29,7 @@ class RequestClient {
27
29
  this.verboseMode = false;
28
30
  this.csrfToken = { headerName: '', value: '' };
29
31
  this.isRecoveringFromNetworkError = false;
32
+ this.mockReadiness = (0, mockReadiness_1.captureMockReadiness)();
30
33
  /**
31
34
  * this method returns all requests, an array of SASjsRequest type
32
35
  * @returns SASjsRequest[]
@@ -133,6 +136,8 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
133
136
  };
134
137
  this.handleAxiosError = (error) => {
135
138
  var _a, _b, _c, _d, _e;
139
+ if (error instanceof MockReadinessError_1.MockReadinessError || (error === null || error === void 0 ? void 0 : error.code) === 'ERR_CANCELED')
140
+ throw error;
136
141
  // Message indicating absent value.
137
142
  const noValueMessage = 'Not provided';
138
143
  const { response, request, config } = error;
@@ -604,6 +609,9 @@ ${resHeaders}${parsedResBody ? `\n\n${parsedResBody}` : ''}
604
609
  ? new (require('https').Agent)(httpsAgentOptions)
605
610
  : undefined;
606
611
  this.httpClient = (0, utils_1.createAxiosInstance)(baseUrl, httpsAgent);
612
+ if (this.mockReadiness) {
613
+ (0, mockReadiness_1.installMockReadinessGate)(this.httpClient, this.mockReadiness);
614
+ }
607
615
  this.httpClient.defaults.validateStatus = (status) => {
608
616
  return status >= 200 && status <= 401;
609
617
  };
@@ -0,0 +1,9 @@
1
+ import { AxiosInstance, InternalAxiosRequestConfig } from 'axios';
2
+ interface MockReadiness {
3
+ promise: Promise<unknown>;
4
+ scope: URL;
5
+ }
6
+ export declare const captureMockReadiness: () => MockReadiness | undefined;
7
+ export declare const installMockReadinessGate: (client: AxiosInstance, ready: MockReadiness) => void;
8
+ export declare const waitForMockReadiness: (ready: MockReadiness | undefined, config: InternalAxiosRequestConfig) => Promise<true | undefined>;
9
+ export {};
@@ -0,0 +1,301 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ Object.defineProperty(exports, "__esModule", { value: true });
45
+ exports.waitForMockReadiness = exports.installMockReadinessGate = exports.captureMockReadiness = void 0;
46
+ const axios_1 = __importStar(require("axios"));
47
+ const MockReadinessError_1 = require("../types/errors/MockReadinessError");
48
+ const captureMockReadiness = () => {
49
+ if (typeof window === 'undefined')
50
+ return undefined;
51
+ const ready = window.__sasjsMockReady;
52
+ if (!ready || typeof ready.then !== 'function')
53
+ return undefined;
54
+ const promise = Promise.resolve(ready);
55
+ promise.catch(() => { });
56
+ const boot = Array.from(document.scripts).find((script) => {
57
+ try {
58
+ return new URL(script.src, window.location.href).pathname.endsWith('/host/boot.js');
59
+ }
60
+ catch (_a) {
61
+ return false;
62
+ }
63
+ });
64
+ const scope = boot
65
+ ? new URL('../', boot.src)
66
+ : new URL('/', window.location.href);
67
+ return { promise, scope };
68
+ };
69
+ exports.captureMockReadiness = captureMockReadiness;
70
+ // Native promises cannot unsubscribe reactions. Attach only one reaction per
71
+ // host promise, and keep removable per-request listeners in a separate hub.
72
+ const readinessHubs = new WeakMap();
73
+ const getReadinessHub = (promise) => {
74
+ const existing = readinessHubs.get(promise);
75
+ if (existing)
76
+ return existing;
77
+ const listeners = new Set();
78
+ let outcome;
79
+ const settle = (value, failed) => {
80
+ outcome = { value, failed };
81
+ for (const listener of listeners)
82
+ listener(value, failed);
83
+ listeners.clear();
84
+ };
85
+ const hub = {
86
+ subscribe: (listener) => {
87
+ if (outcome) {
88
+ const settled = outcome;
89
+ Promise.resolve().then(() => listener(settled.value, settled.failed));
90
+ return () => { };
91
+ }
92
+ listeners.add(listener);
93
+ return () => listeners.delete(listener);
94
+ }
95
+ };
96
+ readinessHubs.set(promise, hub);
97
+ promise.then((value) => settle(value, false), (error) => settle(error, true));
98
+ return hub;
99
+ };
100
+ // Install the gate after the user's transforms: a transform may replace the
101
+ // adapter or the URL, and Axios chooses its adapter only after transforming.
102
+ const installMockReadinessGate = (client, ready) => {
103
+ client.interceptors.request.use((config) => {
104
+ // The adapter fallback survives a later interceptor replacing the entire
105
+ // transform list. The final transform below also covers transforms that
106
+ // deliberately select a different adapter.
107
+ let fallback;
108
+ const wrapAdapter = (selected) => {
109
+ if (selected === fallback && fallback)
110
+ return fallback;
111
+ return (dispatched) => {
112
+ const adapter = axios_1.default.getAdapter(selected, dispatched);
113
+ if (!isMockTarget(ready, dispatched))
114
+ return adapter(dispatched);
115
+ const browserTransport = isBrowserTransport(adapter, dispatched);
116
+ if (browserTransport)
117
+ preserveBrowserXsrf(dispatched);
118
+ if (browserTransport &&
119
+ typeof FormData !== 'undefined' &&
120
+ dispatched.data instanceof FormData &&
121
+ typeof dispatched.data.entries === 'function') {
122
+ const snapshot = new FormData();
123
+ for (const [name, value] of dispatched.data.entries()) {
124
+ snapshot.append(name, value);
125
+ }
126
+ dispatched.data = snapshot;
127
+ }
128
+ else if (browserTransport &&
129
+ dispatched.data instanceof ArrayBuffer) {
130
+ dispatched.data = dispatched.data.slice(0);
131
+ }
132
+ return (0, exports.waitForMockReadiness)(ready, dispatched).then(() => {
133
+ var _a, _b;
134
+ (_a = dispatched.cancelToken) === null || _a === void 0 ? void 0 : _a.throwIfRequested();
135
+ if ((_b = dispatched.signal) === null || _b === void 0 ? void 0 : _b.aborted)
136
+ throw new axios_1.CanceledError('canceled', dispatched);
137
+ return adapter(dispatched);
138
+ });
139
+ };
140
+ };
141
+ const selected = config.adapter || client.defaults.adapter || axios_1.default.defaults.adapter;
142
+ fallback = wrapAdapter(selected);
143
+ config.adapter = fallback;
144
+ const transforms = config.transformRequest;
145
+ const original = transforms == null
146
+ ? []
147
+ : Array.isArray(transforms)
148
+ ? transforms
149
+ : [transforms];
150
+ config.transformRequest = [
151
+ ...original,
152
+ function (data) {
153
+ const selected = this.adapter || client.defaults.adapter || axios_1.default.defaults.adapter;
154
+ this.adapter = wrapAdapter(selected);
155
+ return data;
156
+ }
157
+ ];
158
+ return config;
159
+ }, undefined, { synchronous: true });
160
+ };
161
+ exports.installMockReadinessGate = installMockReadinessGate;
162
+ // Resolve the same public Axios adapters rather than guessing from function names.
163
+ const isBrowserTransport = (adapter, config) => {
164
+ for (const name of ['xhr', 'fetch']) {
165
+ try {
166
+ if (axios_1.default.getAdapter(name, config) === adapter)
167
+ return true;
168
+ }
169
+ catch (_a) {
170
+ // An adapter may be unavailable in this environment.
171
+ }
172
+ }
173
+ return false;
174
+ };
175
+ // Axios resolves XSRF at transport time. Freeze its decision only for its own
176
+ // browser transports; a custom adapter must continue to receive unmodified config.
177
+ const preserveBrowserXsrf = (config) => {
178
+ const decision = config.withXSRFToken;
179
+ const { xsrfCookieName, xsrfHeaderName } = config;
180
+ let value;
181
+ if (xsrfCookieName && xsrfHeaderName) {
182
+ const pair = document.cookie
183
+ .split(';')
184
+ .map((part) => part.replace(/^\s+/, ''))
185
+ .find((part) => part.slice(0, part.indexOf('=')) === xsrfCookieName);
186
+ if (pair) {
187
+ value = pair.slice(pair.indexOf('=') + 1);
188
+ try {
189
+ value = decodeURIComponent(value);
190
+ }
191
+ catch (_a) {
192
+ /* Axios accepts malformed encoding verbatim. */
193
+ }
194
+ }
195
+ }
196
+ // Compare actual transport origins, not Axios's location-relative XSRF check:
197
+ // a document <base> can change while the request is waiting.
198
+ const initialOrigin = new URL(axios_1.default.getUri(Object.assign(Object.assign({}, config), { params: null })), document.baseURI).origin;
199
+ const targetChanged = (url) => {
200
+ const origin = new URL(url, document.baseURI).origin;
201
+ return origin !== initialOrigin && origin !== location.origin;
202
+ };
203
+ config.withXSRFToken = (resolved) => {
204
+ // Axios serializes the URL before calling its policy and retains this
205
+ // headers reference if the callback replaces resolved.headers.
206
+ const headers = resolved.headers;
207
+ const result = typeof decision === 'function' ? decision(resolved) : decision;
208
+ const target = new URL(resolved.url || '', location.href);
209
+ if ((result === true ||
210
+ (result == null && target.origin === location.origin)) &&
211
+ value &&
212
+ xsrfHeaderName &&
213
+ !targetChanged(resolved.url || ''))
214
+ headers.set(xsrfHeaderName, value);
215
+ return false;
216
+ };
217
+ };
218
+ const isMockTarget = (ready, config) => {
219
+ if (!ready || typeof window === 'undefined')
220
+ return false;
221
+ // Query serialization belongs to the actual transport, not scope detection.
222
+ const target = new URL(axios_1.default.getUri(Object.assign(Object.assign({}, config), { params: null })), document.baseURI);
223
+ return (target.origin === ready.scope.origin &&
224
+ target.pathname.startsWith(ready.scope.pathname));
225
+ };
226
+ const waitForMockReadiness = (ready, config) => __awaiter(void 0, void 0, void 0, function* () {
227
+ var _a;
228
+ if (!ready || !isMockTarget(ready, config))
229
+ return;
230
+ let result;
231
+ try {
232
+ result = yield new Promise((resolve, reject) => {
233
+ var _a;
234
+ const signal = config.signal;
235
+ const cancelToken = config.cancelToken;
236
+ let unsubscribeReadiness = () => { };
237
+ let finished = false;
238
+ const cleanup = () => {
239
+ var _a;
240
+ finished = true;
241
+ unsubscribeReadiness();
242
+ clearTimeout(timer);
243
+ (_a = signal === null || signal === void 0 ? void 0 : signal.removeEventListener) === null || _a === void 0 ? void 0 : _a.call(signal, 'abort', onAbort);
244
+ cancelToken === null || cancelToken === void 0 ? void 0 : cancelToken.unsubscribe(onCancel);
245
+ };
246
+ const onAbort = () => {
247
+ cleanup();
248
+ reject(new axios_1.CanceledError('canceled', config));
249
+ };
250
+ const onCancel = (reason) => {
251
+ cleanup();
252
+ reject(reason);
253
+ };
254
+ const timeout = typeof config.timeout === 'number' && config.timeout > 0
255
+ ? config.timeout
256
+ : 0;
257
+ const started = Date.now();
258
+ const timer = setTimeout(() => {
259
+ cleanup();
260
+ if (timeout && timeout <= 120000) {
261
+ reject(new MockReadinessError_1.MockReadinessError(`timeout of ${timeout}ms exceeded while waiting for mock initialization`, 'ECONNABORTED'));
262
+ }
263
+ else {
264
+ reject(new MockReadinessError_1.MockReadinessError('Mock initialization timed out'));
265
+ }
266
+ }, timeout ? Math.min(timeout, 120000) : 120000);
267
+ if (signal === null || signal === void 0 ? void 0 : signal.aborted)
268
+ return onAbort();
269
+ (_a = signal === null || signal === void 0 ? void 0 : signal.addEventListener) === null || _a === void 0 ? void 0 : _a.call(signal, 'abort', onAbort);
270
+ cancelToken === null || cancelToken === void 0 ? void 0 : cancelToken.subscribe(onCancel);
271
+ if (finished)
272
+ return;
273
+ unsubscribeReadiness = getReadinessHub(ready.promise).subscribe((value, failed) => {
274
+ if (finished)
275
+ return;
276
+ cleanup();
277
+ if (failed) {
278
+ reject(value);
279
+ }
280
+ else {
281
+ if (timeout)
282
+ config.timeout = Math.max(1, timeout - (Date.now() - started));
283
+ resolve(value);
284
+ }
285
+ });
286
+ });
287
+ }
288
+ catch (error) {
289
+ if (error instanceof axios_1.CanceledError || error instanceof MockReadinessError_1.MockReadinessError)
290
+ throw error;
291
+ throw new MockReadinessError_1.MockReadinessError(`Mock initialization failed: ${String(error)}`);
292
+ }
293
+ if (result && typeof result === 'object') {
294
+ const value = result;
295
+ const failure = value.error || value.driveError || ((_a = value.boot) === null || _a === void 0 ? void 0 : _a.driveError);
296
+ if (failure)
297
+ throw new MockReadinessError_1.MockReadinessError(`Mock initialization failed: ${String(failure)}`);
298
+ }
299
+ return true;
300
+ });
301
+ exports.waitForMockReadiness = waitForMockReadiness;
@@ -0,0 +1,4 @@
1
+ export declare class MockReadinessError extends Error {
2
+ code?: string;
3
+ constructor(message: string, code?: string);
4
+ }
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MockReadinessError = void 0;
4
+ class MockReadinessError extends Error {
5
+ constructor(message, code) {
6
+ super(message);
7
+ this.name = 'MockReadinessError';
8
+ this.code = code;
9
+ Object.setPrototypeOf(this, MockReadinessError.prototype);
10
+ }
11
+ }
12
+ exports.MockReadinessError = MockReadinessError;
@@ -9,6 +9,7 @@ export * from './JobExecutionError';
9
9
  export * from './JobStatePollError';
10
10
  export * from './JsonParseArrayError';
11
11
  export * from './LoginRequiredError';
12
+ export * from './MockReadinessError';
12
13
  export * from './NoSessionStateError';
13
14
  export * from './NotFoundError';
14
15
  export * from './RootFolderNotFoundError';
@@ -25,6 +25,7 @@ __exportStar(require("./JobExecutionError"), exports);
25
25
  __exportStar(require("./JobStatePollError"), exports);
26
26
  __exportStar(require("./JsonParseArrayError"), exports);
27
27
  __exportStar(require("./LoginRequiredError"), exports);
28
+ __exportStar(require("./MockReadinessError"), exports);
28
29
  __exportStar(require("./NoSessionStateError"), exports);
29
30
  __exportStar(require("./NotFoundError"), exports);
30
31
  __exportStar(require("./RootFolderNotFoundError"), exports);
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Collapse repeated slashes in a folder path.
3
+ *
4
+ * A Viya folder path is a sequence of names separated by single slashes, so a run
5
+ * of slashes is always a caller's join going wrong. Two ways of getting one:
6
+ *
7
+ * - joining a parent path with a name, when the parent is the root: `'/' + '/app'`
8
+ * is `'//app'` (adapter#974)
9
+ * - a caller passing a path it built itself, with a trailing slash or a doubled
10
+ * one in the middle: `'/Users/me/' + 'app'`
11
+ *
12
+ * Some deployments do not collapse the doubled slash when it arrives in `?path=`,
13
+ * and answer 404 for a folder that exists, so the path a request carries has to be
14
+ * the path the server knows. This is applied where a path is turned into a request,
15
+ * not only where one is joined, so the invariant holds for every caller.
16
+ */
17
+ export declare const normaliseFolderPath: (folderPath: string) => string;
18
+ /**
19
+ * Join a parent folder path and a folder name into one path.
20
+ *
21
+ * The result is normalised, so a create at the root reads back the same path it
22
+ * wrote - which is the failure adapter#974 describes.
23
+ */
24
+ export declare const joinFolderPath: (parentFolderPath: string, folderName: string) => string;
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.joinFolderPath = exports.normaliseFolderPath = void 0;
4
+ /**
5
+ * Collapse repeated slashes in a folder path.
6
+ *
7
+ * A Viya folder path is a sequence of names separated by single slashes, so a run
8
+ * of slashes is always a caller's join going wrong. Two ways of getting one:
9
+ *
10
+ * - joining a parent path with a name, when the parent is the root: `'/' + '/app'`
11
+ * is `'//app'` (adapter#974)
12
+ * - a caller passing a path it built itself, with a trailing slash or a doubled
13
+ * one in the middle: `'/Users/me/' + 'app'`
14
+ *
15
+ * Some deployments do not collapse the doubled slash when it arrives in `?path=`,
16
+ * and answer 404 for a folder that exists, so the path a request carries has to be
17
+ * the path the server knows. This is applied where a path is turned into a request,
18
+ * not only where one is joined, so the invariant holds for every caller.
19
+ */
20
+ const normaliseFolderPath = (folderPath) => {
21
+ const collapsed = folderPath.replace(/\/{2,}/g, '/');
22
+ // a single trailing slash is the other way a caller's join goes wrong, and it is
23
+ // not a run of slashes: '/app/' names the same folder as '/app', and asking the
24
+ // server about the first is a 404 on a deployment that does not tidy it up
25
+ return collapsed.length > 1 && collapsed.endsWith('/')
26
+ ? collapsed.slice(0, -1)
27
+ : collapsed;
28
+ };
29
+ exports.normaliseFolderPath = normaliseFolderPath;
30
+ /**
31
+ * Join a parent folder path and a folder name into one path.
32
+ *
33
+ * The result is normalised, so a create at the root reads back the same path it
34
+ * wrote - which is the failure adapter#974 describes.
35
+ */
36
+ const joinFolderPath = (parentFolderPath, folderName) => (0, exports.normaliseFolderPath)(`${parentFolderPath}/${folderName}`);
37
+ exports.joinFolderPath = joinFolderPath;