@sasjs/adapter 6.1.8 → 6.2.1

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/README.md CHANGED
@@ -346,6 +346,20 @@ With this approach (`useComputeApi: true`), the requests/logs will _not_ appear
346
346
  }
347
347
  ```
348
348
 
349
+ ## Forced Viya service-pack deployment
350
+
351
+ The ordinary SASjs CLI `deploy` passes force for Viya; `sasjs servicepack deploy` defaults to non-forced, and its `-f` option also forces replacement. A forced `deployServicePack(..., true)` moves **the entire existing `appLoc` folder**, including content not present in the pack, into the deploying user's recycle bin, then creates a new folder and writes the pack. This is not a merge or a single-file update. The adapter API and servicepack CLI accept partial packs: **forcing a partial pack still replaces all of appLoc**, and omitted content remains only in the recycle bin. Check the selected server, appLoc, pack completeness and permissions before running it.
352
+
353
+ Expect downtime between the move and completion. New folders, files and jobs have new identities; links to old IDs may break, and permissions and other folder/resource metadata may not carry over. Verify and reapply permissions as needed. The parent must already exist. Root, top-level shared folders, user homes, ambiguous paths and unsafe member names are rejected; use a dedicated app folder. The deploying account needs permission to read the target and its parent, inspect and write its recycle bin, move the app, and create all pack resources.
354
+
355
+ Forced deployment prevalidates job names to at most 100 Unicode characters, including nested jobs, before moving anything. This conservative limit supports [Viya 3.5](https://developer.sas.com/rest-apis/jobDefinitions/createJobDefinition?cadence=Viya_35), whose job name limit is 100; the newer [Viya job definition API](https://developer.sas.com/rest-apis/jobDefinitions-v4/createJobDefinition/index.md) permits 255. Names between 101 and 255 are therefore rejected even on newer deployments. File names in forced packs must use printable ASCII and cannot contain double quotes, in addition to the general unsafe-name restrictions. Unicode and quoted file names are rejected before any request rather than encoded or renamed: the existing upload sends the name in a quoted HTTP header, and Viya's handling of alternate encodings has not been established. Rename those files and update references before forcing deployment; non-forced uploads are unchanged. A dedicated app under `/Users/<user>/My Folder` is supported, but the personal folder itself cannot be replaced.
356
+
357
+ When a file type requires a metadata patch, forced deployment requires the create response to identify the new file, provide its exact patch URI and a strong ETag; the patch is conditional on that ETag. Missing or unsafe identity or ETag fails the deployment, potentially leaving a partial app. Restricted deployment retries a CSRF denial at most once, only for a fresh CSRF challenge. Forced creation requires the documented HTTP 201 response. Recycle-bin listings before and after the move must include a consistent count, although the API permits count to be omitted. An invalid pre-move listing stops the operation before moving the app; if a later listing omits the count or is otherwise invalid, verification fails after the move and the error identifies the original folder and recycle bin for inspection before retrying.
358
+
359
+ The folder move sends the exact ETag returned by Viya as `If-Match`, accepting nonempty strong or weak tags. On one Viya deployment, the exact weak tag was accepted and a stale weak tag was rejected. This is provider-specific behavior: HTTP normally specifies strong comparison for `If-Match`, so validate behavior on the target Viya deployment. The folder ETag does not guarantee protection of descendants or other cross-resource changes; exclusive control remains essential.
360
+
361
+ The deployment is not transactional and does not automatically roll back. On failure after a move, the error identifies the original folder and recycle bin; the new appLoc may be incomplete. Inspect both locations, remove or move the partial replacement as appropriate, then restore the original folder from the deploying user's recycle bin. If the move response is lost, its outcome is uncertain: inspect by the reported original folder ID before retrying. Keep exclusive control of the appLoc, its parent, and recycle destination for the entire operation; concurrent moves, renames, writes or deployments can invalidate checks. A folder ETag protects the move only to the extent Viya enforces it, not all cross-resource races.
362
+
349
363
  # More resources
350
364
 
351
365
  For more information and examples specific to this adapter you can check out the [user guide](https://sasjs.io/sasjs-adapter/) or the [technical](http://adapter.sasjs.io/) documentation.
@@ -24,6 +24,8 @@ export declare class SASViyaApiClient {
24
24
  private sessionManager;
25
25
  private contextManager;
26
26
  private folderMap;
27
+ private folderMapGeneration;
28
+ invalidateFolderCache(): void;
27
29
  private fileExtensionMap;
28
30
  private boolExtensionMap;
29
31
  /**
@@ -176,6 +178,18 @@ export declare class SASViyaApiClient {
176
178
  * @param accessToken - an access token for authorizing the request.
177
179
  */
178
180
  createFile(fileName: string, contentBuffer: Buffer, parentFolderPath?: string, parentFolderUri?: string, accessToken?: string): Promise<File>;
181
+ /** Recycle exactly the validated app folder; caller must own the scope exclusively. */
182
+ recycleDeploymentFolder(path: string, accessToken?: string): Promise<{
183
+ parentId: any;
184
+ recycled: undefined;
185
+ } | {
186
+ parentId: any;
187
+ recycled: {
188
+ identity: string;
189
+ recycleName: any;
190
+ binId: any;
191
+ };
192
+ }>;
179
193
  /**
180
194
  * Creates a folder. Path to or URI of the parent folder is required.
181
195
  * @param folderName - the name of the new folder.
@@ -198,6 +212,7 @@ export declare class SASViyaApiClient {
198
212
  createJobDefinition(jobName: string, code: string, parentFolderPath?: string, parentFolderUri?: string, accessToken?: string): Promise<{
199
213
  result: Job;
200
214
  etag: string;
215
+ status?: number;
201
216
  }>;
202
217
  /**
203
218
  * Performs a login redirect and returns an auth code for the given client.
@@ -16,6 +16,7 @@ exports.SASViyaApiClient = void 0;
16
16
  const utils_1 = require("./utils");
17
17
  const joinFolderPath_1 = require("./utils/joinFolderPath");
18
18
  const form_data_1 = __importDefault(require("form-data"));
19
+ const isNode_1 = require("./utils/isNode");
19
20
  const errors_1 = require("./types/errors");
20
21
  const SessionManager_1 = require("./SessionManager");
21
22
  const ContextManager_1 = require("./ContextManager");
@@ -29,6 +30,8 @@ const executeOnComputeApi_1 = require("./api/viya/executeOnComputeApi");
29
30
  const getAccessTokenForViya_1 = require("./auth/getAccessTokenForViya");
30
31
  const refreshTokensForViya_1 = require("./auth/refreshTokensForViya");
31
32
  const host_1 = require("./utils/host");
33
+ const NotFoundError_1 = require("./types/errors/NotFoundError");
34
+ const validateForcedServicePack_1 = require("./utils/validateForcedServicePack");
32
35
  /**
33
36
  * A client for interfacing with the SAS Viya REST API.
34
37
  *
@@ -43,11 +46,16 @@ class SASViyaApiClient {
43
46
  this.sessionManager = new SessionManager_1.SessionManager(this.serverUrl, this.contextName, this.requestClient);
44
47
  this.contextManager = new ContextManager_1.ContextManager(this.serverUrl, this.requestClient);
45
48
  this.folderMap = new Map();
49
+ this.folderMapGeneration = 0;
46
50
  this.fileExtensionMap = new Map();
47
51
  this.boolExtensionMap = false; // required in case the map has zero entries
48
52
  if (serverUrl)
49
53
  (0, utils_1.isUrl)(serverUrl);
50
54
  }
55
+ invalidateFolderCache() {
56
+ this.folderMapGeneration++;
57
+ this.folderMap.clear();
58
+ }
51
59
  // after an attempt to populate it.
52
60
  /**
53
61
  * A helper method used to call appendRequest method of RequestClient
@@ -294,7 +302,7 @@ class SASViyaApiClient {
294
302
  */
295
303
  createFile(fileName, contentBuffer, parentFolderPath, parentFolderUri, accessToken) {
296
304
  return __awaiter(this, void 0, void 0, function* () {
297
- var _a;
305
+ var _a, _b, _c, _d, _e, _f;
298
306
  if (!parentFolderPath && !parentFolderUri) {
299
307
  throw new Error('Path or URI of the parent folder is required.');
300
308
  }
@@ -305,8 +313,18 @@ class SASViyaApiClient {
305
313
  Accept: 'application/vnd.sas.file+json',
306
314
  'Content-Disposition': `filename="${fileName}";`
307
315
  };
308
- const formData = new form_data_1.default();
309
- formData.append('file', contentBuffer, fileName);
316
+ const formData = (0, isNode_1.isNode)() ? new form_data_1.default() : new FormData();
317
+ if (!(0, isNode_1.isNode)()) {
318
+ const bytes = typeof contentBuffer === 'string'
319
+ ? contentBuffer
320
+ : new Uint8Array(contentBuffer.buffer, contentBuffer.byteOffset, contentBuffer.byteLength).slice();
321
+ formData.append('file', new Blob([bytes]), fileName);
322
+ }
323
+ else if (ArrayBuffer.isView(contentBuffer)) {
324
+ formData.append('file', Buffer.from(contentBuffer.buffer, contentBuffer.byteOffset, contentBuffer.byteLength), fileName);
325
+ }
326
+ else
327
+ formData.append('file', contentBuffer, fileName);
310
328
  /** Query Viya for file metadata based on extension type. */
311
329
  // typeDefName - Viya accepts this property during the file creation
312
330
  let typeDefName = undefined;
@@ -321,7 +339,15 @@ class SASViyaApiClient {
321
339
  // Populate the file extension map
322
340
  // 1. Get Viya's response to this api call
323
341
  const typesQueryUrl = `/types/types?limit=999999`;
324
- const response = (yield this.requestClient.get(typesQueryUrl, accessToken)).result;
342
+ const typesResult = yield this.requestClient.get(typesQueryUrl, accessToken);
343
+ if (this.requestClient.isDeploymentTransport() &&
344
+ (!typesResult ||
345
+ !Number.isInteger(typesResult.status) ||
346
+ typesResult.status < 200 ||
347
+ typesResult.status >= 300 ||
348
+ !Array.isArray((_b = typesResult.result) === null || _b === void 0 ? void 0 : _b.items)))
349
+ throw new Error('File type registry did not return success');
350
+ const response = typesResult.result;
325
351
  // 2. Filter the returned items that have file extensions into a map
326
352
  // using forEach as an item may relate to multiple file extensions.
327
353
  response.items
@@ -356,18 +382,50 @@ class SASViyaApiClient {
356
382
  }
357
383
  }
358
384
  // Create the file
359
- const createFileResponse = yield this.requestClient.post(`/files/files?parentFolderUri=${parentFolderUri}&typeDefName=${typeDefName !== null && typeDefName !== void 0 ? typeDefName : 'file'}#rawUpload`, formData, accessToken, 'multipart/form-data; boundary=' + formData._boundary, headers);
385
+ const createFileResponse = yield this.requestClient.post(`/files/files?parentFolderUri=${parentFolderUri}&typeDefName=${typeDefName !== null && typeDefName !== void 0 ? typeDefName : 'file'}#rawUpload`, formData, accessToken, (0, isNode_1.isNode)()
386
+ ? 'multipart/form-data; boundary=' + formData.getBoundary()
387
+ : 'multipart/form-data', headers);
388
+ if (!createFileResponse ||
389
+ typeof createFileResponse.status !== 'number' ||
390
+ createFileResponse.status < 200 ||
391
+ createFileResponse.status >= 300 ||
392
+ (this.requestClient.isDeploymentTransport() &&
393
+ createFileResponse.status !== 201))
394
+ throw new Error('File creation did not return success');
360
395
  // If a patch was created...
