@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.
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.JOB_DEFINITION_HANDLERS = exports.definitionFromFile = exports.isJobDefinitionFileName = void 0;
4
+ const types_js_1 = require("../types.js");
5
+ const uuid_js_1 = require("../uuid.js");
6
+ const ids_js_1 = require("./ids.js");
7
+ const prefix = '.sasjs-viya-job-';
8
+ const fileName = (id) => `${prefix}${id}.json`;
9
+ const 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$/;
10
+ const isJobDefinitionFileName = (name) => pattern.test(name);
11
+ exports.isJobDefinitionFileName = isJobDefinitionFileName;
12
+ /** Read only explicitly marked, well-formed records; malformed files remain ordinary files. */
13
+ const definitionFromFile = async (drive, folder, name) => {
14
+ const match = pattern.exec(name);
15
+ if (!match)
16
+ return undefined;
17
+ const { contents } = await drive.read(`${folder}/${name}`.replace(/\/{2,}/g, '/'));
18
+ if (typeof contents !== 'string')
19
+ return undefined;
20
+ try {
21
+ const value = JSON.parse(contents);
22
+ if (!value ||
23
+ value.id !== match[1] ||
24
+ typeof value.name !== 'string' ||
25
+ typeof value.code !== 'string' ||
26
+ typeof value.type !== 'string' ||
27
+ !Array.isArray(value.parameters) ||
28
+ !Array.isArray(value.links))
29
+ return undefined;
30
+ return value;
31
+ }
32
+ catch {
33
+ return undefined;
34
+ }
35
+ };
36
+ exports.definitionFromFile = definitionFromFile;
37
+ const allNodes = (root) => [
38
+ root,
39
+ ...root.children.flatMap(allNodes)
40
+ ];
41
+ exports.JOB_DEFINITION_HANDLERS = {
42
+ 'POST /jobDefinitions/definitions': async ({ services, request }) => {
43
+ if (services.viya?.allowUntransactionalJobDefinitionCreation !== true)
44
+ throw new types_js_1.ApiError(501, 'Job definition creation requires an isolated host opt-in; Drive mutations are not transactional.');
45
+ const body = request.body;
46
+ if (!body ||
47
+ typeof body.name !== 'string' ||
48
+ !body.name ||
49
+ body.name === '.' ||
50
+ body.name === '..' ||
51
+ /[/\\\u0000-\u001f]/.test(body.name) ||
52
+ typeof body.type !== 'string' ||
53
+ typeof body.code !== 'string' ||
54
+ !Array.isArray(body.parameters))
55
+ throw new types_js_1.ApiError(400, 'A name, type, code and parameters are required.');
56
+ const parameters = Array.from(body.parameters, (item) => {
57
+ const param = item;
58
+ if (!param ||
59
+ typeof param.name !== 'string' ||
60
+ typeof param.type !== 'string' ||
61
+ typeof param.defaultValue !== 'string' ||
62
+ (param.required !== undefined && typeof param.required !== 'boolean'))
63
+ throw new types_js_1.ApiError(400, 'Invalid job parameter.');
64
+ return {
65
+ name: param.name,
66
+ type: param.type,
67
+ defaultValue: param.defaultValue,
68
+ required: param.required ?? false,
69
+ version: 1
70
+ };
71
+ });
72
+ const parent = request.query?.parentFolderUri;
73
+ const match = typeof parent === 'string'
74
+ ? parent.match(/^\/folders\/folders\/([^/]+)$/)
75
+ : undefined;
76
+ if (!match)
77
+ throw new types_js_1.ApiError(400, 'A parent folder URI is required.');
78
+ const drive = services.drive;
79
+ const nodes = allNodes((await drive.tree('/')).tree);
80
+ const folder = nodes.find((node) => node.isFolder && (0, ids_js_1.idFor)(node.relativePath) === match[1]);
81
+ if (!folder)
82
+ throw new types_js_1.ApiError(404, 'Parent folder not found.');
83
+ const listing = await drive.list(folder.relativePath);
84
+ const existing = await Promise.all(listing.files.map((name) => (0, exports.definitionFromFile)(drive, folder.relativePath, name)));
85
+ if (existing.some((definition) => definition?.name === body.name))
86
+ throw new types_js_1.ApiError(409, 'Job definition already exists.');
87
+ const id = (0, uuid_js_1.newUuidV4)();
88
+ const uri = `/jobDefinitions/definitions/${id}`;
89
+ const caller = (0, ids_js_1.callerId)(request.subject);
90
+ const definition = {
91
+ id,
92
+ name: body.name,
93
+ type: body.type,
94
+ code: body.code,
95
+ parameters,
96
+ version: 1,
97
+ createdBy: caller,
98
+ modifiedBy: caller,
99
+ creationTimeStamp: ids_js_1.EMULATED_NOW,
100
+ modifiedTimeStamp: ids_js_1.EMULATED_NOW,
101
+ links: [
102
+ {
103
+ href: uri,
104
+ uri,
105
+ rel: 'self',
106
+ method: 'GET',
107
+ type: 'application/vnd.sas.job.definition'
108
+ }
109
+ ]
110
+ };
111
+ await drive.save(`${folder.relativePath}/${fileName(id)}`.replace(/\/{2,}/g, '/'), JSON.stringify(definition));
112
+ return { status: 201, body: definition };
113
+ },
114
+ 'GET /jobDefinitions/definitions/{}': async ({ services, params }) => {
115
+ const name = fileName(params.id);
116
+ if (!pattern.test(name))
117
+ throw new types_js_1.ApiError(404, 'Job definition not found.');
118
+ const nodes = allNodes((await services.drive.tree('/')).tree);
119
+ const node = nodes.find((item) => !item.isFolder && item.name === name);
120
+ const folder = node?.relativePath.slice(0, -(name.length + 1)) || '/';
121
+ const definition = node && (await (0, exports.definitionFromFile)(services.drive, folder, name));
122
+ if (!definition)
123
+ throw new types_js_1.ApiError(404, 'Job definition not found.');
124
+ return { status: 200, body: definition };
125
+ }
126
+ };
@@ -23,15 +23,8 @@ const declared_js_1 = require("./declared.js");
23
23
  * a second answer to the same question.
