@sasjs/api 0.35.0 → 0.37.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.
Files changed (46) hide show
  1. package/build/browser.js +616 -64
  2. package/build/cjs/viya/compute.js +280 -0
  3. package/build/cjs/viya/declared.js +38 -0
  4. package/build/cjs/viya/dispatch.js +3 -3
  5. package/build/cjs/viya/files.js +199 -0
  6. package/build/cjs/viya/ids.js +60 -0
  7. package/build/cjs/viya/overlay.js +20 -43
  8. package/build/cjs/viya/ports.js +5 -0
  9. package/build/cjs/viya/seed.js +120 -0
  10. package/build/cjs/viya/service.js +51 -85
  11. package/build/cjs/viya/sessions.js +115 -0
  12. package/build/cjs/viya/unrecorded.js +0 -4
  13. package/build/esm/host/dispatch.d.ts +10 -0
  14. package/build/esm/host/dispatch.d.ts.map +1 -1
  15. package/build/esm/viya/compute.d.ts +39 -0
  16. package/build/esm/viya/compute.d.ts.map +1 -0
  17. package/build/esm/viya/compute.js +276 -0
  18. package/build/esm/viya/declared.d.ts +25 -0
  19. package/build/esm/viya/declared.d.ts.map +1 -0
  20. package/build/esm/viya/declared.js +35 -0
  21. package/build/esm/viya/dispatch.d.ts +1 -1
  22. package/build/esm/viya/dispatch.d.ts.map +1 -1
  23. package/build/esm/viya/dispatch.js +3 -3
  24. package/build/esm/viya/files.d.ts +33 -0
  25. package/build/esm/viya/files.d.ts.map +1 -0
  26. package/build/esm/viya/files.js +196 -0
  27. package/build/esm/viya/ids.d.ts +35 -0
  28. package/build/esm/viya/ids.d.ts.map +1 -0
  29. package/build/esm/viya/ids.js +55 -0
  30. package/build/esm/viya/overlay.d.ts.map +1 -1
  31. package/build/esm/viya/overlay.js +20 -43
  32. package/build/esm/viya/ports.d.ts +12 -0
  33. package/build/esm/viya/ports.d.ts.map +1 -0
  34. package/build/esm/viya/ports.js +1 -0
  35. package/build/esm/viya/seed.d.ts +97 -0
  36. package/build/esm/viya/seed.d.ts.map +1 -0
  37. package/build/esm/viya/seed.js +111 -0
  38. package/build/esm/viya/service.d.ts +0 -16
  39. package/build/esm/viya/service.d.ts.map +1 -1
  40. package/build/esm/viya/service.js +10 -43
  41. package/build/esm/viya/sessions.d.ts +78 -0
  42. package/build/esm/viya/sessions.d.ts.map +1 -0
  43. package/build/esm/viya/sessions.js +109 -0
  44. package/build/esm/viya/unrecorded.d.ts.map +1 -1
  45. package/build/esm/viya/unrecorded.js +0 -4
  46. package/package.json +3 -2
@@ -14,15 +14,7 @@ exports.assertOverlayEntries = exports.VIYA_OVERLAY = void 0;
14
14
  * A declined row is not a TODO. The reason names what is missing, so a caller
15
15
  * that reaches it learns why rather than that something is unimplemented.
16
16
  */