361
396
  if (filePatch) {
362
397
  try {
398
+ const links = (_d = (_c = createFileResponse.result) === null || _c === void 0 ? void 0 : _c.links) === null || _d === void 0 ? void 0 : _d.filter((e) => e.method == 'PATCH' && e.rel == 'patch');
399
+ let fileUri = (_e = links === null || links === void 0 ? void 0 : links[0]) === null || _e === void 0 ? void 0 : _e.uri;
400
+ if (typeof fileUri !== 'string' || !fileUri)
401
+ throw new Error('Missing file metadata patch link');
363
402
  const patchHeaders = {
364
403
  Accept: 'application/json',
365
404
  'If-Match': '*'
366
405
  };
367
- // Get the URI of the newly created file
368
- const fileUri = createFileResponse.result.links.filter((e) => e.method == 'PATCH' && e.rel == 'patch')[0].uri;
406
+ if (this.requestClient.isDeploymentTransport()) {
407
+ const id = (_f = createFileResponse.result) === null || _f === void 0 ? void 0 : _f.id;
408
+ const etag = createFileResponse.etag;
409
+ if (typeof id !== 'string' ||
410
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(id) ||
411
+ (links === null || links === void 0 ? void 0 : links.length) !== 1 ||
412
+ fileUri !== `/files/files/${id}` ||
413
+ typeof etag !== 'string' ||
414
+ !/^"[\x21\x23-\x7e\x80-\xff]+"$/.test(etag))
415
+ throw new Error('Invalid created file identity, patch link or ETag');
416
+ patchHeaders['If-Match'] = etag;
417
+ fileUri = `/files/files/${id}`;
418
+ }
369
419
  // and apply the patch
370
- return (yield this.requestClient.patch(`${fileUri}`, filePatch, accessToken, patchHeaders)).result;
420
+ const patched = yield this.requestClient.patch(`${fileUri}`, filePatch, accessToken, patchHeaders);
421
+ if (!patched ||
422
+ (this.requestClient.isDeploymentTransport() &&
423
+ (typeof patched.status !== 'number' ||
424
+ !Number.isInteger(patched.status))) ||
425
+ patched.status < 200 ||
426
+ patched.status >= 300)
427
+ throw new Error('File metadata patch did not return success');
428
+ return patched.result;
371
429
  }
372
430
  catch (e) {
373
431
  throw new Error(`Error patching file ${fileName}.\n${e.message}`);
@@ -376,6 +434,175 @@ class SASViyaApiClient {
376
434
  return createFileResponse.result;
377
435
  });
378
436
  }