24
24
  */
25
25
  const NEEDS_AUTH = 'The token endpoint is answered by the host that mounts the emulator, which owns the token port.';
26
- /**
27
- * The job family is a capture without a handler.
28
- *
29
- * The deploy-and-run path is recorded - a service pack deploy creates a job
30
- * definition and submits it - and this package answers the compute and content
31
- * families, not that one. Saying so is the difference between a client learning
32
- * what is missing and a client learning nothing.
33
- */
34
- const 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.';
26
+ /** Definition storage is modelled separately from job execution. */
27
+ const NEEDS_JOBS = 'The emulator stores job definitions but does not model job executions.';
35
28
  exports.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.';
36
29
  exports.VIYA_OVERLAY = {
37
30
  // answered here
@@ -69,19 +62,9 @@ exports.VIYA_OVERLAY = {
69
62
  'PATCH /files/files/{}': { implemented: true },
70
63
  'GET /files/files/{}/content': { implemented: true },
71
64
  'PUT /files/files/{}/content': { implemented: true },
72
- // declined: the job family needs a job service
73
- //
74
- // A capture describes what the estate answers on the deploy-and-run path, and
75
- // the emulator does not answer that path yet: a client that deploys a service
76
- // pack against an emulated estate stops here, with a reason rather than a 404.
77
- 'POST /jobDefinitions/definitions': {
78
- implemented: false,
79
- reason: NEEDS_JOBS
80
- },
81
- 'GET /jobDefinitions/definitions/{}': {
82
- implemented: false,
83
- reason: NEEDS_JOBS
84
- },
65
+ // Definition persistence does not implement job execution.
66
+ 'POST /jobDefinitions/definitions': { implemented: true },
67
+ 'GET /jobDefinitions/definitions/{}': { implemented: true },
85
68
  'POST /jobExecution/jobs': { implemented: false, reason: NEEDS_JOBS },
86
69
  'GET /jobExecution/jobs/{}': { implemented: false, reason: NEEDS_JOBS },
87
70
  'GET /jobExecution/jobs/{}/state': { implemented: false, reason: NEEDS_JOBS },
@@ -6,6 +6,7 @@ const ports_js_1 = require("./ports.js");
6
6
  const compute_js_1 = require("./compute.js");
7
7
  const files_js_1 = require("./files.js");
8
8
  const identity_js_1 = require("./identity.js");
9
+ const job_definitions_js_1 = require("./job-definitions.js");
9
10
  const ids_js_1 = require("./ids.js");
10
11
  const linksFor = (uri, collection = false) => {
11
12
  const self = {
@@ -89,18 +90,19 @@ const isRecycleBin = (uri) => !!uri &&
89
90
  * opposite of "a client stores an id and asks for it later".
90
91
  */
91
92
  const pathForId = async (drive, id) => {
92
- const walk = (node) => {
93
- if (node.isFolder && (0, ids_js_1.idFor)(node.relativePath) === id)
94
- return node.relativePath;
95
- for (const child of node.children) {
96
- const hit = walk(child);
97
- if (hit)
93
+ const walk = async (path) => {
94
+ if ((0, ids_js_1.idFor)(path) === id)
95
+ return path;
96
+ const { folders } = await drive.list(path);
97
+ for (const name of folders) {
98
+ const child = path === '/' ? `/${name}` : `${path}/${name}`;
99
+ const hit = await walk(child);
100
+ if (hit !== undefined)
98
101
  return hit;
99
102
  }
100
103
  return undefined;
101
104
  };
102
- const { tree } = await drive.tree('/');
103
- const path = walk(tree);
105
+ const path = await walk('/');
104
106
  if (!path)
105
107
  throw new types_js_1.ApiError(404, `No folder matches the id ${id}. Ids are derived from paths, so an id that names no folder is one no folder ever had.`);
106
108
  return path;
@@ -208,6 +210,10 @@ exports.VIYA_HANDLERS = {
208
210
  'GET /folders/folders/{}/members': async ({ services, params, request }) => {
209
211
  const drive = (0, ports_js_1.requireDrive)(services);
210
212
  const limit = Number(request.query?.limit ?? 0) || 0;
213
+ const requestedStart = Number(request.query?.start ?? 0);
214
+ const start = Number.isSafeInteger(requestedStart) && requestedStart > 0
215
+ ? requestedStart
216
+ : 0;
211
217
  // the bin is not a folder in the drive, and its own body advertises this
212
218
  // link - so a client following the answer it just received must not 404
213
219
  if (params.id === (0, ids_js_1.idFor)('@myRecycleBin'))
@@ -216,7 +222,7 @@ exports.VIYA_HANDLERS = {
216
222
  body: {
217
223
  accept: 'application/json',
218
224
  name: 'members',
219
- start: 0,
225
+ start,
220
226
  // the query value is echoed as the sibling branch echoes it: a caller
221
227
  // that asked for five and is told zero cannot tell what happened
222
228
  limit,
@@ -229,6 +235,11 @@ exports.VIYA_HANDLERS = {
229
235
  const path = await pathForId(drive, params.id);
230
236
  const listing = await drive.list(path);
231
237
  const caller = (0, ids_js_1.callerId)(request.subject);
238
+ const canReadMetadata = services.viya?.readJobDefinitionMetadata !== false;
239
+ const definitions = canReadMetadata
240
+ ? await Promise.all(listing.files.map((name) => (0, job_definitions_js_1.definitionFromFile)(drive, path, name)))
241
+ : [];
242
+ const definitionByFile = new Map(listing.files.map((name, index) => [name, definitions[index]]));
232
243
  /**
233
244
  * A member's `uri` is the resource, not its path.
234
245
  *
@@ -252,7 +263,10 @@ exports.VIYA_HANDLERS = {
252
263
  uri: `/folders/folders/${(0, ids_js_1.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'))}`,
253
264
  links: linksFor(`/folders/folders/${(0, ids_js_1.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'))}`)
254
265
  })),
255
- ...listing.files.map((name) => ({
266
+ ...listing.files
267
+ .filter((name) => !definitionByFile.get(name) &&
268
+ (canReadMetadata || !(0, job_definitions_js_1.isJobDefinitionFileName)(name)))
269
+ .map((name) => ({
256
270
  id: (0, ids_js_1.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'), 'file'),
257
271
  name,
258
272
  type: 'file',
@@ -266,9 +280,39 @@ exports.VIYA_HANDLERS = {
266
280
  added: ids_js_1.EMULATED_NOW,
267
281
  uri: `/files/files/${(0, ids_js_1.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'), 'file')}`,
268
282
  links: linksFor(`/files/files/${(0, ids_js_1.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'), 'file')}`)
269
- }))
283
+ })),
284
+ ...definitions
285
+ .filter((definition) => definition !== undefined)
286
+ .map((definition) => {
287
+ const uri = `/jobDefinitions/definitions/${definition.id}`;
288
+ return {
289
+ id: definition.id,
290
+ name: definition.name,
291
+ // The captured member identifies its relationship separately from
292
+ // the resource kind. Other links remain emulated, not estate parity.
293
+ type: 'child',
294
+ contentType: 'jobDefinition',
295
+ version: 1,
296
+ createdBy: definition.createdBy,
297
+ modifiedBy: definition.modifiedBy,
298
+ creationTimeStamp: definition.creationTimeStamp,
299
+ modifiedTimeStamp: definition.modifiedTimeStamp,
300
+ parentFolderUri: `/folders/folders/${(0, ids_js_1.idFor)(path)}`,
301
+ added: definition.creationTimeStamp,
302
+ uri,
303
+ links: [
304
+ {
305
+ href: uri,
306
+ uri,
307
+ rel: 'getResource',
308
+ method: 'GET',
309
+ type: 'application/vnd.sas.summary'
310
+ }
311
+ ]
312
+ };
313
+ })
270
314
  ];
271
- const page = limit > 0 ? items.slice(0, limit) : items;
315
+ const page = limit > 0 ? items.slice(start, start + limit) : items.slice(start);
272
316
  // the envelope is what the capture recorded, including the paging fields a
273
317
  // client reads to decide whether to ask for more
274
318
  return {
@@ -276,7 +320,7 @@ exports.VIYA_HANDLERS = {
276
320
  body: {
277
321
  accept: 'application/json',
278
322
  name: 'members',
279
- start: 0,
323
+ start,
280
324
  limit: limit || page.length,
281
325
  count: page.length,
282
326
  version: 2,
@@ -341,5 +385,6 @@ exports.VIYA_HANDLERS = {
341
385
  },
342
386
  ...compute_js_1.COMPUTE_HANDLERS,
343
387
  ...files_js_1.FILE_HANDLERS,
344
- ...identity_js_1.IDENTITY_HANDLERS
388
+ ...identity_js_1.IDENTITY_HANDLERS,
389
+ ...job_definitions_js_1.JOB_DEFINITION_HANDLERS
345
390
  };
@@ -7,35 +7,21 @@
7
7
  * because there is no SAS engine to reach for in a browser and no reason to reach
8
8
  * for one here.
9
9
  *
10
- * The context is the one place the emulator answers the question it was asked
11
- * rather than one it chose: a client names the context it wants by filter and the
12
- * emulated estate has exactly one, under that name. Its id does not move with the
13
- * name, so a session can be created for the id the list returned.
10
+ * The emulated estate has one context. Its list, detail and session creation
11
+ * share its fixed identity; a filter cannot rename it.
14
12
  */
15
13
  import type { ApiResponse, Services } from '../host/dispatch.js';
16
14
  import type { Subject } from '../identity/types.js';
17
- /**
18
- * The name the emulator answers when a client asks for no particular context.
19
- *
20
- * It is the name of the context a Viya estate ships with, because that is the
21
- * name a client carries: `SASViyaApiClient.createSession` lists `/compute/contexts`
22
- * with no filter and picks the entry whose name it was given, so a default of the
23
- * emulator's own choosing fails every caller with a name that is right everywhere
24
- * else. A client may still name any context it likes - see `contextNameFrom` - and
25
- * the estate answers under that name.
26
- */
27
- export declare const DEFAULT_CONTEXT_NAME = "SAS Job Execution compute context";
28
- /** The one context id this estate mints, whatever name it is asked for. */
15
+ /** The one mock context, selected explicitly by clients. */
16
+ export declare const DEFAULT_CONTEXT_NAME = "SASjs Mock context";
17
+ /** The fixed id of the one emulated context. */
29
18
  export declare const EMULATED_CONTEXT_ID: string;
30
19
  /**
31
- * The context name a client asked for.
32
- *
33
- * The adapter filters by name (`filter=eq(name,'X')`), so the answer is the one
34
- * emulated context under the requested name. A second estate is not something an
35
- * emulator can have, and an empty list would fail a client that has nothing wrong
36
- * with it.
20
+ * Read only the simple equality filter used by the adapter. Single-quoted
21
+ * names are also supported for existing mock clients. Escapes, other operators
22
+ * and compound expressions are refused rather than guessed.
37
23
  */
38
- export declare const contextNameFrom: (filter: string | undefined) => string;
24
+ export declare const contextNameFrom: (filter: unknown) => string;
39
25
  export declare const COMPUTE_HANDLERS: Record<string, (context: {
40
26
  services: Services;
41
27
  request: {
@@ -1 +1 @@
1
- {"version":3,"file":"compute.d.ts","sourceRoot":"","sources":["../../../src/viya/compute.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAChE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAA;AAOnD;;;;;;;;;GASG;AACH,eAAO,MAAM,oBAAoB,sCAAsC,CAAA;AAEvE,2EAA2E;AAC3E,eAAO,MAAM,mBAAmB,QAAuC,CAAA;AAgDvE;;;;;;;GAOG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,MAAM,GAAG,SAAS,KAAG,MAM5D,CAAA;AA0KD,eAAO,MAAM,gBAAgB,EAAE,MAAM,CACnC,MAAM,EACN,CAAC,OAAO,EAAE;IACR,QAAQ,EAAE,QAAQ,CAAA;IAClB,OAAO,EAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAA;QAC1C,IAAI,CAAC,EAAE,OAAO,CAAA;QACd,KAAK,CAAC,EAAE,MAAM,CAAA;QACd,OAAO,CAAC,EAAE,OAAO,CAAA;KAClB,CAAA;IACD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC/B,KAAK,OAAO,CAAC,WAAW,CAAC,CAwU3B,CAAA"}
1
+ {"version":3,"file":"compute.d.ts","sourceRoot":"","sources":["../../../src/viya/compute.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAChE,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAA;AAOnD,4DAA4D;AAC5D,eAAO,MAAM,oBAAoB,uBAAuB,CAAA;AAExD,gDAAgD;AAChD,eAAO,MAAM,mBAAmB,QAAuC,CAAA;AAgDvE;;;;GAIG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,OAAO,KAAG,MAgBjD,CAAA;AA0KD,eAAO,MAAM,gBAAgB,EAAE,MAAM,CACnC,MAAM,EACN,CAAC,OAAO,EAAE;IACR,QAAQ,EAAE,QAAQ,CAAA;IAClB,OAAO,EAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAA;QAC1C,IAAI,CAAC,EAAE,OAAO,CAAA;QACd,KAAK,CAAC,EAAE,MAAM,CAAA;QACd,OAAO,CAAC,EAAE,OAAO,CAAA;KAClB,CAAA;IACD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC/B,KAAK,OAAO,CAAC,WAAW,CAAC,CA0V3B,CAAA"}
@@ -3,18 +3,9 @@ import { estateKeyOf, normaliseServerUrl, seedOf } from './seed.js';
3
3
  import { estateFor } from './sessions.js';
4
4
  import { idFor, callerId, EMULATED_NOW } from './ids.js';
5
5
  import { SESSION_VARIABLE_REFUSAL } from './overlay.js';
6
- /**
7
- * The name the emulator answers when a client asks for no particular context.
8
- *
9
- * It is the name of the context a Viya estate ships with, because that is the
10
- * name a client carries: `SASViyaApiClient.createSession` lists `/compute/contexts`
11
- * with no filter and picks the entry whose name it was given, so a default of the
12
- * emulator's own choosing fails every caller with a name that is right everywhere
13
- * else. A client may still name any context it likes - see `contextNameFrom` - and
14
- * the estate answers under that name.
15
- */
16
- export const DEFAULT_CONTEXT_NAME = 'SAS Job Execution compute context';
17
- /** The one context id this estate mints, whatever name it is asked for. */
6
+ /** The one mock context, selected explicitly by clients. */
7
+ export const DEFAULT_CONTEXT_NAME = 'SASjs Mock context';
8
+ /** The fixed id of the one emulated context. */
18
9
  export const EMULATED_CONTEXT_ID = idFor('emulated-context', 'context');
19
10
  /**
20
11
  * The links a client follows, by rel.
@@ -53,18 +44,19 @@ const linksFor = (uri, type, collection = false, itemType = false) => [
53
44
  ];
54
45
  const estateOf = (services) => estateFor(estateKeyOf(services.viya), seedOf(services.viya));
55
46
  /**
56
- * The context name a client asked for.
57
- *
58
- * The adapter filters by name (`filter=eq(name,'X')`), so the answer is the one
59
- * emulated context under the requested name. A second estate is not something an
60
- * emulator can have, and an empty list would fail a client that has nothing wrong
61
- * with it.
47
+ * Read only the simple equality filter used by the adapter. Single-quoted
48
+ * names are also supported for existing mock clients. Escapes, other operators
49
+ * and compound expressions are refused rather than guessed.
62
50
  */
63
51
  export const contextNameFrom = (filter) => {
64
- if (!filter)
52
+ if (filter === undefined)
65
53
  return DEFAULT_CONTEXT_NAME;
66
- const match = /name\s*,\s*'([^']*)'|name\s*,\s*"([^"]*)"/i.exec(filter);
67
- return match?.[1] ?? match?.[2] ?? DEFAULT_CONTEXT_NAME;
54
+ const match = typeof filter === 'string'
55
+ ? /^\s*eq\(\s*name\s*,\s*(?:'([^'\\]*)'|"([^"\\]*)")\s*\)\s*$/.exec(filter)
56
+ : null;
57
+ if (!match)
58
+ throw new ApiError(400, 'Unsupported compute context filter. Use eq(name, "...").');
59
+ return match[1] ?? match[2];
68
60
  };
69
61
  const contextBody = (name, caller) => ({
70
62
  id: EMULATED_CONTEXT_ID,
@@ -203,19 +195,34 @@ const validCodeLines = (lines) => {
203
195
  };
204
196
  export const COMPUTE_HANDLERS = {
205
197
  'GET /compute/contexts': async ({ request }) => {
206
- const limit = Number(request.query?.limit ?? 0) || 0;
198
+ if (request.query?.sortBy !== undefined)
199
+ throw new ApiError(400, 'Unsupported compute context sortBy.');
200
+ const limitText = request.query?.limit;
201
+ const startText = request.query?.start;
202
+ const limitValue = limitText === undefined ? '10' : limitText;
203
+ const startValue = startText === undefined ? '0' : startText;
204
+ if (typeof startValue !== 'string' ||
205
+ typeof limitValue !== 'string' ||
206
+ !/^\d+$/.test(startValue) ||
207
+ !/^\d+$/.test(limitValue) ||
208
+ !Number.isSafeInteger(Number(startValue)) ||
209
+ !Number.isSafeInteger(Number(limitValue)))
210
+ throw new ApiError(400, 'Unsupported compute context pagination. Use non-negative integers for start and limit.');
211
+ const start = Number(startValue);
212
+ const limit = Number(limitValue);
213
+ const matches = contextNameFrom(request.query?.filter) === DEFAULT_CONTEXT_NAME
214
+ ? [contextBody(DEFAULT_CONTEXT_NAME, callerId(request.subject))]
215
+ : [];
207
216
  return {
208
217
  status: 200,
209
218
  body: {
210
219
  accept: 'application/json',
211
220
  name: 'contexts',
212
- start: 0,
221
+ start,
213
222
  limit,
214
- count: 1,
223
+ count: matches.length,
215
224
  version: 2,
216
- items: [
217
- contextBody(contextNameFrom(request.query?.filter), callerId(request.subject))
218
- ],
225
+ items: matches.slice(start, start + limit),
219
226
  links: linksFor('/compute/contexts', 'application/vnd.sas.compute.context', true)
220
227
  }
221
228
  };
@@ -0,0 +1,43 @@
1
+ import type { ApiResponse, Services } from '../host/dispatch.js';
2
+ import type { DriveService } from '../drive/service.js';
3
+ import type { Subject } from '../identity/types.js';
4
+ export declare const isJobDefinitionFileName: (name: string) => boolean;
5
+ type Parameter = {
6
+ name: string;
7
+ type: string;
8
+ defaultValue: string;
9
+ required: boolean;
10
+ version: number;
11
+ };
12
+ type Definition = {
13
+ id: string;
14
+ name: string;
15
+ code: string;
16
+ type: string;
17
+ parameters: Parameter[];
18
+ createdBy: string;
19
+ modifiedBy: string;
20
+ creationTimeStamp: string;
21
+ modifiedTimeStamp: string;
22
+ version: number;
23
+ links: Array<{
24
+ href: string;
25
+ uri: string;
26
+ rel: string;
27
+ method: string;
28
+ type: string;
29
+ }>;
30
+ };
31
+ /** Read only explicitly marked, well-formed records; malformed files remain ordinary files. */
32
+ export declare const definitionFromFile: (drive: DriveService, folder: string, name: string) => Promise<Definition | undefined>;
33
+ export declare const JOB_DEFINITION_HANDLERS: Record<string, (context: {
34
+ services: Services;
35
+ request: {
36
+ query?: Record<string, string | undefined>;
37
+ body?: unknown;
38
+ subject?: Subject;
39
+ };
40
+ params: Record<string, string>;
41
+ }) => Promise<ApiResponse>>;
42
+ export {};
43
+ //# sourceMappingURL=job-definitions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"job-definitions.d.ts","sourceRoot":"","sources":["../../../src/viya/job-definitions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,qBAAqB,CAAA;AAChE,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AACvD,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,sBAAsB,CAAA;AAWnD,eAAO,MAAM,uBAAuB,GAAI,MAAM,MAAM,KAAG,OACnC,CAAA;AAEpB,KAAK,SAAS,GAAG;IACf,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,YAAY,EAAE,MAAM,CAAA;IACpB,QAAQ,EAAE,OAAO,CAAA;IACjB,OAAO,EAAE,MAAM,CAAA;CAChB,CAAA;AACD,KAAK,UAAU,GAAG;IAChB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,IAAI,EAAE,MAAM,CAAA;IACZ,UAAU,EAAE,SAAS,EAAE,CAAA;IACvB,SAAS,EAAE,MAAM,CAAA;IACjB,UAAU,EAAE,MAAM,CAAA;IAClB,iBAAiB,EAAE,MAAM,CAAA;IACzB,iBAAiB,EAAE,MAAM,CAAA;IACzB,OAAO,EAAE,MAAM,CAAA;IACf,KAAK,EAAE,KAAK,CAAC;QACX,IAAI,EAAE,MAAM,CAAA;QACZ,GAAG,EAAE,MAAM,CAAA;QACX,GAAG,EAAE,MAAM,CAAA;QACX,MAAM,EAAE,MAAM,CAAA;QACd,IAAI,EAAE,MAAM,CAAA;KACb,CAAC,CAAA;CACH,CAAA;AAED,+FAA+F;AAC/F,eAAO,MAAM,kBAAkB,GAC7B,OAAO,YAAY,EACnB,QAAQ,MAAM,EACd,MAAM,MAAM,KACX,OAAO,CAAC,UAAU,GAAG,SAAS,CAuBhC,CAAA;AAOD,eAAO,MAAM,uBAAuB,EAAE,MAAM,CAC1C,MAAM,EACN,CAAC,OAAO,EAAE;IACR,QAAQ,EAAE,QAAQ,CAAA;IAClB,OAAO,EAAE;QACP,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAA;QAC1C,IAAI,CAAC,EAAE,OAAO,CAAA;QACd,OAAO,CAAC,EAAE,OAAO,CAAA;KAClB,CAAA;IACD,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAC/B,KAAK,OAAO,CAAC,WAAW,CAAC,CA+G3B,CAAA"}
@@ -0,0 +1,121 @@
1
+ import { ApiError } from '../types.js';
2
+ import { newUuidV4 } from '../uuid.js';
3
+ import { callerId, EMULATED_NOW, idFor } from './ids.js';
4
+ const prefix = '.sasjs-viya-job-';
5
+ const fileName = (id) => `${prefix}${id}.json`;
6
+ const 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$/;
7
+ export const isJobDefinitionFileName = (name) => pattern.test(name);
8
+ /** Read only explicitly marked, well-formed records; malformed files remain ordinary files. */
9
+ export const definitionFromFile = async (drive, folder, name) => {
10
+ const match = pattern.exec(name);
11
+ if (!match)
12
+ return undefined;
13
+ const { contents } = await drive.read(`${folder}/${name}`.replace(/\/{2,}/g, '/'));
14
+ if (typeof contents !== 'string')
15
+ return undefined;
16
+ try {
17
+ const value = JSON.parse(contents);
18
+ if (!value ||
19
+ value.id !== match[1] ||
20
+ typeof value.name !== 'string' ||
21
+ typeof value.code !== 'string' ||
22
+ typeof value.type !== 'string' ||
23
+ !Array.isArray(value.parameters) ||
24
+ !Array.isArray(value.links))
25
+ return undefined;
26
+ return value;
27
+ }
28
+ catch {
29
+ return undefined;
30
+ }
31
+ };
32
+ const allNodes = (root) => [
33
+ root,
34
+ ...root.children.flatMap(allNodes)
35
+ ];
36
+ export const JOB_DEFINITION_HANDLERS = {
37
+ 'POST /jobDefinitions/definitions': async ({ services, request }) => {
38
+ if (services.viya?.allowUntransactionalJobDefinitionCreation !== true)
39
+ throw new ApiError(501, 'Job definition creation requires an isolated host opt-in; Drive mutations are not transactional.');
40
+ const body = request.body;
41
+ if (!body ||
42
+ typeof body.name !== 'string' ||
43
+ !body.name ||
44
+ body.name === '.' ||
45
+ body.name === '..' ||
46
+ /[/\\\u0000-\u001f]/.test(body.name) ||
47
+ typeof body.type !== 'string' ||
48
+ typeof body.code !== 'string' ||
49
+ !Array.isArray(body.parameters))
50
+ throw new ApiError(400, 'A name, type, code and parameters are required.');
51
+ const parameters = Array.from(body.parameters, (item) => {
52
+ const param = item;
53
+ if (!param ||
54
+ typeof param.name !== 'string' ||
55
+ typeof param.type !== 'string' ||
56
+ typeof param.defaultValue !== 'string' ||
57
+ (param.required !== undefined && typeof param.required !== 'boolean'))
58
+ throw new ApiError(400, 'Invalid job parameter.');
59
+ return {
60
+ name: param.name,
61
+ type: param.type,
62
+ defaultValue: param.defaultValue,
63
+ required: param.required ?? false,
64
+ version: 1
65
+ };
66
+ });
67
+ const parent = request.query?.parentFolderUri;
68
+ const match = typeof parent === 'string'
69
+ ? parent.match(/^\/folders\/folders\/([^/]+)$/)
70
+ : undefined;
71
+ if (!match)
72
+ throw new ApiError(400, 'A parent folder URI is required.');
73
+ const drive = services.drive;
74
+ const nodes = allNodes((await drive.tree('/')).tree);
75
+ const folder = nodes.find((node) => node.isFolder && idFor(node.relativePath) === match[1]);
76
+ if (!folder)
77
+ throw new ApiError(404, 'Parent folder not found.');
78
+ const listing = await drive.list(folder.relativePath);
79
+ const existing = await Promise.all(listing.files.map((name) => definitionFromFile(drive, folder.relativePath, name)));
80
+ if (existing.some((definition) => definition?.name === body.name))
81
+ throw new ApiError(409, 'Job definition already exists.');
82
+ const id = newUuidV4();
83
+ const uri = `/jobDefinitions/definitions/${id}`;
84
+ const caller = callerId(request.subject);
85
+ const definition = {
86
+ id,
87
+ name: body.name,
88
+ type: body.type,
89
+ code: body.code,
90
+ parameters,
91
+ version: 1,
92
+ createdBy: caller,
93
+ modifiedBy: caller,
94
+ creationTimeStamp: EMULATED_NOW,
95
+ modifiedTimeStamp: EMULATED_NOW,
96
+ links: [
97
+ {
98
+ href: uri,
99
+ uri,
100
+ rel: 'self',
101
+ method: 'GET',
102
+ type: 'application/vnd.sas.job.definition'
103
+ }
104
+ ]
105
+ };
106
+ await drive.save(`${folder.relativePath}/${fileName(id)}`.replace(/\/{2,}/g, '/'), JSON.stringify(definition));
107
+ return { status: 201, body: definition };
108
+ },
109
+ 'GET /jobDefinitions/definitions/{}': async ({ services, params }) => {
110
+ const name = fileName(params.id);
111
+ if (!pattern.test(name))
112
+ throw new ApiError(404, 'Job definition not found.');
113
+ const nodes = allNodes((await services.drive.tree('/')).tree);
114
+ const node = nodes.find((item) => !item.isFolder && item.name === name);
115
+ const folder = node?.relativePath.slice(0, -(name.length + 1)) || '/';
116
+ const definition = node && (await definitionFromFile(services.drive, folder, name));
117
+ if (!definition)
118
+ throw new ApiError(404, 'Job definition not found.');
119
+ return { status: 200, body: definition };
120
+ }
121
+ };
@@ -1 +1 @@
1
- {"version":3,"file":"overlay.d.ts","sourceRoot":"","sources":["../../../src/viya/overlay.ts"],"names":[],"mappings":"AAeA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,OAAO,CAAA;IACpB,6DAA6D;IAC7D,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAuBD,eAAO,MAAM,wBAAwB,qSAC+P,CAAA;AAEpS,eAAO,MAAM,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAyEzD,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB,GAC/B,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EACzC,aAAY,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAmB,KAClD,IAcF,CAAA"}
1
+ {"version":3,"file":"overlay.d.ts","sourceRoot":"","sources":["../../../src/viya/overlay.ts"],"names":[],"mappings":"AAeA,MAAM,WAAW,gBAAgB;IAC/B,WAAW,EAAE,OAAO,CAAA;IACpB,6DAA6D;IAC7D,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB;AAgBD,eAAO,MAAM,wBAAwB,qSAC+P,CAAA;AAEpS,eAAO,MAAM,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE,gBAAgB,CA+DzD,CAAA;AAED;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB,GAC/B,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EACzC,aAAY,KAAK,CAAC;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAmB,KAClD,IAcF,CAAA"}