17
- const table_js_1 = require("./table.js");
18
- /**
19
- * The reason the session and file families carry.
20
- *
21
- * They need the session port and the file content routes, which this slice does
22
- * not mount. Saying it once is better than saying it thirteen times in slightly
23
- * different words.
24
- */
25
- const NEEDS_RUNTIME = 'The emulated estate answers folders, identities and types today. This operation needs the session or file port, which the host mounting the emulator has not supplied.';
17
+ const declared_js_1 = require("./declared.js");
26
18
  /**
27
19
  * The token endpoint is the host's.
28
20
  *
@@ -41,40 +33,25 @@ exports.VIYA_OVERLAY = {
41
33
  'GET /folders/folders/@myRecycleBin': { implemented: true },
42
34
  'GET /identities/users/@currentUser': { implemented: true },
43
35
  'GET /types/types': { implemented: true },
44
- // declined: the session and file ports
45
- 'GET /compute/contexts': { implemented: false, reason: NEEDS_RUNTIME },
46
- 'POST /compute/contexts/{}/sessions': {
47
- implemented: false,
48
- reason: NEEDS_RUNTIME
49
- },
50
- 'DELETE /compute/sessions/{}': { implemented: false, reason: NEEDS_RUNTIME },
51
- 'POST /compute/sessions/{}/jobs': {
52
- implemented: false,
53
- reason: NEEDS_RUNTIME
54
- },
55
- 'GET /compute/sessions/{}/jobs/{}': {
56
- implemented: false,
57
- reason: NEEDS_RUNTIME
58
- },
59
- 'GET /compute/sessions/{}/jobs/{}/log/content': {
60
- implemented: false,
61
- reason: NEEDS_RUNTIME
62
- },
63
- 'GET /compute/sessions/{}/jobs/{}/state': {
64
- implemented: false,
65
- reason: NEEDS_RUNTIME
66
- },
67
- 'GET /compute/sessions/{}/state': {
68
- implemented: false,
69
- reason: NEEDS_RUNTIME
70
- },
71
- 'POST /files/files': { implemented: false, reason: NEEDS_RUNTIME },
72
- 'GET /files/files/{}': { implemented: false, reason: NEEDS_RUNTIME },
73
- 'PATCH /files/files/{}': { implemented: false, reason: NEEDS_RUNTIME },
74
- 'GET /files/files/{}/content': { implemented: false, reason: NEEDS_RUNTIME },
75
- 'PUT /files/files/{}/content': { implemented: false, reason: NEEDS_RUNTIME },
36
+ // answered here: compute
37
+ 'GET /compute/contexts': { implemented: true },
38
+ 'POST /compute/contexts/{}/sessions': { implemented: true },
39
+ 'DELETE /compute/sessions/{}': { implemented: true },
40
+ 'POST /compute/sessions/{}/jobs': { implemented: true },
41
+ 'GET /compute/sessions/{}/jobs/{}': { implemented: true },
42
+ 'GET /compute/sessions/{}/jobs/{}/log/content': { implemented: true },
43
+ 'GET /compute/sessions/{}/jobs/{}/state': { implemented: true },
44
+ 'GET /compute/sessions/{}/state': { implemented: true },
45
+ // answered here: files
46
+ 'POST /files/files': { implemented: true },
47
+ 'GET /files/files/{}': { implemented: true },
48
+ 'PATCH /files/files/{}': { implemented: true },
49
+ 'GET /files/files/{}/content': { implemented: true },
50
+ 'PUT /files/files/{}/content': { implemented: true },
76
51
  // declined: the host owns the token port
77
- 'POST /SASLogon/oauth/token': { implemented: false, reason: NEEDS_AUTH }
52
+ 'POST /SASLogon/oauth/token': { implemented: false, reason: NEEDS_AUTH },
53
+ // declared, not captured: the webout an application's service returns
54
+ 'GET /compute/sessions/{}/filerefs/_webout/content': { implemented: true }
78
55
  };
79
56
  /**
80
57
  * Refuse an overlay and a table that do not describe the same operations.
@@ -91,7 +68,7 @@ exports.VIYA_OVERLAY = {
91
68
  * Called at import, and exported so the refusals themselves can be tested: a
92
69
  * check that only runs on import is a check nothing can pin.
93
70
  */