437
+ /** Recycle exactly the validated app folder; caller must own the scope exclusively. */
438
+ recycleDeploymentFolder(path, accessToken) {
439
+ return __awaiter(this, void 0, void 0, function* () {
440
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
441
+ this.requestClient.restrictDeploymentTransport();
442
+ (0, validateForcedServicePack_1.validateForcedServicePack)(path, { members: [] });
443
+ const requireFolder = (response, expectedName) => {
444
+ if (!response ||
445
+ response.status < 200 ||
446
+ response.status >= 300 ||
447
+ !Number.isInteger(response.status) ||
448
+ !response.result ||
449
+ typeof response.result.id !== 'string' ||
450
+ !uuid.test(response.result.id) ||
451
+ (expectedName !== undefined && response.result.name !== expectedName))
452
+ throw new Error('Invalid folder response during deployment');
453
+ return response.result;
454
+ };
455
+ const parentPath = path.slice(0, path.lastIndexOf('/'));
456
+ const name = path.slice(path.lastIndexOf('/') + 1);
457
+ const lookup = (folderPath) => __awaiter(this, void 0, void 0, function* () {
458
+ try {
459
+ const response = yield this.requestClient.get(`${this.serverUrl}/folders/folders/@item?path=${encodeURIComponent(folderPath)}`, accessToken);
460
+ if (!response)
461
+ throw new Error('No response to folder lookup');
462
+ return response;
463
+ }
464
+ catch (e) {
465
+ if (e instanceof NotFoundError_1.NotFoundError)
466
+ return null;
467
+ throw e;
468
+ }
469
+ });
470
+ const parent = requireFolder(yield lookup(parentPath), parentPath.split('/').pop());
471
+ // Accept the user home and its personal folder as parents, never targets.
472
+ const isUserHome = /^\/users\/[^/]+$/i.test(parentPath);
473
+ const isPersonalFolder = /^\/users\/[^/]+\/my folder$/i.test(parentPath);
474
+ if (parent.type !== 'folder' &&
475
+ !(isUserHome && ['myFolder', 'userFolder'].includes(parent.type)) &&
476
+ !(isPersonalFolder && parent.type === 'myFolder'))
477
+ throw new Error('Cannot safely identify deployment parent folder');
478
+ const existing = yield lookup(path);
479
+ if (existing === null)
480
+ return { parentId: parent.id, recycled: undefined };
481
+ const folder = requireFolder(existing, name);
482
+ if (!existing)
483
+ throw new Error('Invalid folder response during deployment');
484
+ if (folder.id === parent.id ||
485
+ folder.type !== 'folder' ||
486
+ folder.parentFolderUri !== `/folders/folders/${parent.id}` ||
487
+ typeof existing.etag !== 'string' ||
488
+ !/^(W\/)?"[\x21\x23-\x7e\x80-\xff]+"$/.test(existing.etag))
489
+ throw new Error('Cannot safely identify deployment folder');
490
+ const bin = requireFolder(yield this.requestClient.get(`${this.serverUrl}/folders/folders/@myRecycleBin`, accessToken));
491
+ if (bin.type !== 'trashFolder' ||
492
+ bin.id === folder.id ||
493
+ bin.id === parent.id)
494
+ throw new Error('Invalid recycle bin');
495
+ // A UUID keeps the destination name bounded even for long app names.
496
+ const recycleName = folder.id;
497
+ const url = `${this.serverUrl}/folders/folders/${bin.id}/members?limit=100&start=`;
498
+ const requireEmptyNextPage = (start, total) => __awaiter(this, void 0, void 0, function* () {
499
+ var _a;
500
+ const page = yield this.requestClient.get(url + start, accessToken);
501
+ if (!Number.isInteger(page === null || page === void 0 ? void 0 : page.status) ||
502
+ page.status < 200 ||
503
+ page.status >= 300 ||
504
+ !Array.isArray((_a = page.result) === null || _a === void 0 ? void 0 : _a.items) ||
505
+ page.result.items.length !== 0 ||
506
+ page.result.count !== total)
507
+ throw new Error('Ambiguous recycle bin listing count');
508
+ });
509
+ let start = 0;
510
+ let total;
511
+ do {
512
+ const page = yield this.requestClient.get(url + start, accessToken);
513
+ if (!page ||
514
+ page.status < 200 ||
515
+ page.status >= 300 ||
516
+ !Number.isInteger(page.status) ||
517
+ !page.result ||
518
+ !Array.isArray(page.result.items) ||
519
+ !Number.isSafeInteger(page.result.count) ||
520
+ page.result.count < 0 ||
521
+ (total !== undefined && page.result.count !== total) ||
522
+ page.result.items.length > 100 ||
523
+ start + page.result.items.length > page.result.count)
524
+ throw new Error('Invalid recycle bin listing');
525
+ total = page.result.count;
526
+ if (page.result.items.some((item) => !item ||
527
+ typeof item.name !== 'string' ||
528
+ typeof item.uri !== 'string' ||
529
+ item.name.toLowerCase() === recycleName.toLowerCase() ||
530
+ item.uri === `/folders/folders/${folder.id}`))
531
+ throw new Error('Recycle destination collision or invalid member');
532
+ if (!page.result.items.length && start < total)
533
+ throw new Error('Incomplete recycle bin listing');
534
+ start += page.result.items.length;
535
+ // A full terminal page cannot prove that there are no further members.
536
+ if (start === total && page.result.items.length === 100)
537
+ yield requireEmptyNextPage(start, total);
538
+ } while (start < total);
539
+ const identity = `/folders/folders/${folder.id}`;
540
+ try {
541
+ // PUT replaces the folder; retain all writable fields from the GET.
542
+ const moved = yield this.requestClient.put(`${this.serverUrl}${identity}`, Object.assign(Object.assign(Object.assign({ name: recycleName, type: folder.type }, (folder.description !== undefined && {
543
+ description: folder.description
544
+ })), (folder.version !== undefined && { version: folder.version })), { parentFolderUri: `/folders/folders/${bin.id}` }), accessToken, { 'If-Match': existing.etag });
545
+ requireFolder(moved);
546
+ if (moved.result.id !== folder.id ||
547
+ moved.result.name !== recycleName ||
548
+ moved.result.type !== 'folder' ||
549
+ moved.result.parentFolderUri !== `/folders/folders/${bin.id}`)
550
+ throw new Error('Moved folder identity mismatch');
551
+ }
552
+ catch (e) {
553
+ throw new Error(`Recycle move failed or outcome unknown for ${path}; inspect recycle bin /folders/folders/${bin.id} for ${identity} as '${recycleName}' before retrying. ${e instanceof Error ? e.message : ''}`);
554
+ }
555
+ try {
556
+ const confirmed = yield lookup(path);
557
+ if (confirmed !== null)
558
+ throw new Error('Original path is still occupied');
559
+ let position = 0;
560
+ let expected;
561
+ let matches = 0;
562
+ do {
563
+ const page = yield this.requestClient.get(url + position, accessToken);
564
+ const data = page === null || page === void 0 ? void 0 : page.result;
565
+ if (!page ||
566
+ !Number.isInteger(page.status) ||
567
+ page.status < 200 ||
568
+ page.status >= 300 ||
569
+ !data ||
570
+ !Array.isArray(data.items) ||
571
+ !Number.isSafeInteger(data.count) ||
572
+ data.count < 0 ||
573
+ (expected !== undefined && data.count !== expected) ||
574
+ data.items.length > 100 ||
575
+ position + data.items.length > data.count ||
576
+ (!data.items.length && position < data.count))
577
+ throw new Error('Invalid recycle listing after move');
578
+ expected = data.count;
579
+ for (const item of data.items) {
580
+ if (!item ||
581
+ typeof item.name !== 'string' ||
582
+ typeof item.uri !== 'string')
583
+ throw new Error('Invalid recycle member after move');
584
+ if (item.uri === identity && item.name === recycleName)
585
+ matches++;
586
+ else if (item.uri === identity ||
587
+ item.name.toLowerCase() === recycleName.toLowerCase())
588
+ throw new Error('Ambiguous recycle member after move');
589
+ }
590
+ position += data.items.length;
591
+ if (position === expected && data.items.length === 100)
592
+ yield requireEmptyNextPage(position, expected);
593
+ } while (position < expected);
594
+ if (matches !== 1)
595
+ throw new Error('Moved folder not found in recycle bin');
596
+ }
597
+ catch (e) {
598
+ throw new Error(`Recycle move outcome could not be verified for ${path}; inspect ${identity} in recycle bin ${bin.id} before retrying. ${e instanceof Error ? e.message : ''}`);
599
+ }
600
+ return {
601
+ parentId: parent.id,
602
+ recycled: { identity, recycleName, binId: bin.id }
603
+ };
604
+ });
605
+ }
379
606
  /**
380
607
  * Creates a folder. Path to or URI of the parent folder is required.
381
608
  * @param folderName - the name of the new folder.
@@ -406,15 +633,15 @@ class SASViyaApiClient {
406
633
  logger.info(`Parent folder '${newFolderName}' has been successfully created.`);
407
634
  parentFolderUri = `/folders/folders/${parentFolder.id}`;
408
635
  }
409
- else if (isForced) {
410
- const folderPath = (0, joinFolderPath_1.joinFolderPath)(parentFolderPath, folderName);
411
- const folderUri = yield this.getFolderUri(folderPath, accessToken);
412
- if (folderUri) {
413
- yield this.deleteFolder(folderPath, accessToken);
414
- }
415
- }
416
636
  }
417
- const { result: createFolderResponse } = yield this.requestClient
637
+ // Resolve the child by path even when the caller supplied its parent URI.
638
+ if (isForced && parentFolderPath) {
639
+ const folderPath = (0, joinFolderPath_1.joinFolderPath)(parentFolderPath, folderName);
640
+ const folderUri = yield this.getFolderUri(folderPath, accessToken);
641
+ if (folderUri)
642
+ yield this.deleteFolder(folderPath, accessToken);
643
+ }
644
+ const createResponse = yield this.requestClient
418
645
  .post(`/folders/folders?parentFolderUri=${parentFolderUri}`, {
419
646
  name: folderName,
420
647
  type: 'folder'
@@ -433,6 +660,16 @@ class SASViyaApiClient {
433
660
  }
434
661
  throw err;
435
662
  });
663
+ if (!createResponse ||
664
+ typeof createResponse.status !== 'number' ||
665
+ createResponse.status < 200 ||
666
+ createResponse.status >= 300 ||
667
+ (this.requestClient.isDeploymentTransport() &&
668
+ createResponse.status !== 201) ||
669
+ !createResponse.result ||
670
+ !createResponse.result.id)
671
+ throw new Error('Folder creation did not return success');
672
+ const createFolderResponse = createResponse.result;
436
673
  // The POST answered with the folder it created, so there is nothing to look up:
437
674
  // a new folder has no members, and re-reading it by a path joined here by hand
438
675
  // is how the doubled slash in adapter#974 reached the server.
@@ -742,6 +979,7 @@ class SASViyaApiClient {
742
979
  if (this.folderMap.get(path)) {
743
980
  return;
744
981
  }
982
+ const generation = this.folderMapGeneration;
745
983
  const url = '/folders/folders/@item?path=' + path;
746
984
  const { result: folder } = yield this.requestClient
747
985
  .get(`${url}`, accessToken)
@@ -758,6 +996,9 @@ class SASViyaApiClient {
758
996
  throw (0, error_1.prefixMessage)(err, 'Error while getting members. ');
759
997
  });
760
998
  const itemsAtRoot = members.items;
999
+ if (generation !== this.folderMapGeneration) {
1000
+ return this.populateFolderMap(path, accessToken);
1001
+ }
761
1002
  this.folderMap.set(path, itemsAtRoot);
762
1003
  });
763
1004
  }
package/SASjs.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { SASjsConfig, UploadFile, EditContextInput, PollOptions, VerboseMode, LoginOptions, LoginResult, ExecutionQuery, Tables } from './types';
1
+ import { SASjsConfig, UploadFile, EditContextInput, PollOptions, VerboseMode, LoginOptions, LoginResult, ExecutionQuery, Tables, DeployProgress } from './types';
2
2
  import { SASViyaApiClient } from './SASViyaApiClient';
3
3
  import { SASjsAuthResponse } from './SASjsApiClient';
4
4
  import { OnTokensRefreshed } from './auth/getTokens';
@@ -213,6 +213,7 @@ export default class SASjs {
213
213
  createJobDefinition(jobName: string, code: string, parentFolderPath?: string, parentFolderUri?: string, accessToken?: string, sasApiClient?: SASViyaApiClient): Promise<{
214
214
  result: import("./types").Job;
215
215
  etag: string;
216
+ status?: number;
216
217
  }>;
217
218
  getAuthCode(clientId: string): Promise<string | null>;
218
219
  /**
@@ -360,9 +361,10 @@ export default class SASjs {
360
361
  * If not provided, is taken from SASjsConfig.
361
362
  * @param accessToken - an optional access token to be passed in when
362
363
  * using this function from the command line.
363
- * @param isForced - flag that indicates if target folder already exists, it and all subfolders have to be deleted.
364
+ * @param isForced - move the entire existing appLoc to the recycle bin before deploying (including content omitted from this pack); defaults to false. Requires exclusive control of appLoc, its parent and recycle bin. A failure may leave an incomplete app; see README for recovery.
365
+ * @param onProgress - called immediately before each pack member is written, with its name, folder, type and 1-based position.
364
366
  */
