@sasjs/api 0.51.0 → 0.52.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/README.md CHANGED
@@ -33,10 +33,16 @@ Both lists are held against their inventory in both directions by `spec/viyaAppS
33
33
  `check:app-scope` is not a CI step: it needs a checkout of the application, so it runs where that checkout exists and states so when it is not given one.
34
34
  The operations an application's calls add are declared rather than captured (`src/viya/declared.ts`), since no recording pass driven by the adapter can observe them.
35
35
 
36
+ **Viya job definitions.** Create and read store inert JSON records in the parent Drive folder and expose a `getResource` member link. A host that persists Drive data can reconstruct the definitions; IDs are newly minted UUIDs and follow a parent folder move. These records are ordinary Drive files, subject to the host's existing Drive permissions and modification/removal. Creation fails with 501 by default: the Drive operations are not transactional. For an isolated mock only, a trusted host can set `services.viya.allowUntransactionalJobDefinitionCreation: true` in host configuration, never from HTTP input. The host must guarantee that no Drive mutations overlap any definition create, across all processes and all users of the underlying store (including other definition creates, folder moves and deletes). This opt-in does not enforce exclusivity or resolve the races; do not enable it in shared or parallel environments. Robust concurrency requires transactional mutation support. Existing definitions remain readable with creation disabled. This slice does not execute jobs or implement update, delete, overwrite or duplicate-name concurrency guarantees; it does not claim Viya parity for those behaviours. Existing folder IDs remain path-derived. Do not treat definition data as executable code.
37
+
38
+ **Viya folder-member authorization.** On each member request, a trusted host must set `services.viya.readJobDefinitionMetadata` to `false` unless it has independently authorized this caller to read definition files; never derive this capability from the query or body. When false, member discovery does not read file contents and hides every reserved `.sasjs-viya-job-<UUID-v4>.json` filename, including malformed records. Other files and folders remain visible. When true or omitted, historical discovery reads and exposes valid definitions, and malformed records remain ordinary files. Omission is for trusted existing/browser hosts only: multi-user hosts must set the flag per request. This flag only controls folder-member discovery, not direct definition or Drive endpoints; the host must authorize those independently. Folder ID lookup walks Drive folder listings, exposing the same recursive names available under the native folder-list grant, without file content reads or per-file stats.
39
+
36
40
  **Viya job log collection.** The CLI follows a job's `log` link and pages the returned line objects. The emulator supports non-negative decimal `start` and `limit` (default 0 and 10; maximum limit 2147483647, maximum start JavaScript's safe integer), with `count` equal to the total stored lines. Malformed or repeated values are refused with 400; `type` filtering and `timeout` are not implemented and are refused. Every stored string is labelled `NOTE`, without classifying its content; `/log/content` retains its existing behavior. Defaults, validation, link details and line types are mock choices, not verified Viya behavior. A successful collection read is not evidence of SAS execution; its lines come from the configured host or the mock generator.
37
41
 
38
42
  **Viya mock SYSJOBID.** By default every session-variable lookup retains the 501 refusal. A trusted host may set `services.viya.mockSysjobid: true` in host configuration, never from HTTP data, to enable only the exact case-sensitive name `SYSJOBID` after normal subject, estate and session ownership checks. The value is `mock-<session UUID>`, stable only for that mock session and unmistakably synthetic: it is not a process ID, a SAS value or evidence of execution. The adapter's `printPid` nevertheless labels it `PID`; do not interpret it as a real one. Unknown variables remain 501 for an authorized live session; foreign, missing, deleted or ownerless sessions return 404, and unresolved credentials return 401. No subject and no token is the shared anonymous mock identity described below, not authentication. The [SAS getVariable documentation](https://developer.sas.com/rest-apis/compute/getVariable/index.md) specifies name, value, scope and representation version 1; the committed capture records link field types, not their values. `AUTOMATIC` and the single self link and its media type are mock-specific choices, not observed Viya values. The dispatch request carries no Accept header: this mock only returns a JSON-shaped resource and does not implement or negotiate SAS's documented `text/plain` or other Accept representations. Hosts must not enable it for clients relying on content negotiation.
39
43
 
44
+ **Viya mock compute context.** The list and detail expose one context, `SASjs Mock context`. Configure `contextName: 'SASjs Mock context'` when constructing a SASjs adapter for this mock: the adapter's own default remains `SAS Job Execution compute context` and does not match. Filtered name lookups return an empty collection for other names, not a synthesized context. The emulator supports only `eq(name,"...")` and `eq(name,'...')` with literal unescaped values, and case-sensitive matching; other filters and `sortBy` return 400 rather than silently being ignored. It supports non-negative integer `start` and `limit` (defaults 0 and 10); repeated or non-string values for `filter`, `start`, or `limit` return 400, and any supplied `sortBy` returns 400. `count` is the total matching collection size before pagination. This is a bounded mock contract, not a claim that these are the only valid Viya requests or that Viya uses the same error responses. The emulator does not execute SAS or provide a reusable batch identity.
45
+
40
46
  **Viya compute ownership.** A multi-user host must authenticate its caller and pass the resolved `subject` to `dispatchViya` on every compute session request. Set `subject.ownerId` to the immutable account ID from the host's identity store, never from request data. `subject.userId` still controls the username on the wire. Hosts that omit `ownerId` use `userId` as before, in a separate namespace; switching an existing host to stable IDs requires recreating any live username-scoped sessions. Ownership spans client IDs, and another owner gets the same 404 as for a missing session. Ownerless records are refused. A token without a resolved subject is refused; no subject and no token selects a shared anonymous browser mock, not an authentication boundary. Session stores are keyed by the full normalised `serverUrl`, not the 32-bit seed.
41
47
 
42
48
  **Viya mock job submissions.** After resolving the session owner, the mock accepts an omitted request body or an object whose optional `code` is a string or an array of strings (including empty strings and arrays); omitted `code` becomes an empty string. Explicit null, non-object or array bodies, a null or non-string/non-array `code`, and arrays with non-string or sparse elements return 400 before job allocation, generated logging or executor invocation. This is a mock safety contract, not a verified Viya validation response. Valid code is still handed to any trusted host-configured executor, so hosts must enforce their own execution policy; the emulator alone does not execute SAS.
package/build/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- /* @sasjs/api 0.51.0 - the SASjs Server API, for a service worker. https://github.com/sasjs/api */
1
+ /* @sasjs/api 0.52.0 - the SASjs Server API, for a service worker. https://github.com/sasjs/api */
2
2
  "use strict";
3
3
  var SASjsApi = (() => {
4
4
  var __defProp = Object.defineProperty;
@@ -1049,17 +1049,17 @@ var SASjsApi = (() => {
1049
1049
  }
1050
1050
  }
1051
1051
  children(path) {
1052
- const prefix = path === "/" ? "/" : path + "/";
1052
+ const prefix2 = path === "/" ? "/" : path + "/";
1053
1053
  const files = [];
1054
1054
  const folders = [];
1055
1055
  for (const candidate of this.files.keys()) {
1056
- if (!candidate.startsWith(prefix)) continue;
1057
- const rest = candidate.slice(prefix.length);
1056
+ if (!candidate.startsWith(prefix2)) continue;
1057
+ const rest = candidate.slice(prefix2.length);
1058
1058
  if (rest && !rest.includes("/")) files.push(rest);
1059
1059
  }
1060
1060
  for (const candidate of this.folders) {
1061
- if (!candidate.startsWith(prefix)) continue;
1062
- const rest = candidate.slice(prefix.length);
1061
+ if (!candidate.startsWith(prefix2)) continue;
1062
+ const rest = candidate.slice(prefix2.length);
1063
1063
  if (rest && !rest.includes("/")) folders.push(rest);
1064
1064
  }
1065
1065
  return { files: files.sort(), folders: folders.sort() };
@@ -1095,12 +1095,12 @@ var SASjsApi = (() => {
1095
1095
  }
1096
1096
  async remove(path) {
1097
1097
  if (this.files.delete(path)) return;
1098
- const prefix = path === "/" ? "/" : path + "/";
1098
+ const prefix2 = path === "/" ? "/" : path + "/";
1099
1099
  for (const candidate of [...this.files.keys()]) {
1100
- if (candidate.startsWith(prefix)) this.files.delete(candidate);
1100
+ if (candidate.startsWith(prefix2)) this.files.delete(candidate);
1101
1101
  }
1102
1102
  for (const candidate of [...this.folders]) {
1103
- if (candidate === path || candidate.startsWith(prefix))
1103
+ if (candidate === path || candidate.startsWith(prefix2))
1104
1104
  this.folders.delete(candidate);
1105
1105
  }
1106
1106
  }
@@ -1113,10 +1113,10 @@ var SASjsApi = (() => {
1113
1113
  this.files.set(to, copy);
1114
1114
  return;
1115
1115
  }
1116
- const prefix = from + "/";
1116
+ const prefix2 = from + "/";
1117
1117
  const moves = [];
1118
1118
  for (const [candidate, value] of this.files) {
1119
- if (candidate.startsWith(prefix))
1119
+ if (candidate.startsWith(prefix2))
1120
1120
  moves.push([candidate, to + candidate.slice(from.length), value]);
1121
1121
  }
1122
1122
  for (const [source] of moves) this.files.delete(source);
@@ -1125,7 +1125,7 @@ var SASjsApi = (() => {
1125
1125
  this.files.set(destination, value);
1126
1126
  }
1127
1127
  for (const candidate of [...this.folders]) {
1128
- if (candidate === from || candidate.startsWith(prefix)) {
1128
+ if (candidate === from || candidate.startsWith(prefix2)) {
1129
1129
  this.folders.delete(candidate);
1130
1130
  this.folders.add(to + candidate.slice(from.length));
1131
1131
  }
@@ -3787,14 +3787,14 @@ var SASjsApi = (() => {
3787
3787
  var compiled = ROUTES.filter((route) => route.path.includes("{")).map(
3788
3788
  (route) => {
3789
3789
  const keys = [];
3790
- const pattern = route.path.split("/").map((segment) => {
3790
+ const pattern2 = route.path.split("/").map((segment) => {
3791
3791
  if (segment.startsWith("{") && segment.endsWith("}")) {
3792
3792
  keys.push(segment.slice(1, -1));
3793
3793
  return "([^/]+)";
3794
3794
  }
3795
3795
  return escape(segment);
3796
3796
  }).join("/");
3797
- return { route, keys, regex: new RegExp("^" + pattern + "/?$", "i") };
3797
+ return { route, keys, regex: new RegExp("^" + pattern2 + "/?$", "i") };
3798
3798
  }
3799
3799
  );
3800
3800
  var exact = /* @__PURE__ */ new Map();
@@ -5533,7 +5533,7 @@ var SASjsApi = (() => {
5533
5533
 
5534
5534
  // src/viya/overlay.ts
5535
5535
  var NEEDS_AUTH = "The token endpoint is answered by the host that mounts the emulator, which owns the token port.";
5536
- var NEEDS_JOBS = "The emulator answers the compute and content families; the job definitions a deploy creates and the executions a run submits are not modelled yet.";
5536
+ var NEEDS_JOBS = "The emulator stores job definitions but does not model job executions.";
5537
5537
  var SESSION_VARIABLE_REFUSAL = "GET /compute/sessions/{}/variables/{} is not emulated. The emulator does not model session variables; the client reads these only to log the pid of a job it is about to submit (SYSJOBID), and any name it asks for is refused here rather than answered with a value the emulator did not run.";
5538
5538
  var VIYA_OVERLAY = {
5539
5539
  // answered here
@@ -5571,19 +5571,9 @@ var SASjsApi = (() => {
5571
5571
  "PATCH /files/files/{}": { implemented: true },
5572
5572
  "GET /files/files/{}/content": { implemented: true },
5573
5573
  "PUT /files/files/{}/content": { implemented: true },
5574
- // declined: the job family needs a job service
5575
- //
5576
- // A capture describes what the estate answers on the deploy-and-run path, and
5577
- // the emulator does not answer that path yet: a client that deploys a service
5578
- // pack against an emulated estate stops here, with a reason rather than a 404.
5579
- "POST /jobDefinitions/definitions": {
5580
- implemented: false,
5581
- reason: NEEDS_JOBS
5582
- },
5583
- "GET /jobDefinitions/definitions/{}": {
5584
- implemented: false,
5585
- reason: NEEDS_JOBS
5586
- },
5574
+ // Definition persistence does not implement job execution.
5575
+ "POST /jobDefinitions/definitions": { implemented: true },
5576
+ "GET /jobDefinitions/definitions/{}": { implemented: true },
5587
5577
  "POST /jobExecution/jobs": { implemented: false, reason: NEEDS_JOBS },
5588
5578
  "GET /jobExecution/jobs/{}": { implemented: false, reason: NEEDS_JOBS },
5589
5579
  "GET /jobExecution/jobs/{}/state": { implemented: false, reason: NEEDS_JOBS },
@@ -5780,7 +5770,7 @@ var SASjsApi = (() => {
5780
5770
  };
5781
5771
 
5782
5772
  // src/viya/compute.ts
5783
- var DEFAULT_CONTEXT_NAME = "SAS Job Execution compute context";
5773
+ var DEFAULT_CONTEXT_NAME = "SASjs Mock context";
5784
5774
  var EMULATED_CONTEXT_ID = idFor("emulated-context", "context");
5785
5775
  var relLinks = (type, rels) => rels.map(([rel, href]) => ({ href, uri: href, rel, method: "GET", type }));
5786
5776
  var linksFor = (uri, type, collection2 = false, itemType = false) => [
@@ -5809,9 +5799,16 @@ var SASjsApi = (() => {
5809
5799
  ];
5810
5800
  var estateOf = (services) => estateFor(estateKeyOf(services.viya), seedOf(services.viya));
5811
5801
  var contextNameFrom = (filter) => {
5812
- if (!filter) return DEFAULT_CONTEXT_NAME;
5813
- const match = /name\s*,\s*'([^']*)'|name\s*,\s*"([^"]*)"/i.exec(filter);
5814
- return match?.[1] ?? match?.[2] ?? DEFAULT_CONTEXT_NAME;
5802
+ if (filter === void 0) return DEFAULT_CONTEXT_NAME;
5803
+ const match = typeof filter === "string" ? /^\s*eq\(\s*name\s*,\s*(?:'([^'\\]*)'|"([^"\\]*)")\s*\)\s*$/.exec(
5804
+ filter
5805
+ ) : null;
5806
+ if (!match)
5807
+ throw new ApiError(
5808
+ 400,
5809
+ 'Unsupported compute context filter. Use eq(name, "...").'
5810
+ );
5811
+ return match[1] ?? match[2];
5815
5812
  };
5816
5813
  var contextBody = (name, caller) => ({
5817
5814
  id: EMULATED_CONTEXT_ID,
@@ -5929,22 +5926,30 @@ var SASjsApi = (() => {
5929
5926
  };
5930
5927
  var COMPUTE_HANDLERS = {
5931
5928
  "GET /compute/contexts": async ({ request }) => {
5932
- const limit = Number(request.query?.limit ?? 0) || 0;
5929
+ if (request.query?.sortBy !== void 0)
5930
+ throw new ApiError(400, "Unsupported compute context sortBy.");
5931
+ const limitText = request.query?.limit;
5932
+ const startText = request.query?.start;
5933
+ const limitValue = limitText === void 0 ? "10" : limitText;
5934
+ const startValue = startText === void 0 ? "0" : startText;
5935
+ if (typeof startValue !== "string" || typeof limitValue !== "string" || !/^\d+$/.test(startValue) || !/^\d+$/.test(limitValue) || !Number.isSafeInteger(Number(startValue)) || !Number.isSafeInteger(Number(limitValue)))
5936
+ throw new ApiError(
5937
+ 400,
5938
+ "Unsupported compute context pagination. Use non-negative integers for start and limit."
5939
+ );
5940
+ const start = Number(startValue);
5941
+ const limit = Number(limitValue);
5942
+ const matches = contextNameFrom(request.query?.filter) === DEFAULT_CONTEXT_NAME ? [contextBody(DEFAULT_CONTEXT_NAME, callerId(request.subject))] : [];
5933
5943
  return {
5934
5944
  status: 200,
5935
5945
  body: {
5936
5946
  accept: "application/json",
5937
5947
  name: "contexts",
5938
- start: 0,
5948
+ start,
5939
5949
  limit,
5940
- count: 1,
5950
+ count: matches.length,
5941
5951
  version: 2,
5942
- items: [
5943
- contextBody(
5944
- contextNameFrom(request.query?.filter),
5945
- callerId(request.subject)
5946
- )
5947
- ],
5952
+ items: matches.slice(start, start + limit),
5948
5953
  links: linksFor(
5949
5954
  "/compute/contexts",
5950
5955
  "application/vnd.sas.compute.context",
@@ -6552,6 +6557,116 @@ var SASjsApi = (() => {
6552
6557
  }
6553
6558
  };
6554
6559
 
6560
+ // src/viya/job-definitions.ts
6561
+ var prefix = ".sasjs-viya-job-";
6562
+ var fileName = (id) => `${prefix}${id}.json`;
6563
+ var pattern = /^\.sasjs-viya-job-([0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})\.json$/;
6564
+ var isJobDefinitionFileName = (name) => pattern.test(name);
6565
+ var definitionFromFile = async (drive, folder, name) => {
6566
+ const match = pattern.exec(name);
6567
+ if (!match) return void 0;
6568
+ const { contents } = await drive.read(
6569
+ `${folder}/${name}`.replace(/\/{2,}/g, "/")
6570
+ );
6571
+ if (typeof contents !== "string") return void 0;
6572
+ try {
6573
+ const value = JSON.parse(contents);
6574
+ if (!value || value.id !== match[1] || typeof value.name !== "string" || typeof value.code !== "string" || typeof value.type !== "string" || !Array.isArray(value.parameters) || !Array.isArray(value.links))
6575
+ return void 0;
6576
+ return value;
6577
+ } catch {
6578
+ return void 0;
6579
+ }
6580
+ };
6581
+ var allNodes = (root) => [
6582
+ root,
6583
+ ...root.children.flatMap(allNodes)
6584
+ ];
6585
+ var JOB_DEFINITION_HANDLERS = {
6586
+ "POST /jobDefinitions/definitions": async ({ services, request }) => {
6587
+ if (services.viya?.allowUntransactionalJobDefinitionCreation !== true)
6588
+ throw new ApiError(
6589
+ 501,
6590
+ "Job definition creation requires an isolated host opt-in; Drive mutations are not transactional."
6591
+ );
6592
+ const body = request.body;
6593
+ if (!body || typeof body.name !== "string" || !body.name || body.name === "." || body.name === ".." || /[/\\\u0000-\u001f]/.test(body.name) || typeof body.type !== "string" || typeof body.code !== "string" || !Array.isArray(body.parameters))
6594
+ throw new ApiError(400, "A name, type, code and parameters are required.");
6595
+ const parameters = Array.from(
6596
+ body.parameters,
6597
+ (item) => {
6598
+ const param = item;
6599
+ if (!param || typeof param.name !== "string" || typeof param.type !== "string" || typeof param.defaultValue !== "string" || param.required !== void 0 && typeof param.required !== "boolean")
6600
+ throw new ApiError(400, "Invalid job parameter.");
6601
+ return {
6602
+ name: param.name,
6603
+ type: param.type,
6604
+ defaultValue: param.defaultValue,
6605
+ required: param.required ?? false,
6606
+ version: 1
6607
+ };
6608
+ }
6609
+ );
6610
+ const parent = request.query?.parentFolderUri;
6611
+ const match = typeof parent === "string" ? parent.match(/^\/folders\/folders\/([^/]+)$/) : void 0;
6612
+ if (!match) throw new ApiError(400, "A parent folder URI is required.");
6613
+ const drive = services.drive;
6614
+ const nodes = allNodes((await drive.tree("/")).tree);
6615
+ const folder = nodes.find(
6616
+ (node) => node.isFolder && idFor(node.relativePath) === match[1]
6617
+ );
6618
+ if (!folder) throw new ApiError(404, "Parent folder not found.");
6619
+ const listing = await drive.list(folder.relativePath);
6620
+ const existing = await Promise.all(
6621
+ listing.files.map(
6622
+ (name) => definitionFromFile(drive, folder.relativePath, name)
6623
+ )
6624
+ );
6625
+ if (existing.some((definition2) => definition2?.name === body.name))
6626
+ throw new ApiError(409, "Job definition already exists.");
6627
+ const id = newUuidV4();
6628
+ const uri = `/jobDefinitions/definitions/${id}`;
6629
+ const caller = callerId(request.subject);
6630
+ const definition = {
6631
+ id,
6632
+ name: body.name,
6633
+ type: body.type,
6634
+ code: body.code,
6635
+ parameters,
6636
+ version: 1,
6637
+ createdBy: caller,
6638
+ modifiedBy: caller,
6639
+ creationTimeStamp: EMULATED_NOW,
6640
+ modifiedTimeStamp: EMULATED_NOW,
6641
+ links: [
6642
+ {
6643
+ href: uri,
6644
+ uri,
6645
+ rel: "self",
6646
+ method: "GET",
6647
+ type: "application/vnd.sas.job.definition"
6648
+ }
6649
+ ]
6650
+ };
6651
+ await drive.save(
6652
+ `${folder.relativePath}/${fileName(id)}`.replace(/\/{2,}/g, "/"),
6653
+ JSON.stringify(definition)
6654
+ );
6655
+ return { status: 201, body: definition };
6656
+ },
6657
+ "GET /jobDefinitions/definitions/{}": async ({ services, params }) => {
6658
+ const name = fileName(params.id);
6659
+ if (!pattern.test(name))
6660
+ throw new ApiError(404, "Job definition not found.");
6661
+ const nodes = allNodes((await services.drive.tree("/")).tree);
6662
+ const node = nodes.find((item) => !item.isFolder && item.name === name);
6663
+ const folder = node?.relativePath.slice(0, -(name.length + 1)) || "/";
6664
+ const definition = node && await definitionFromFile(services.drive, folder, name);
6665
+ if (!definition) throw new ApiError(404, "Job definition not found.");
6666
+ return { status: 200, body: definition };
6667
+ }
6668
+ };
6669
+
6555
6670
  // src/viya/service.ts
6556
6671
  var linksFor2 = (uri, collection2 = false) => {
6557
6672
  const self = {
@@ -6622,17 +6737,17 @@ var SASjsApi = (() => {
6622
6737
  var RECYCLE_BIN_ALIAS = "/folders/folders/@myRecycleBin";
6623
6738
  var isRecycleBin = (uri) => !!uri && (uri === RECYCLE_BIN_ALIAS || uri.endsWith(`/${idFor("@myRecycleBin")}`));
6624
6739
  var pathForId = async (drive, id) => {
6625
- const walk2 = (node) => {
6626
- if (node.isFolder && idFor(node.relativePath) === id)
6627
- return node.relativePath;
6628
- for (const child of node.children) {
6629
- const hit = walk2(child);
6630
- if (hit) return hit;
6740
+ const walk2 = async (path2) => {
6741
+ if (idFor(path2) === id) return path2;
6742
+ const { folders } = await drive.list(path2);
6743
+ for (const name of folders) {
6744
+ const child = path2 === "/" ? `/${name}` : `${path2}/${name}`;
6745
+ const hit = await walk2(child);
6746
+ if (hit !== void 0) return hit;
6631
6747
  }
6632
6748
  return void 0;
6633
6749
  };
6634
- const { tree } = await drive.tree("/");
6635
- const path = walk2(tree);
6750
+ const path = await walk2("/");
6636
6751
  if (!path)
6637
6752
  throw new ApiError(
6638
6753
  404,
@@ -6745,13 +6860,15 @@ var SASjsApi = (() => {
6745
6860
  "GET /folders/folders/{}/members": async ({ services, params, request }) => {
6746
6861
  const drive = requireDrive(services);
6747
6862
  const limit = Number(request.query?.limit ?? 0) || 0;
6863
+ const requestedStart = Number(request.query?.start ?? 0);
6864
+ const start = Number.isSafeInteger(requestedStart) && requestedStart > 0 ? requestedStart : 0;
6748
6865
  if (params.id === idFor("@myRecycleBin"))
6749
6866
  return {
6750
6867
  status: 200,
6751
6868
  body: {
6752
6869
  accept: "application/json",
6753
6870
  name: "members",
6754
- start: 0,
6871
+ start,
6755
6872
  // the query value is echoed as the sibling branch echoes it: a caller
6756
6873
  // that asked for five and is told zero cannot tell what happened
6757
6874
  limit,
@@ -6764,6 +6881,13 @@ var SASjsApi = (() => {
6764
6881
  const path = await pathForId(drive, params.id);
6765
6882
  const listing = await drive.list(path);
6766
6883
  const caller = callerId(request.subject);
6884
+ const canReadMetadata = services.viya?.readJobDefinitionMetadata !== false;
6885
+ const definitions = canReadMetadata ? await Promise.all(
6886
+ listing.files.map((name) => definitionFromFile(drive, path, name))
6887
+ ) : [];
6888
+ const definitionByFile = new Map(
6889
+ listing.files.map((name, index) => [name, definitions[index]])
6890
+ );
6767
6891
  const items = [
6768
6892
  ...listing.folders.map((name) => ({
6769
6893
  id: idFor(`${path}/${name}`.replace(/\/{2,}/g, "/")),
@@ -6780,7 +6904,9 @@ var SASjsApi = (() => {
6780
6904
  `/folders/folders/${idFor(`${path}/${name}`.replace(/\/{2,}/g, "/"))}`
6781
6905
  )
6782
6906
  })),
6783
- ...listing.files.map((name) => ({
6907
+ ...listing.files.filter(
6908
+ (name) => !definitionByFile.get(name) && (canReadMetadata || !isJobDefinitionFileName(name))
6909
+ ).map((name) => ({
6784
6910
  id: idFor(`${path}/${name}`.replace(/\/{2,}/g, "/"), "file"),
6785
6911
  name,
6786
6912
  type: "file",
@@ -6796,15 +6922,43 @@ var SASjsApi = (() => {
6796
6922
  links: linksFor2(
6797
6923
  `/files/files/${idFor(`${path}/${name}`.replace(/\/{2,}/g, "/"), "file")}`
6798
6924
  )
6799
- }))
6925
+ })),
6926
+ ...definitions.filter((definition) => definition !== void 0).map((definition) => {
6927
+ const uri = `/jobDefinitions/definitions/${definition.id}`;
6928
+ return {
6929
+ id: definition.id,
6930
+ name: definition.name,
6931
+ // The captured member identifies its relationship separately from
6932
+ // the resource kind. Other links remain emulated, not estate parity.
6933
+ type: "child",
6934
+ contentType: "jobDefinition",
6935
+ version: 1,
6936
+ createdBy: definition.createdBy,
6937
+ modifiedBy: definition.modifiedBy,
6938
+ creationTimeStamp: definition.creationTimeStamp,
6939
+ modifiedTimeStamp: definition.modifiedTimeStamp,
6940
+ parentFolderUri: `/folders/folders/${idFor(path)}`,
6941
+ added: definition.creationTimeStamp,
6942
+ uri,
6943
+ links: [
6944
+ {
6945
+ href: uri,
6946
+ uri,
6947
+ rel: "getResource",
6948
+ method: "GET",
6949
+ type: "application/vnd.sas.summary"
6950
+ }
6951
+ ]
6952
+ };
6953
+ })
6800
6954
  ];
6801
- const page = limit > 0 ? items.slice(0, limit) : items;
6955
+ const page = limit > 0 ? items.slice(start, start + limit) : items.slice(start);
6802
6956
  return {
6803
6957
  status: 200,
6804
6958
  body: {
6805
6959
  accept: "application/json",
6806
6960
  name: "members",
6807
- start: 0,
6961
+ start,
6808
6962
  limit: limit || page.length,
6809
6963
  count: page.length,
6810
6964
  version: 2,
@@ -6854,7 +7008,8 @@ var SASjsApi = (() => {
6854
7008
  },
6855
7009
  ...COMPUTE_HANDLERS,
6856
7010
  ...FILE_HANDLERS,
6857
- ...IDENTITY_HANDLERS
7011
+ ...IDENTITY_HANDLERS,
7012
+ ...JOB_DEFINITION_HANDLERS
6858
7013
  };
6859
7014
 
6860
7015
  // src/viya/dispatch.ts
@@ -10364,10 +10519,10 @@ var SASjsApi = (() => {
10364
10519
  return file;
10365
10520
  });
10366
10521
  };
10367
- var checkLogFileName = (fileName) => {
10368
- if (!fileName || fileName.includes("/") || fileName.includes("\\") || fileName.split(/[\\/]/).pop() !== fileName || !fileName.toLowerCase().endsWith(".log"))
10522
+ var checkLogFileName = (fileName2) => {
10523
+ if (!fileName2 || fileName2.includes("/") || fileName2.includes("\\") || fileName2.split(/[\\/]/).pop() !== fileName2 || !fileName2.toLowerCase().endsWith(".log"))
10369
10524
  throw new ApiError(400, "Invalid log file name.");
10370
- return fileName;
10525
+ return fileName2;
10371
10526
  };
10372
10527
  var logLines = (lines) => {
10373
10528
  if (lines === void 0 || lines === null || lines === "")
@@ -10396,8 +10551,8 @@ var SASjsApi = (() => {
10396
10551
  async logs() {
10397
10552
  return normaliseLogFiles(await reports.logs());
10398
10553
  },
10399
- async logTail(fileName, lines) {
10400
- const name = checkLogFileName(fileName);
10554
+ async logTail(fileName2, lines) {
10555
+ const name = checkLogFileName(fileName2);
10401
10556
  const tail = await reports.logTail(name, logLines(lines));
10402
10557
  if (tail === void 0) throw new ApiError(404, "Log file not found.");
10403
10558
  return normaliseLogTail(tail);
@@ -12805,7 +12960,7 @@ var SASjsApi = (() => {
12805
12960
  admin: createAdminService({
12806
12961
  diagnostics: async () => CORPUS_DIAGNOSTICS,
12807
12962
  logs: async () => [CORPUS_LOG],
12808
- logTail: async (fileName) => fileName === CORPUS_LOG.name ? CORPUS_LOG_TAIL : void 0
12963
+ logTail: async (fileName2) => fileName2 === CORPUS_LOG.name ? CORPUS_LOG_TAIL : void 0
12809
12964
  }),
12810
12965
  directory: createDirectoryService(identity, CORPUS_DIRECTORY),
12811
12966
  identity: createIdentityService(identity),
@@ -6,18 +6,9 @@ const seed_js_1 = require("./seed.js");
6
6
  const sessions_js_1 = require("./sessions.js");
7
7
  const ids_js_1 = require("./ids.js");
8
8
  const overlay_js_1 = require("./overlay.js");
9
- /**
10
- * The name the emulator answers when a client asks for no particular context.
11
- *
12
- * It is the name of the context a Viya estate ships with, because that is the
13
- * name a client carries: `SASViyaApiClient.createSession` lists `/compute/contexts`
14
- * with no filter and picks the entry whose name it was given, so a default of the
15
- * emulator's own choosing fails every caller with a name that is right everywhere
16
- * else. A client may still name any context it likes - see `contextNameFrom` - and
17
- * the estate answers under that name.
18
- */
19
- exports.DEFAULT_CONTEXT_NAME = 'SAS Job Execution compute context';
20
- /** The one context id this estate mints, whatever name it is asked for. */
9
+ /** The one mock context, selected explicitly by clients. */
10
+ exports.DEFAULT_CONTEXT_NAME = 'SASjs Mock context';
11
+ /** The fixed id of the one emulated context. */
21
12
  exports.EMULATED_CONTEXT_ID = (0, ids_js_1.idFor)('emulated-context', 'context');
22
13
  /**
23
14
  * The links a client follows, by rel.
@@ -56,18 +47,19 @@ const linksFor = (uri, type, collection = false, itemType = false) => [
56
47
  ];
57
48
  const estateOf = (services) => (0, sessions_js_1.estateFor)((0, seed_js_1.estateKeyOf)(services.viya), (0, seed_js_1.seedOf)(services.viya));
58
49
  /**
59
- * The context name a client asked for.
60
- *
61
- * The adapter filters by name (`filter=eq(name,'X')`), so the answer is the one
62
- * emulated context under the requested name. A second estate is not something an
63
- * emulator can have, and an empty list would fail a client that has nothing wrong
64
- * with it.
50
+ * Read only the simple equality filter used by the adapter. Single-quoted
51
+ * names are also supported for existing mock clients. Escapes, other operators
52
+ * and compound expressions are refused rather than guessed.
65
53
  */
66
54
  const contextNameFrom = (filter) => {
67
- if (!filter)
55
+ if (filter === undefined)
68
56
  return exports.DEFAULT_CONTEXT_NAME;
69
- const match = /name\s*,\s*'([^']*)'|name\s*,\s*"([^"]*)"/i.exec(filter);
70
- return match?.[1] ?? match?.[2] ?? exports.DEFAULT_CONTEXT_NAME;
57
+ const match = typeof filter === 'string'
58
+ ? /^\s*eq\(\s*name\s*,\s*(?:'([^'\\]*)'|"([^"\\]*)")\s*\)\s*$/.exec(filter)
59
+ : null;
60
+ if (!match)
61
+ throw new types_js_1.ApiError(400, 'Unsupported compute context filter. Use eq(name, "...").');
62
+ return match[1] ?? match[2];
71
63
  };
72
64
  exports.contextNameFrom = contextNameFrom;
73
65
  const contextBody = (name, caller) => ({
@@ -207,19 +199,34 @@ const validCodeLines = (lines) => {
207
199
  };
208
200
  exports.COMPUTE_HANDLERS = {
209
201
  'GET /compute/contexts': async ({ request }) => {
210
- const limit = Number(request.query?.limit ?? 0) || 0;
202
+ if (request.query?.sortBy !== undefined)
203
+ throw new types_js_1.ApiError(400, 'Unsupported compute context sortBy.');
204
+ const limitText = request.query?.limit;
205
+ const startText = request.query?.start;
206
+ const limitValue = limitText === undefined ? '10' : limitText;
207
+ const startValue = startText === undefined ? '0' : startText;
208
+ if (typeof startValue !== 'string' ||
209
+ typeof limitValue !== 'string' ||
210
+ !/^\d+$/.test(startValue) ||
211
+ !/^\d+$/.test(limitValue) ||
212
+ !Number.isSafeInteger(Number(startValue)) ||
213
+ !Number.isSafeInteger(Number(limitValue)))
214
+ throw new types_js_1.ApiError(400, 'Unsupported compute context pagination. Use non-negative integers for start and limit.');
215
+ const start = Number(startValue);
216
+ const limit = Number(limitValue);
217
+ const matches = (0, exports.contextNameFrom)(request.query?.filter) === exports.DEFAULT_CONTEXT_NAME
218
+ ? [contextBody(exports.DEFAULT_CONTEXT_NAME, (0, ids_js_1.callerId)(request.subject))]
219
+ : [];
211
220
  return {
212
221
  status: 200,
213
222
  body: {
214
223
  accept: 'application/json',
215
224
  name: 'contexts',
216
- start: 0,
225
+ start,
217
226
  limit,
218
- count: 1,
227
+ count: matches.length,
219
228
  version: 2,
220
- items: [
221
- contextBody((0, exports.contextNameFrom)(request.query?.filter), (0, ids_js_1.callerId)(request.subject))
222
- ],
229
+ items: matches.slice(start, start + limit),
223
230
  links: linksFor('/compute/contexts', 'application/vnd.sas.compute.context', true)
224
231
  }
225
232
  };