94
- const assertOverlayEntries = (overlay, operations = table_js_1.VIYA_TABLE) => {
71
+ const assertOverlayEntries = (overlay, operations = declared_js_1.VIYA_OPERATIONS) => {
95
72
  const known = new Set(operations.map((operation) => operation.id));
96
73
  for (const id of Object.keys(overlay))
97
74
  if (!known.has(id))
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.requireDrive = void 0;
4
+ const requireDrive = (services) => services.drive;
5
+ exports.requireDrive = requireDrive;
@@ -0,0 +1,120 @@
1
+ "use strict";
2
+ /**
3
+ * What the emulated estate derives its generated data from.
4
+ *
5
+ * The emulator cannot execute SAS, so any answer that a real engine would produce
6
+ * - a job log, a listing, a webout - is generated. Generated data is only useful
7
+ * if it is the same data twice: a screenshot taken after a build must still be
8
+ * true after the next one, and a fixture committed today must match the answer
9
+ * tomorrow.
10
+ *
11
+ * The seed is therefore the identity of the estate, and the identity of an estate
12
+ * is the address clients already use to reach it. A target that points at
13
+ * `http://localhost:5000` and a target that points at `http://127.0.0.1:5000` are
14
+ * the same estate spelled two ways, so the address is normalised before it is
15
+ * hashed - and `seed` exists for the two cases where the address is the wrong
16
+ * identity: the estate reached by a different hostname (a container name, a LAN
17
+ * address), and the port that moves between runs (CI picks an ephemeral one).
18
+ *
19
+ * Absent both, every emulated estate shares one seed. That is the only honest
20
+ * default: an emulator with no address has not told us which estate it is.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.drawFrom = exports.drawInt = exports.generator = exports.seedOf = exports.hash = exports.normaliseServerUrl = exports.DEFAULT_SEED = void 0;
24
+ /** The seed every emulated estate falls back to. */
25
+ exports.DEFAULT_SEED = 'emulated';
26
+ /**
27
+ * The address reduced to what identifies it.
28
+ *
29
+ * Lowercased host, no default port, no trailing slash, no path: `https://Viya.Example.com:443/SASDrive/`
30
+ * and `https://viya.example.com` are one estate, and a path is where a client
31
+ * lands rather than which server it is. A non-default port stays, because two
32
+ * emulators on one machine are two estates.
33
+ */
34
+ const normaliseServerUrl = (url) => {
35
+ if (!url)
36
+ return '';
37
+ const trimmed = url.trim();
38
+ if (!trimmed)
39
+ return '';
40
+ // parsed by hand rather than with `new URL`, because the browser build has no
41
+ // URL global and this module is part of it
42
+ const match = /^(?:([a-z][a-z0-9+.-]*):\/\/)?([^/?#]+)/i.exec(trimmed);
43
+ if (!match)
44
+ return trimmed.replace(/\/+$/, '').toLowerCase();
45
+ const scheme = (match[1] ?? 'http').toLowerCase();
46
+ let authority = match[2].toLowerCase();
47
+ const credentials = authority.lastIndexOf('@');
48
+ if (credentials >= 0)
49
+ authority = authority.slice(credentials + 1);
50
+ let host = authority;
51
+ let port = '';
52
+ if (authority.startsWith('[')) {
53
+ const close = authority.indexOf(']');
54
+ if (close >= 0) {
55
+ host = authority.slice(0, close + 1);
56
+ if (authority[close + 1] === ':')
57
+ port = authority.slice(close + 2);
58
+ }
59
+ }
60
+ else {
61
+ const colon = authority.lastIndexOf(':');
62
+ if (colon >= 0) {
63
+ host = authority.slice(0, colon);
64
+ port = authority.slice(colon + 1);
65
+ }
66
+ }
67
+ const isDefault = (scheme === 'http' && port === '80') ||
68
+ (scheme === 'https' && port === '443');
69
+ // a non-default port stays: two emulators on one machine are two estates
70
+ return `${scheme}://${host}${port && !isDefault ? `:${port}` : ''}`;
71
+ };
72
+ exports.normaliseServerUrl = normaliseServerUrl;
73
+ /** A 32-bit FNV-1a hash, so one string becomes one number. */
74
+ const hash = (input) => {
75
+ let value = 2166136261;
76
+ for (let index = 0; index < input.length; index++) {
77
+ value ^= input.charCodeAt(index);
78
+ value = Math.imul(value, 16777619) >>> 0;
79
+ }
80
+ return value >>> 0;
81
+ };
82
+ exports.hash = hash;
83
+ /**
84
+ * The number that makes this estate's generated data reproducible.
85
+ *
86
+ * `seed` wins over the address when both are present: it is the override a host
87
+ * reaches for when the address disagrees with the estate, not a second opinion
88
+ * the address gets to overrule.
89
+ */
90
+ const seedOf = (settings = {}) => {
91
+ if (settings.seed !== undefined && settings.seed !== '')
92
+ return (0, exports.hash)(`seed:${settings.seed}`);
93
+ const address = (0, exports.normaliseServerUrl)(settings.serverUrl);
94
+ return (0, exports.hash)(`url:${address || exports.DEFAULT_SEED}`);
95
+ };
96
+ exports.seedOf = seedOf;
97
+ /**
98
+ * A uniform generator over one seed (mulberry32).
99
+ *
100
+ * Every draw advances the same 32-bit state, so a sequence is a function of the
101
+ * seed alone - which is the whole point: the same estate answers the same way,
102
+ * and two estates answer differently.
103
+ */
104
+ const generator = (seed) => {
105
+ let state = seed >>> 0;
106
+ return () => {
107
+ state = (state + 0x6d2b79f5) >>> 0;
108
+ let value = state;
109
+ value = Math.imul(value ^ (value >>> 15), value | 1);
110
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
111
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
112
+ };
113
+ };
114
+ exports.generator = generator;
115
+ /** An integer in `[0, bound)`, drawn from the generator. */
116
+ const drawInt = (next, bound) => Math.floor(next() * bound);
117
+ exports.drawInt = drawInt;
118
+ /** A line from a list, drawn from the generator. */
119
+ const drawFrom = (next, values) => values[(0, exports.drawInt)(next, values.length)];
120
+ exports.drawFrom = drawFrom;
@@ -1,42 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.VIYA_HANDLERS = exports.idFor = exports.EMULATED_USER = exports.EMULATED_NOW = void 0;
3
+ exports.VIYA_HANDLERS = void 0;
4
4
  const types_js_1 = require("../types.js");
5
- /** The emulated clock: a fixed instant, so a body is reproducible. */
6
- exports.EMULATED_NOW = '2026-01-01T00:00:00.000Z';
7
- /** The caller the emulated estate reports when a host does not name one. */
8
- exports.EMULATED_USER = { id: 'emulated-user', name: 'Emulated User' };
9
- /**
10
- * A uuid shape from a string, deterministically.
11
- *
12
- * Two 32-bit FNV-1a passes give enough of a hash to fill a uuid's fields, and the
13
- * version/variant nibbles are set so the result is a well-formed v4-shaped id.
14
- * Collisions are possible in principle and irrelevant here: the id is a handle
15
- * the emulator hands back, not a uniqueness guarantee.
16
- */
17
- const idFor = (path, kind = 'folder') => {
18
- const hash = (input, seed) => {
19
- let value = seed;
20
- for (let index = 0; index < input.length; index++) {
21
- value ^= input.charCodeAt(index);
22
- value = Math.imul(value, 16777619) >>> 0;
23
- }
24
- return value.toString(16).padStart(8, '0');
25
- };
26
- const raw = hash(`${kind}:${path}`, 2166136261) +
27
- hash(`${kind}:${path}`, 2246822519) +
28
- hash(`${kind}:${path}`, 3266489917) +
29
- hash(`${kind}:${path}`, 668265263);
30
- const hex = raw.slice(0, 32);
31
- return [
32
- hex.slice(0, 8),
33
- hex.slice(8, 12),
34
- `4${hex.slice(13, 16)}`,
35
- `a${hex.slice(17, 20)}`,
36
- hex.slice(20, 32)
37
- ].join('-');
38
- };
39
- exports.idFor = idFor;
5
+ const ports_js_1 = require("./ports.js");
6
+ const compute_js_1 = require("./compute.js");
7
+ const files_js_1 = require("./files.js");
8
+ const ids_js_1 = require("./ids.js");
40
9
  const linksFor = (uri, collection = false) => {
41
10
  const self = {
42
11
  href: uri,
@@ -59,7 +28,7 @@ const linksFor = (uri, collection = false) => {
59
28
  };
60
29
  const folderBody = async (drive, path) => {
61
30
  const listing = await drive.list(path);
62
- const id = (0, exports.idFor)(path);
31
+ const id = (0, ids_js_1.idFor)(path);
63
32
  const name = path.split('/').filter(Boolean).pop() ?? '';
64
33
  const parent = path.split('/').slice(0, -1).join('/') || '/';
65
34
  return {
@@ -68,49 +37,44 @@ const folderBody = async (drive, path) => {
68
37
  description: '',
69
38
  type: 'folder',
70
39
  version: 1,
71
- createdBy: exports.EMULATED_USER.id,
72
- modifiedBy: exports.EMULATED_USER.id,
73
- creationTimeStamp: exports.EMULATED_NOW,
74
- modifiedTimeStamp: exports.EMULATED_NOW,
40
+ createdBy: ids_js_1.EMULATED_USER.id,
41
+ modifiedBy: ids_js_1.EMULATED_USER.id,
42
+ creationTimeStamp: ids_js_1.EMULATED_NOW,
43
+ modifiedTimeStamp: ids_js_1.EMULATED_NOW,
75
44
  memberCount: listing.files.length + listing.folders.length,
76
- parentFolderUri: `/folders/folders/${(0, exports.idFor)(parent)}`,
45
+ parentFolderUri: `/folders/folders/${(0, ids_js_1.idFor)(parent)}`,
77
46
  links: linksFor(`/folders/folders/${id}`)
78
47
  };
79
48
  };
80
49
  const recycleBin = () => {
81
50
  const path = '@myRecycleBin';
82
- const id = (0, exports.idFor)(path);
51
+ const id = (0, ids_js_1.idFor)(path);
83
52
  return {
84
53
  id,
85
54
  name: 'Recycle Bin',
86
55
  description: 'Recycle Bin',
87
56
  type: 'trashFolder',
88
57
  version: 1,
89
- createdBy: exports.EMULATED_USER.id,
90
- modifiedBy: exports.EMULATED_USER.id,
91
- creationTimeStamp: exports.EMULATED_NOW,
92
- modifiedTimeStamp: exports.EMULATED_NOW,
58
+ createdBy: ids_js_1.EMULATED_USER.id,
59
+ modifiedBy: ids_js_1.EMULATED_USER.id,
60
+ creationTimeStamp: ids_js_1.EMULATED_NOW,
61
+ modifiedTimeStamp: ids_js_1.EMULATED_NOW,
93
62
  memberCount: 0,
94
63
  parentFolderUri: '',
95
64
  properties: { allowMove: 'false' },
96
65
  links: linksFor(`/folders/folders/${id}`)
97
66
  };
98
67
  };
99
- const requireDrive = (services) => {
100
- if (!services.drive)
101
- throw new types_js_1.ApiError(501, 'This host has no drive, so it cannot answer a folder operation.');
102
- return services.drive;
103
- };
104
68
  const pathFromQuery = (request) => {
105
69
  const path = request.query?.path;
106
70
  if (!path)
107
71
  throw new types_js_1.ApiError(400, 'The path parameter is required.');
108
- return path;
72
+ return (0, ids_js_1.normalisePath)(path);
109
73
  };
110
74
  /** The recycle-bin alias the emulator answers, which is also a valid parent. */
111
75
  const RECYCLE_BIN_ALIAS = '/folders/folders/@myRecycleBin';
112
76
  const isRecycleBin = (uri) => !!uri &&
113
- (uri === RECYCLE_BIN_ALIAS || uri.endsWith(`/${(0, exports.idFor)('@myRecycleBin')}`));
77
+ (uri === RECYCLE_BIN_ALIAS || uri.endsWith(`/${(0, ids_js_1.idFor)('@myRecycleBin')}`));
114
78
  /**
115
79
  * The path a folder id stands for, found by walking the drive.
116
80
  *
@@ -121,7 +85,7 @@ const isRecycleBin = (uri) => !!uri &&
121
85
  */
122
86
  const pathForId = async (drive, id) => {
123
87
  const walk = (node) => {
124
- if (node.isFolder && (0, exports.idFor)(node.relativePath) === id)
88
+ if (node.isFolder && (0, ids_js_1.idFor)(node.relativePath) === id)
125
89
  return node.relativePath;
126
90
  for (const child of node.children) {
127
91
  const hit = walk(child);
@@ -141,12 +105,12 @@ exports.VIYA_HANDLERS = {
141
105
  'GET /identities/users/@currentUser': async ({ services, request }) => {
142
106
  const subject = request.subject ??
143
107
  (await services.identity?.authenticate(request.token));
144
- const id = subject?.userId ?? exports.EMULATED_USER.id;
108
+ const id = subject?.userId ?? ids_js_1.EMULATED_USER.id;
145
109
  return {
146
110
  status: 200,
147
111
  body: {
148
112
  id,
149
- name: subject?.userId ?? exports.EMULATED_USER.name,
113
+ name: subject?.userId ?? ids_js_1.EMULATED_USER.name,
150
114
  providerId: 'sas',
151
115
  state: 'active',
152
116
  version: 1,
@@ -180,7 +144,7 @@ exports.VIYA_HANDLERS = {
180
144
  }),
181
145
  'GET /folders/folders/@item': async ({ services, request }) => ({
182
146
  status: 200,
183
- body: await folderBody(requireDrive(services), pathFromQuery(request))
147
+ body: await folderBody((0, ports_js_1.requireDrive)(services), pathFromQuery(request))
184
148
  }),
185
149
  'GET /folders/folders/@myRecycleBin': async () => ({
186
150
  status: 200,
@@ -188,20 +152,20 @@ exports.VIYA_HANDLERS = {
188
152
  }),
189
153
  'GET /folders/folders/{}': async ({ services, params }) => {
190
154
  // the bin is addressed by id too, and it is not in the drive's tree
191
- if (params.id === (0, exports.idFor)('@myRecycleBin'))
155
+ if (params.id === (0, ids_js_1.idFor)('@myRecycleBin'))
192
156
  return { status: 200, body: recycleBin() };
193
- const drive = requireDrive(services);
157
+ const drive = (0, ports_js_1.requireDrive)(services);
194
158
  return {
195
159
  status: 200,
196
160
  body: await folderBody(drive, await pathForId(drive, params.id))
197
161
  };
198
162
  },
199
163
  'GET /folders/folders/{}/members': async ({ services, params, request }) => {
200
- const drive = requireDrive(services);
164
+ const drive = (0, ports_js_1.requireDrive)(services);
201
165
  const limit = Number(request.query?.limit ?? 0) || 0;
202
166
  // the bin is not a folder in the drive, and its own body advertises this
203
167
  // link - so a client following the answer it just received must not 404
204
- if (params.id === (0, exports.idFor)('@myRecycleBin'))
168
+ if (params.id === (0, ids_js_1.idFor)('@myRecycleBin'))
205
169
  return {
206
170
  status: 200,
207
171
  body: {
@@ -214,39 +178,39 @@ exports.VIYA_HANDLERS = {
214
178
  count: 0,
215
179
  version: 2,
216
180
  items: [],
217
- links: linksFor(`/folders/folders/${(0, exports.idFor)('@myRecycleBin')}`, true)
181
+ links: linksFor(`/folders/folders/${(0, ids_js_1.idFor)('@myRecycleBin')}`, true)
218
182
  }
219
183
  };
220
184
  const path = await pathForId(drive, params.id);
221
185
  const listing = await drive.list(path);
222
186
  const items = [
223
187
  ...listing.folders.map((name) => ({
224
- id: (0, exports.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/')),
188
+ id: (0, ids_js_1.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/')),
225
189
  name,
226
190
  type: 'folder',
227
191
  version: 1,
228
- createdBy: exports.EMULATED_USER.id,
229
- modifiedBy: exports.EMULATED_USER.id,
230
- creationTimeStamp: exports.EMULATED_NOW,
231
- modifiedTimeStamp: exports.EMULATED_NOW,
232
- parentFolderUri: `/folders/folders/${(0, exports.idFor)(path)}`,
192
+ createdBy: ids_js_1.EMULATED_USER.id,
193
+ modifiedBy: ids_js_1.EMULATED_USER.id,
194
+ creationTimeStamp: ids_js_1.EMULATED_NOW,
195
+ modifiedTimeStamp: ids_js_1.EMULATED_NOW,
196
+ parentFolderUri: `/folders/folders/${(0, ids_js_1.idFor)(path)}`,
233
197
  uri: `${path}/${name}`.replace(/\/{2,}/g, '/'),
234
- links: linksFor(`/folders/folders/${(0, exports.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'))}`)
198
+ links: linksFor(`/folders/folders/${(0, ids_js_1.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'))}`)
235
199
  })),
236
200
  ...listing.files.map((name) => ({
237
- id: (0, exports.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'), 'file'),
201
+ id: (0, ids_js_1.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'), 'file'),
238
202
  name,
239
203
  type: 'file',
240
204
  version: 1,
241
205
  contentType: 'text/plain',
242
- createdBy: exports.EMULATED_USER.id,
243
- modifiedBy: exports.EMULATED_USER.id,
244
- creationTimeStamp: exports.EMULATED_NOW,
245
- modifiedTimeStamp: exports.EMULATED_NOW,
246
- parentFolderUri: `/folders/folders/${(0, exports.idFor)(path)}`,
247
- added: exports.EMULATED_NOW,
206
+ createdBy: ids_js_1.EMULATED_USER.id,
207
+ modifiedBy: ids_js_1.EMULATED_USER.id,
208
+ creationTimeStamp: ids_js_1.EMULATED_NOW,
209
+ modifiedTimeStamp: ids_js_1.EMULATED_NOW,
210
+ parentFolderUri: `/folders/folders/${(0, ids_js_1.idFor)(path)}`,
211
+ added: ids_js_1.EMULATED_NOW,
248
212
  uri: `${path}/${name}`.replace(/\/{2,}/g, '/'),
249
- links: linksFor(`/files/files/${(0, exports.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'), 'file')}`)
213
+ links: linksFor(`/files/files/${(0, ids_js_1.idFor)(`${path}/${name}`.replace(/\/{2,}/g, '/'), 'file')}`)
250
214
  }))
251
215
  ];
252
216
  const page = limit > 0 ? items.slice(0, limit) : items;
@@ -262,12 +226,12 @@ exports.VIYA_HANDLERS = {
262
226
  count: page.length,
263
227
  version: 2,
264
228
  items: page,
265
- links: linksFor(`/folders/folders/${(0, exports.idFor)(path)}`, true)
229
+ links: linksFor(`/folders/folders/${(0, ids_js_1.idFor)(path)}`, true)
266
230
  }
267
231
  };
268
232
  },
269
233
  'POST /folders/folders': async ({ services, request }) => {
270
- const drive = requireDrive(services);
234
+ const drive = (0, ports_js_1.requireDrive)(services);
271
235
  const body = (request.body ?? {});
272
236
  if (!body.name)
273
237
  throw new types_js_1.ApiError(400, 'A folder name is required.');
@@ -277,13 +241,13 @@ exports.VIYA_HANDLERS = {
277
241
  const parent = parentUri
278
242
  ? await pathForId(drive, String(parentUri).split('/').pop())
279
243
  : '/';
280
- const path = `${parent}/${body.name}`.replace(/\/{2,}/g, '/');
244
+ const path = (0, ids_js_1.normalisePath)(`${parent}/${body.name}`);
281
245
  await drive.mkdir(path);
282
246
  return { status: 201, body: await folderBody(drive, path) };
283
247
  },
284
248
  'PATCH /folders/folders/{}': async ({ services, request, params }) => {
285
- const drive = requireDrive(services);
286
- if (params.id === (0, exports.idFor)('@myRecycleBin'))
249
+ const drive = (0, ports_js_1.requireDrive)(services);
250
+ if (params.id === (0, ids_js_1.idFor)('@myRecycleBin'))
287
251
  throw new types_js_1.ApiError(400, 'The recycle bin cannot be moved or renamed.');
288
252
  const path = await pathForId(drive, params.id);
289
253
  const body = (request.body ?? {});
@@ -309,9 +273,11 @@ exports.VIYA_HANDLERS = {
309
273
  : body.parentFolderUri === ''
310
274
  ? '/'
311
275
  : await pathForId(drive, body.parentFolderUri.split('/').pop());
312
- const target = `${parent}/${name}`.replace(/\/{2,}/g, '/');
276
+ const target = (0, ids_js_1.normalisePath)(`${parent}/${name}`);
313
277
  if (target !== path)
314
278
  await drive.rename(path, target);
315
279
  return { status: 200, body: await folderBody(drive, target) };
316
- }
280
+ },
281
+ ...compute_js_1.COMPUTE_HANDLERS,
282
+ ...files_js_1.FILE_HANDLERS
317
283
  };
@@ -0,0 +1,115 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.estateFor = exports.EmulatedEstate = exports.logFor = void 0;
4
+ /**
5
+ * The emulated compute estate: sessions, jobs and the logs generated for them.
6
+ *
7
+ * A session is a handle a client keeps and asks about later, so it lives in the
8
+ * process that issued it - the way a real compute server's does - and it survives
9
+ * as long as the emulator does. Ids are a function of the seed and a counter
10
+ * rather than a random uuid: a session id that changes between runs would break
11
+ * every fixture that names one, which is the same rule as a folder id.
12
+ *
13
+ * Nothing here executes SAS. The engine is not present, and a log that claimed to
14
+ * be output would be a lie the first time somebody read it. The log echoes what
15
+ * was submitted and states, in the log itself, that it is generated - so a client
16
+ * that parses for NOTEs still gets a well-formed log, and a person reading it is
17
+ * not misled about what ran.
18
+ */
19
+ const seed_js_1 = require("./seed.js");
20
+ /**
21
+ * The generated log for one program.
22
+ *
23
+ * Deterministic in (seed, code): the same program on the same estate answers the
24
+ * same lines, so a test can assert a log and a screenshot stays true. The numbers
25
+ * are drawn rather than fixed so that two estates do not look identical, and the
26
+ * generator is re-seeded from the code for each job so that one job's log does not
27
+ * depend on how many jobs ran before it.
28
+ */
29
+ const logFor = (seed, program) => {
30
+ const code = Array.isArray(program) ? program.join('\n') : program;
31
+ // seeded from the program's TEXT, not its length: two programs of the same
32
+ // length are two programs, and a fixture that names the numbers would be
33
+ // right for both of them otherwise
34
+ const next = (0, seed_js_1.generator)(seed ^ (0, seed_js_1.hash)(`code:${code}`));
35
+ const rows = (0, seed_js_1.drawInt)(next, 900) + 100;
36
+ const seconds = ((0, seed_js_1.drawInt)(next, 90) + 10) / 100;
37
+ const lines = code
38
+ .split('\n')
39
+ .map((line, index) => `${String(index + 1).padStart(3, ' ')} ${line}`);
40
+ return [
41
+ 'NOTE: Emulated compute engine - this log is generated, not produced by SAS.',
42
+ 'NOTE: No library was touched: the emulated engine has none.',
43
+ ...lines,
44
+ `NOTE: The data set WORK.EMULATED has ${rows} observations and 3 variables.`,
45
+ `NOTE: DATA statement used (Total process time):`,
46
+ `NOTE: real time ${seconds.toFixed(2)} seconds`,
47
+ `NOTE: user cpu time ${(seconds / 2).toFixed(2)} seconds`,
48
+ `NOTE: ${(0, seed_js_1.drawFrom)(next, ['The emulated run completed.', 'Emulation complete - no SAS was executed.'])}`
49
+ ];
50
+ };
51
+ exports.logFor = logFor;
52
+ /**
53
+ * The sessions one estate holds.
54
+ *
55
+ * Keyed by seed, so two emulated estates in one process - a test that runs two
56
+ * targets - do not share a session namespace.
57
+ */
58
+ class EmulatedEstate {
59
+ constructor(seed) {
60
+ this.seed = seed;
61
+ this.sessions = new Map();
62
+ this.created = 0;
63
+ }
64
+ /** A new session: deterministic id, no jobs. */
65
+ create() {
66
+ const session = {
67
+ id: `emulated-${this.seed.toString(16)}-ses${String(this.created++).padStart(4, '0')}`,
68
+ createdAt: new Date().toISOString(),
69
+ jobs: new Map(),
70
+ submitted: 0
71
+ };
72
+ this.sessions.set(session.id, session);
73
+ return session;
74
+ }
75
+ session(id) {
76
+ return this.sessions.get(id);
77
+ }
78
+ remove(id) {
79
+ return this.sessions.delete(id);
80
+ }
81
+ /** A job accepted into a session, with the log the emulator generated for it. */
82
+ submit(session, job) {
83
+ const id = `${session.id}-job${String(session.submitted++).padStart(4, '0')}`;
84
+ const code = job.code ?? '';
85
+ const submitted = {
86
+ id,
87
+ name: job.name ?? id,
88
+ // the log is a function of the seed and the program alone, so the same
89
+ // program answers the same lines whatever session it was submitted in
90
+ log: (0, exports.logFor)(this.seed, code),
91
+ state: 'running',
92
+ // the real clock, unlike a folder's: a client computes a session's age
93
+ // from this stamp and expires it, so a fixed instant in the past is a
94
+ // session that is born expired
95
+ creationTimeStamp: new Date().toISOString(),
96
+ // no completion stamp here: a job is finished when something finished it,
97
+ // and the handler that knows whether anything will run sets both
98
+ sessionId: session.id
99
+ };
100
+ session.jobs.set(id, submitted);
101
+ return submitted;
102
+ }
103
+ }
104
+ exports.EmulatedEstate = EmulatedEstate;
105
+ /** One estate per seed, for the life of the process. */
106
+ const estates = new Map();
107
+ const estateFor = (seed) => {
108
+ const existing = estates.get(seed);
109
+ if (existing)
110
+ return existing;
111
+ const estate = new EmulatedEstate(seed);
112
+ estates.set(seed, estate);
113
+ return estate;
114
+ };
115
+ exports.estateFor = estateFor;
@@ -30,10 +30,6 @@ exports.UNRECORDED = [
30
30
  reason: 'no capture: the authorisation-code step needs a browser; the pass uses the password grant'
31
31
  },
32
32
  // Compute operations the scripted passes do not reach.
33
- {
34
- path: '/compute/sessions/{}/filerefs/_webout/content',
35
- reason: 'no capture: the adapter reads the webout fileref only when a run expects one (`expectWebout`); the execute pass submits a `%put` and reads the log'
36
- },
37
33
  {
38
34
  path: '/compute/sessions/{}/variables/{}',
39
35
  reason: "no capture: the adapter reads a session variable only to report a submitted job's pid (`printPid`), which the pass does not set"
@@ -2,6 +2,7 @@ import type { DriveService } from '../drive/service.js';
2
2
  import type { IdentityService } from '../identity/service.js';
3
3
  import type { RecordService } from '../identity/records.js';
4
4
  import type { SessionService } from '../session/service.js';
5
+ import type { ViyaSeedSettings } from '../viya/seed.js';
5
6
  import type { RuntimeService } from '../runtime/service.js';
6
7
  import type { AppStreamService } from '../appstream/service.js';
7
8
  import type { CodeService } from '../code/service.js';
@@ -94,6 +95,15 @@ export interface Services {
94
95
  * answers 501 for these four, naming the capability.
95
96
  */
96
97
  session?: SessionService;
98
+ /**
99
+ * The emulated Viya estate this host mounts, when it mounts one.
100
+ *
101
+ * Absent, the emulated answers fall back to one shared seed. The address is what
102
+ * identifies an estate, so `serverUrl` is the seed unless `seed` overrides it -
103
+ * which a host does when the port moves between runs or the estate answers on a
104
+ * second hostname.
105
+ */
106
+ viya?: ViyaSeedSettings;
97
107
  /**
98
108
  * The execute and trigger routes, over the host's runner. Absent, they answer
99
109
  * 501: the package can decide everything about a run except performing it.
@@ -1 +1 @@
1
- {"version":3,"file":"dispatch.d.ts","sourceRoot":"","sources":["../../../src/host/dispatch.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AACvD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAA;AAC7D,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAA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