365
- deployServicePack(serviceJson: any, appLoc?: string, serverUrl?: string, accessToken?: string, isForced?: boolean): Promise<void>;
367
+ deployServicePack(serviceJson: any, appLoc?: string, serverUrl?: string, accessToken?: string, isForced?: boolean, onProgress?: (progress: DeployProgress) => void): Promise<void>;
366
368
  /**
367
369
  * Kicks off execution of the given job via the compute API.
368
370
  * @returns an object representing the compute session created for the given job.
package/SASjs.js CHANGED
@@ -20,6 +20,7 @@ const types_2 = require("@sasjs/utils/types");
20
20
  const RequestClient_1 = require("./request/RequestClient");
21
21
  const SasjsRequestClient_1 = require("./request/SasjsRequestClient");
22
22
  const job_execution_1 = require("./job-execution");
23
+ const validateForcedServicePack_1 = require("./utils/validateForcedServicePack");
23
24
  const defaultConfig = {
24
25
  serverUrl: '',
25
26
  // The one name the adapter needs for SASjs Server: the mount its routes sit
@@ -614,19 +615,23 @@ class SASjs {
614
615
  * If not provided, is taken from SASjsConfig.
615
616
  * @param accessToken - an optional access token to be passed in when
616
617
  * using this function from the command line.
617
- * @param isForced - flag that indicates if target folder already exists, it and all subfolders have to be deleted.
618
+ * @param isForced - move the entire existing appLoc to the recycle bin before deploying (including content omitted from this pack); defaults to false. Requires exclusive control of appLoc, its parent and recycle bin. A failure may leave an incomplete app; see README for recovery.
619
+ * @param onProgress - called immediately before each pack member is written, with its name, folder, type and 1-based position.
618
620
  */
619
621
  deployServicePack(serviceJson_1, appLoc_1, serverUrl_1, accessToken_1) {
620
- return __awaiter(this, arguments, void 0, function* (serviceJson, appLoc, serverUrl, accessToken, isForced = false) {
622
+ return __awaiter(this, arguments, void 0, function* (serviceJson, appLoc, serverUrl, accessToken, isForced = false, onProgress) {
623
+ var _a, _b, _c;
621
624
  this.isMethodSupported('deployServicePack', [types_2.ServerType.SasViya]);
622
625
  let sasApiClient = null;
623
- if (serverUrl || appLoc) {
624
- if (!serverUrl)
626
+ if (serverUrl !== undefined || appLoc !== undefined) {
627
+ if (serverUrl === undefined)
625
628
  serverUrl = this.sasjsConfig.serverUrl;
626
- if (!appLoc)
629
+ if (appLoc === undefined)
627
630
  appLoc = this.sasjsConfig.appLoc;
628
631
  if (this.sasjsConfig.serverType === types_2.ServerType.SasViya) {
629
- sasApiClient = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, this.requestClient);
632
+ sasApiClient = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, serverUrl === this.sasjsConfig.serverUrl
633
+ ? this.requestClient
634
+ : new RequestClient_1.RequestClient(serverUrl, this.sasjsConfig.httpsAgentOptions));
630
635
  sasApiClient.debug = this.sasjsConfig.debug;
631
636
  }
632
637
  else if (this.sasjsConfig.serverType === types_2.ServerType.Sas9) {
@@ -644,12 +649,67 @@ class SASjs {
644
649
  serverUrl = sasClientConfig.serverUrl;
645
650
  appLoc = sasClientConfig.rootFolderName;
646
651
  }
652
+ const safeServer = (() => {
653
+ try {
654
+ const origin = new URL(serverUrl || (typeof location !== 'undefined' ? location.href : ''));
655
+ return ((origin.protocol === 'https:' || origin.protocol === 'http:') &&
656
+ !origin.username &&
657
+ !origin.password &&
658
+ !origin.search &&
659
+ !origin.hash);
660
+ }
661
+ catch (_a) {
662
+ return false;
663
+ }
664
+ })();
665
+ if (isForced && !safeServer)
666
+ throw new Error('Invalid deployment server URL');
667
+ if (isForced) {
668
+ (0, validateForcedServicePack_1.validateForcedServicePack)(appLoc, serviceJson);
669
+ const deploymentClient = new RequestClient_1.RequestClient(serverUrl, this.sasjsConfig.httpsAgentOptions);
670
+ if (serverUrl === this.sasjsConfig.serverUrl)
671
+ deploymentClient.copyCsrfFrom(this.requestClient);
672
+ deploymentClient.restrictDeploymentTransport();
673
+ const api = new SASViyaApiClient_1.SASViyaApiClient(serverUrl, appLoc, this.sasjsConfig.contextName, deploymentClient);
674
+ (_a = this.sasViyaApiClient) === null || _a === void 0 ? void 0 : _a.invalidateFolderCache();
675
+ try {
676
+ const { parentId, recycled } = yield api.recycleDeploymentFolder(appLoc, accessToken);
677
+ try {
678
+ const parent = appLoc.slice(0, appLoc.lastIndexOf('/'));
679
+ const name = appLoc.slice(appLoc.lastIndexOf('/') + 1);
680
+ const root = yield api.createFolder(name, parent, `/folders/folders/${parentId}`, accessToken, false);
681
+ if (!root ||
682
+ root.name !== name ||
683
+ root.parentFolderUri !== `/folders/folders/${parentId}` ||
684
+ root.type !== 'folder' ||
685
+ typeof root.id !== 'string' ||
686
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(root.id))
687
+ throw new Error('Invalid created app folder identity');
688
+ yield this.createFoldersAndServices(appLoc, serviceJson.members, accessToken, api, false, {
689
+ onProgress,
690
+ index: 0,
691
+ total: countMembers(serviceJson.members),
692
+ strict: true
693
+ }, `/folders/folders/${root.id}`);
694
+ }
695
+ catch (e) {
696
+ const recovery = recycled
697
+ ? `Original folder ${recycled.identity} is in recycle bin ${recycled.binId} as '${recycled.recycleName}'.`
698
+ : 'No prior folder was recycled.';
699
+ throw new Error(`Deployment may be partial at ${appLoc}. ${recovery} ${e instanceof Error ? e.message : String(e)}`);
700
+ }
701
+ }
702
+ finally {
703
+ (_b = this.sasViyaApiClient) === null || _b === void 0 ? void 0 : _b.invalidateFolderCache();
704
+ }
705
+ return;
706
+ }
647
707
  // members of type 'folder' should be processed first
648
- if (serviceJson.members[0].members) {
708
+ if ((_c = serviceJson.members[0]) === null || _c === void 0 ? void 0 : _c.members) {
649
709
  serviceJson.members[0].members.sort((member) => member.type === 'folder' ? -1 : 1);
650
710
  }
651
711
  const members = serviceJson.members;
652
- yield this.createFoldersAndServices(appLoc, members, accessToken, sasApiClient, isForced);
712
+ yield this.createFoldersAndServices(appLoc, members, accessToken, sasApiClient, isForced, { onProgress, index: 0, total: countMembers(members), strict: false });
653
713
  });
654
714
  }
655
715
  /**
@@ -797,24 +857,46 @@ class SASjs {
797
857
  this.computeJobExecutor = new job_execution_1.ComputeJobExecutor(this.sasjsConfig.serverUrl, this.sasViyaApiClient);
798
858
  this.jesJobExecutor = new job_execution_1.JesJobExecutor(this.sasjsConfig.serverUrl, this.sasViyaApiClient);
799
859
  }
800
- createFoldersAndServices(parentFolder, membersJson, accessToken, sasApiClient, isForced) {
801
- return __awaiter(this, void 0, void 0, function* () {
860
+ createFoldersAndServices(parentFolder_1, membersJson_1, accessToken_1, sasApiClient_1, isForced_1) {
861
+ return __awaiter(this, arguments, void 0, function* (parentFolder, membersJson, accessToken, sasApiClient, isForced, progress = {
862
+ index: 0,
863
+ total: countMembers(membersJson),
864
+ strict: false
865
+ }, parentFolderUri) {
802
866
  yield (0, utils_1.asyncForEach)(membersJson, (member) => __awaiter(this, void 0, void 0, function* () {
867
+ let childUri;
803
868
  switch (member.type) {
804
- case 'folder':
805
- yield this.createFolder(member.name, parentFolder, undefined, accessToken, sasApiClient, isForced);
869
+ case 'folder': {
870
+ reportMember(progress, 'folder', member.name, parentFolder);
871
+ const folder = yield this.createFolder(member.name, parentFolder, parentFolderUri, accessToken, sasApiClient, isForced);
872
+ if (progress.strict) {
873
+ if (!folder ||
874
+ folder.name !== member.name ||
875
+ folder.parentFolderUri !== parentFolderUri ||
876
+ folder.type !== 'folder' ||
877
+ typeof folder.id !== 'string' ||
878
+ !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(folder.id))
879
+ throw new Error('Invalid created folder identity');
880
+ }
881
+ childUri = (folder === null || folder === void 0 ? void 0 : folder.id) ? `/folders/folders/${folder.id}` : undefined;
806
882
  break;
883
+ }
807
884
  case 'file':
808
- yield this.createFile(member.name, member.code, parentFolder, undefined, accessToken, sasApiClient);
885
+ reportMember(progress, 'file', member.name, parentFolder);
886
+ yield this.createFile(member.name, member.code, parentFolder, parentFolderUri, accessToken, sasApiClient);
809
887
  break;
810
- case 'service':
811
- yield this.createJobDefinition(member.name, member.code, parentFolder, undefined, accessToken, sasApiClient);
888
+ case 'service': {
889
+ reportMember(progress, 'service', member.name, parentFolder);
890
+ const response = yield this.createJobDefinition(member.name, member.code, parentFolder, parentFolderUri, accessToken, sasApiClient);
891
+ if (progress.strict && (!response || response.status !== 201))
892
+ throw new Error('Job definition creation did not return success');
812
893
  break;
894
+ }
813
895
  default:
814
896
  throw new Error(`Unidentified member '${member.name}' provided.`);
815
897
  }
816
898
  if (member.type === 'folder' && member.members && member.members.length)
817
- yield this.createFoldersAndServices(`${parentFolder}/${member.name}`, member.members, accessToken, sasApiClient, isForced);
899
+ yield this.createFoldersAndServices(`${parentFolder}/${member.name}`, member.members, accessToken, sasApiClient, isForced, progress, childUri);
818
900
  }));
819
901
  });
820
902
  }
@@ -852,3 +934,28 @@ class SASjs {
852
934
  }
853
935
  }
854
936
  exports.default = SASjs;
937
+ /**
938
+ * Counts every member of a service pack, at every depth.
939
+ *
940
+ * Folders are counted as well as their children, because the deploy writes the
941
+ * folder itself before recursing - one `onProgress` call per member, so the
942
+ * total is exactly the number of calls the deploy will make.
943
+ */
944
+ const countMembers = (members = []) => members.reduce((count, member) => count + 1 + (member.members ? countMembers(member.members) : 0), 0);
945
+ /**
946
+ * Reports one member immediately before it is written.
947
+ *
948
+ * Emitted per case rather than before the switch so an unidentified member
949
+ * throws without first announcing a write that will not happen.
950
+ */
951
+ const reportMember = (progress, type, name, parentFolder) => {
952
+ var _a;
953
+ const index = ++progress.index;
954
+ (_a = progress.onProgress) === null || _a === void 0 ? void 0 : _a.call(progress, {
955
+ type,
956
+ name,
957
+ parentFolder,
958
+ index,
959
+ total: progress.total
960
+ });
961
+ };