@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
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.COMPUTE_HANDLERS = exports.contextNameFrom = exports.EMULATED_CONTEXT_ID = exports.DEFAULT_CONTEXT_NAME = void 0;
4
+ const types_js_1 = require("../types.js");
5
+ const seed_js_1 = require("./seed.js");
6
+ const seed_js_2 = require("./seed.js");
7
+ const sessions_js_1 = require("./sessions.js");
8
+ const ids_js_1 = require("./ids.js");
9
+ /** The name the emulator answers when a client asks for no particular context. */
10
+ exports.DEFAULT_CONTEXT_NAME = 'Emulated Compute Context';
11
+ /** The one context id this estate mints, whatever name it is asked for. */
12
+ exports.EMULATED_CONTEXT_ID = (0, ids_js_1.idFor)('emulated-context', 'context');
13
+ /**
14
+ * The links a client follows, by rel.
15
+ *
16
+ * The rels are not decoration: the adapter reads `state` to poll a session and a
17
+ * job, `log` to fetch the log, `up` to reach the session from a job. A body that
18
+ * carried only `self` answered 201 and then failed the client, which is how the
19
+ * conformance harness found this.
20
+ */
21
+ const relLinks = (type, rels) => rels.map(([rel, href]) => ({ href, uri: href, rel, method: 'GET', type }));
22
+ const linksFor = (uri, type, collection = false, itemType = false) => [
23
+ // the collection link comes first, because that is the order the capture
24
+ // recorded and the item shape assertion walks the first element
25
+ ...(collection
26
+ ? [
27
+ {
28
+ href: `${uri}/members`,
29
+ uri: `${uri}/members`,
30
+ rel: 'members',
31
+ method: 'GET',
32
+ type,
33
+ itemType: type
34
+ }
35
+ ]
36
+ : []),
37
+ {
38
+ href: uri,
39
+ uri,
40
+ rel: 'self',
41
+ method: 'GET',
42
+ type,
43
+ // the log's capture records itemType on its first link, so it is stamped
44
+ // there rather than invented as a members link the estate does not have
45
+ ...(itemType ? { itemType: type } : {})
46
+ }
47
+ ];
48
+ const estateOf = (services) => (0, sessions_js_1.estateFor)((0, seed_js_2.seedOf)(services.viya));
49
+ /**
50
+ * The context name a client asked for.
51
+ *
52
+ * The adapter filters by name (`filter=eq(name,'X')`), so the answer is the one
53
+ * emulated context under the requested name. A second estate is not something an
54
+ * emulator can have, and an empty list would fail a client that has nothing wrong
55
+ * with it.
56
+ */
57
+ const contextNameFrom = (filter) => {
58
+ if (!filter)
59
+ return exports.DEFAULT_CONTEXT_NAME;
60
+ const match = /name\s*,\s*'([^']*)'|name\s*,\s*"([^"]*)"/i.exec(filter);
61
+ return match?.[1] ?? match?.[2] ?? exports.DEFAULT_CONTEXT_NAME;
62
+ };
63
+ exports.contextNameFrom = contextNameFrom;
64
+ const contextBody = (name) => ({
65
+ id: exports.EMULATED_CONTEXT_ID,
66
+ name,
67
+ createdBy: ids_js_1.EMULATED_USER.id,
68
+ version: 2,
69
+ links: linksFor(`/compute/contexts/${exports.EMULATED_CONTEXT_ID}`, 'application/vnd.sas.compute.context')
70
+ });
71
+ const sessionBody = (services, session, autoExecLines) => {
72
+ const { id } = session;
73
+ const uri = `/compute/sessions/${id}`;
74
+ return {
75
+ id,
76
+ applicationName: 'emulated',
77
+ owner: ids_js_1.EMULATED_USER.id,
78
+ serverId: (0, ids_js_1.idFor)((0, seed_js_1.normaliseServerUrl)(services.viya?.serverUrl) || 'emulated', 'server'),
79
+ state: 'idle',
80
+ attributes: {
81
+ homeDirectory: '/tmp/emulated',
82
+ sessionInactiveTimeout: 3600
83
+ },
84
+ environment: { autoExecLines },
85
+ // the real clock: the adapter computes a session's age from this stamp and
86
+ // expires it against sessionInactiveTimeout
87
+ creationTimeStamp: session.createdAt,
88
+ serviceAPIVersion: 1,
89
+ sessionConditionCode: 0,
90
+ stateElapsedTime: 0,
91
+ version: 2,
92
+ links: relLinks('application/vnd.sas.compute.session', [
93
+ ['self', uri],
94
+ ['state', `${uri}/state`],
95
+ ['log', `${uri}/log`],
96
+ ['jobs', `${uri}/jobs`]
97
+ ])
98
+ };
99
+ };
100
+ const jobBody = (job) => {
101
+ const uri = `/compute/sessions/${job.sessionId}/jobs/${job.id}`;
102
+ return {
103
+ id: job.id,
104
+ name: job.name,
105
+ sessionId: job.sessionId,
106
+ state: job.state,
107
+ creationTimeStamp: job.creationTimeStamp,
108
+ ...(job.completedTimeStamp
109
+ ? { completedTimeStamp: job.completedTimeStamp }
110
+ : {}),
111
+ jobConditionCode: 0,
112
+ stateElapsedTime: 1,
113
+ listingStatistics: {
114
+ lineCount: job.log.length,
115
+ modifiedTimeStamp: job.completedTimeStamp ?? job.creationTimeStamp
116
+ },
117
+ logStatistics: {
118
+ lineCount: job.log.length,
119
+ modifiedTimeStamp: job.completedTimeStamp ?? job.creationTimeStamp
120
+ },
121
+ statistics: { systemCpuTime: 0.01, userCpuTime: 0.02 },
122
+ version: 2,
123
+ links: relLinks('application/vnd.sas.compute.job', [
124
+ ['self', uri],
125
+ ['state', `${uri}/state`],
126
+ ['log', `${uri}/log`],
127
+ ['up', `/compute/sessions/${job.sessionId}`]
128
+ ])
129
+ };
130
+ };
131
+ /** The session the request names, or the 404 a client that lost it expects. */
132
+ const sessionOf = (services, id) => {
133
+ const session = estateOf(services).session(id);
134
+ if (!session)
135
+ throw new types_js_1.ApiError(404, `Session with ID '${id}' was not found.`);
136
+ return session;
137
+ };
138
+ const jobOf = (services, sessionId, jobId) => {
139
+ const job = sessionOf(services, sessionId).jobs.get(jobId);
140
+ if (!job)
141
+ throw new types_js_1.ApiError(404, `Job with ID '${jobId}' was not found.`);
142
+ return job;
143
+ };
144
+ /**
145
+ * The `{}` values a request carried, in path order.
146
+ *
147
+ * `dispatchViya` sets `segments` on every request it hands a handler, so there is
148
+ * no absent case to answer - a fallback here would be a branch nothing reaches.
149
+ */
150
+ const segmentsOf = (params) => params.segments;
151
+ exports.COMPUTE_HANDLERS = {
152
+ 'GET /compute/contexts': async ({ request }) => {
153
+ const limit = Number(request.query?.limit ?? 0) || 0;
154
+ return {
155
+ status: 200,
156
+ body: {
157
+ accept: 'application/json',
158
+ name: 'contexts',
159
+ start: 0,
160
+ limit,
161
+ count: 1,
162
+ version: 2,
163
+ items: [contextBody((0, exports.contextNameFrom)(request.query?.filter))],
164
+ links: linksFor('/compute/contexts', 'application/vnd.sas.compute.context', true)
165
+ }
166
+ };
167
+ },
168
+ 'POST /compute/contexts/{}/sessions': async ({ services, params, request }) => {
169
+ if (params.id !== exports.EMULATED_CONTEXT_ID)
170
+ throw new types_js_1.ApiError(404, `Context with ID '${params.id}' was not found.`);
171
+ const body = (request.body ?? {});
172
+ const session = estateOf(services).create();
173
+ return {
174
+ status: 201,
175
+ body: sessionBody(services, session, body.environment?.autoExecLines ?? [])
176
+ };
177
+ },
178
+ 'GET /compute/sessions/{}/state': async ({ services, params }) => {
179
+ sessionOf(services, params.id);
180
+ // a bare enum, not an object: the adapter calls `.trim()` on the answer, and
181
+ // the capture recorded no shape here because there is no JSON body
182
+ return { status: 200, body: 'idle' };
183
+ },
184
+ 'DELETE /compute/sessions/{}': async ({ services, params }) => {
185
+ sessionOf(services, params.id);
186
+ estateOf(services).remove(params.id);
187
+ return { status: 204, body: undefined };
188
+ },
189
+ 'POST /compute/sessions/{}/jobs': async ({ services, params, request }) => {
190
+ const session = sessionOf(services, params.id);
191
+ const body = (request.body ?? {});
192
+ const job = estateOf(services).submit(session, body);
193
+ const execute = services.viya?.execute;
194
+ // a host with no engine has nothing to run, so the job is finished at once
195
+ if (!execute) {
196
+ job.state = 'completed';
197
+ job.completedTimeStamp = new Date().toISOString();
198
+ return { status: 201, body: jobBody(job) };
199
+ }
200
+ // the 201 is the submission, not the run: the client polls the state link,
201
+ // and `waitForResult: false` is documented to return here and poll later
202
+ job.state = 'running';
203
+ // and there is no log yet: the generated lines are what a host with NO engine
204
+ // answers, including one that says the run completed, so a running job must
205
+ // not advertise them - the run writes the log when it has one
206
+ job.log = [];
207
+ void execute({
208
+ program: body.code ?? '',
209
+ variables: body.variables,
210
+ name: body.name,
211
+ sessionId: session.id
212
+ })
213
+ .then((ran) => {
214
+ job.log = ran.log.split('\n');
215
+ job.state = ran.state ?? 'completed';
216
+ if (ran.webout !== undefined)
217
+ job.webout = ran.webout;
218
+ job.completedTimeStamp = new Date().toISOString();
219
+ })
220
+ .catch((error) => {
221
+ // a run that threw is a failed job with the reason in its log, because a
222
+ // client reads the failure from the state and the log together
223
+ job.state = 'failed';
224
+ job.log = [`ERROR: ${error.message}`];
225
+ job.completedTimeStamp = new Date().toISOString();
226
+ });
227
+ return { status: 201, body: jobBody(job) };
228
+ },
229
+ 'GET /compute/sessions/{}/filerefs/_webout/content': async ({ services, params }) => {
230
+ const session = sessionOf(services, params.id);
231
+ const last = [...session.jobs.values()].pop();
232
+ if (!last)
233
+ throw new types_js_1.ApiError(404, 'This session has no `_webout` yet: nothing has run in it.');
234
+ // the answer belongs to the last job submitted, not to the newest one that
235
+ // happened to produce something: a failed service must not answer with an
236
+ // earlier service's data
237
+ if (last.webout === undefined)
238
+ throw new types_js_1.ApiError(404, last.state === 'running'
239
+ ? `This session has no \`_webout\` yet: job '${last.id}' has not finished.`
240
+ : services.viya?.execute
241
+ ? `This session has no \`_webout\`: job '${last.id}' ran and produced none.`
242
+ : `This session has no \`_webout\`: the host supplied no engine, so no program has run.`);
243
+ return {
244
+ status: 200,
245
+ contents: last.webout,
246
+ headers: { 'content-type': 'text/plain' }
247
+ };
248
+ },
249
+ 'GET /compute/sessions/{}/jobs/{}': async ({ services, params }) => {
250
+ const [sessionId, jobId] = segmentsOf(params);
251
+ return { status: 200, body: jobBody(jobOf(services, sessionId, jobId)) };
252
+ },
253
+ 'GET /compute/sessions/{}/jobs/{}/state': async ({ services, params }) => {
254
+ const [sessionId, jobId] = segmentsOf(params);
255
+ return {
256
+ status: 200,
257
+ body: jobOf(services, sessionId, jobId).state
258
+ };
259
+ },
260
+ 'GET /compute/sessions/{}/jobs/{}/log/content': async ({ services, params, request }) => {
261
+ const [sessionId, jobId] = segmentsOf(params);
262
+ const job = jobOf(services, sessionId, jobId);
263
+ const start = Number(request.query?.start ?? 0) || 0;
264
+ const limit = Number(request.query?.limit ?? 0) || 0;
265
+ const lines = job.log.slice(start, limit ? start + limit : undefined);
266
+ return {
267
+ status: 200,
268
+ body: {
269
+ accept: 'application/json',
270
+ name: 'content',
271
+ start,
272
+ limit: limit || lines.length,
273
+ count: job.log.length,
274
+ version: 2,
275
+ items: lines.map((line) => ({ line, type: 'NOTE', version: 2 })),
276
+ links: linksFor(`/compute/sessions/${job.sessionId}/jobs/${job.id}/log`, 'application/vnd.sas.compute.job.log', false, true)
277
+ }
278
+ };
279
+ }
280
+ };
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.VIYA_OPERATIONS = exports.DECLARED = void 0;
4
+ /**
5
+ * Operations the emulator must answer that no capture describes.
6
+ *
7
+ * The table is generated from what an estate answered, which is the right rule:
8
+ * a row nobody observed is a claim about a call no client makes. But a client
9
+ * does make some calls that no recording pass reaches, and an emulator that
10
+ * cannot answer them is an emulator an application cannot run on. Those rows are
11
+ * stated here, each with the reason it has no capture, and they pass through the
12
+ * same overlay ratchet as a captured one - so a declared operation still needs a
13
+ * decision about whether this package implements it.
14
+ *
15
+ * They are kept out of `src/viya/table.ts` because that file is generated: a
16
+ * hand-written row in it would be deleted by the next `npm run sync:viya`, and a
17
+ * generator that had to preserve hand edits would stop being a generator.
18
+ */
19
+ const table_js_1 = require("./table.js");
20
+ exports.DECLARED = [
21
+ {
22
+ id: 'GET /compute/sessions/{}/filerefs/_webout/content',
23
+ method: 'GET',
24
+ path: '/compute/sessions/{}/filerefs/_webout/content',
25
+ steps: [],
26
+ // what this emulator answers, not what an estate did: 200 with the webout,
27
+ // 404 when no program has run in the session
28
+ statuses: [200, 404],
29
+ queries: [],
30
+ request: { queries: [], body: undefined },
31
+ // the body is the program's `_webout`, which is whatever the program wrote:
32
+ // there is no JSON shape to record
33
+ shape: undefined,
34
+ declared: 'The adapter fetches this only when a run expects a webout (`expectWebout`), and the recording pass submits a `%put` and reads the log instead. Without it an application cannot receive the data its service returns, so the emulator answers it from the job it just ran.'
35
+ }
36
+ ];
37
+ /** Every operation the emulator answers: what an estate did, plus what it must. */
38
+ exports.VIYA_OPERATIONS = [...table_js_1.VIYA_TABLE, ...exports.DECLARED];
@@ -2,12 +2,12 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.dispatchViya = exports.findViyaOperation = void 0;
4
4
  const types_js_1 = require("../types.js");
5
- const table_js_1 = require("./table.js");
5
+ const declared_js_1 = require("./declared.js");
6
6
  const overlay_js_1 = require("./overlay.js");
7
7
  const service_js_1 = require("./service.js");
8
8
  const version_js_1 = require("./version.js");
9
9
  const escape = (segment) => segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
10
- const compiled = table_js_1.VIYA_TABLE.filter((operation) => operation.path.includes('{}')).map((operation) => ({
10
+ const compiled = declared_js_1.VIYA_OPERATIONS.filter((operation) => operation.path.includes('{}')).map((operation) => ({
11
11
  operation,
12
12
  pattern: new RegExp('^' +
13
13
  operation.path
@@ -19,7 +19,7 @@ const compiled = table_js_1.VIYA_TABLE.filter((operation) => operation.path.incl
19
19
  'i')
20
20
  }));
21
21
  const exact = new Map();
22
- for (const operation of table_js_1.VIYA_TABLE)
22
+ for (const operation of declared_js_1.VIYA_OPERATIONS)
23
23
  if (!operation.path.includes('{}'))
24
24
  // keyed in lower case, because the hosts are: express's `case sensitive
25
25
  // routing` is off and the emulated estate has to match what they serve
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FILE_HANDLERS = void 0;
4
+ const types_js_1 = require("../types.js");
5
+ const ports_js_1 = require("./ports.js");
6
+ const ids_js_1 = require("./ids.js");
7
+ const contentTypeOf = (name) => {
8
+ if (/\.sas$/i.test(name))
9
+ return 'text/plain';
10
+ if (/\.(json)$/i.test(name))
11
+ return 'application/json';
12
+ if (/\.(csv|txt|log)$/i.test(name))
13
+ return 'text/plain';
14
+ if (/\.(html?)$/i.test(name))
15
+ return 'text/html';
16
+ if (/\.(png)$/i.test(name))
17
+ return 'image/png';
18
+ if (/\.(jpe?g)$/i.test(name))
19
+ return 'image/jpeg';
20
+ return 'application/octet-stream';
21
+ };
22
+ /**
23
+ * What the estate records about a file.
24
+ *
25
+ * `properties` carries the five keys the capture recorded, with the values a
26
+ * client reads rather than placeholders: the three `content.*` flags say what can
27
+ * be done with the file, and `typeRegistrant` says who registered the type.
28
+ */
29
+ const fileBody = (file) => {
30
+ const id = (0, ids_js_1.idFor)(file.path, 'file');
31
+ const uri = `/files/files/${id}`;
32
+ const contentType = contentTypeOf(file.name);
33
+ return {
34
+ id,
35
+ name: file.name,
36
+ contentType,
37
+ contentDisposition: `attachment; filename="${file.name}"`,
38
+ encoding: 'UTF-8',
39
+ size: file.size,
40
+ fileStatus: 'complete',
41
+ fileVersion: 1,
42
+ version: 2,
43
+ typeDefName: 'file',
44
+ createdBy: ids_js_1.EMULATED_USER.id,
45
+ modifiedBy: ids_js_1.EMULATED_USER.id,
46
+ creationTimeStamp: ids_js_1.EMULATED_NOW,
47
+ modifiedTimeStamp: ids_js_1.EMULATED_NOW,
48
+ quarantine: false,
49
+ searchable: true,
50
+ virusDetected: false,
51
+ urlDetected: false,
52
+ properties: {
53
+ 'content.download': 'true',
54
+ 'content.openInBrowser': 'true',
55
+ 'content.preview': 'false',
56
+ sasIconKey: 'file',
57
+ typeRegistrant: ids_js_1.EMULATED_USER.id
58
+ },
59
+ links: [
60
+ {
61
+ href: uri,
62
+ uri,
63
+ rel: 'self',
64
+ method: 'GET',
65
+ type: 'application/vnd.sas.file'
66
+ },
67
+ {
68
+ href: `${uri}/content`,
69
+ uri: `${uri}/content`,
70
+ rel: 'content',
71
+ method: 'GET',
72
+ type: 'application/vnd.sas.file.content'
73
+ }
74
+ ]
75
+ };
76
+ };
77
+ /**
78
+ * The bytes in a string, counted rather than measured.
79
+ *
80
+ * `Buffer.byteLength` is not available in the browser build, and the number this
81
+ * returns is the size a client sees, so it has to be right for non-ASCII too.
82
+ */
83
+ const utf8Length = (text) => {
84
+ let bytes = 0;
85
+ for (const character of text) {
86
+ const point = character.codePointAt(0);
87
+ bytes += point < 0x80 ? 1 : point < 0x800 ? 2 : point < 0x10000 ? 3 : 4;
88
+ }
89
+ return bytes;
90
+ };
91
+ const sizeOf = (contents) => typeof contents === 'string' ? utf8Length(contents) : contents.byteLength;
92
+ /** Every file in the drive, as `path` and name. */
93
+ const filesIn = async (drive) => {
94
+ const walk = (node, found) => {
95
+ if (!node.isFolder)
96
+ found.push({ name: node.name, path: node.relativePath, size: 0 });
97
+ for (const child of node.children)
98
+ walk(child, found);
99
+ return found;
100
+ };
101
+ return walk((await drive.tree('/')).tree, []);
102
+ };
103
+ /**
104
+ * The path a file id names, or the 404 a client with a stale id expects.
105
+ *
106
+ * Resolved against the drive rather than remembered in a map: a rename changes the
107
+ * path and therefore the id, and a map would keep answering for the old one.
108
+ */
109
+ const pathForFileId = async (drive, id) => {
110
+ const file = (await filesIn(drive)).find((candidate) => (0, ids_js_1.idFor)(candidate.path, 'file') === id);
111
+ if (!file)
112
+ throw new types_js_1.ApiError(404, `File with ID '${id}' was not found.`);
113
+ return file.path;
114
+ };
115
+ const bodyOf = async (drive, path) => {
116
+ const read = await drive.read(path);
117
+ return {
118
+ name: path.split('/').pop(),
119
+ path,
120
+ size: sizeOf(read.contents)
121
+ };
122
+ };
123
+ /** The parent folder a request names, or the root it means by its absence. */
124
+ const parentOf = async (drive, uri) => {
125
+ if (!uri)
126
+ return '/';
127
+ const id = uri.split('/').pop();
128
+ const tree = await drive.tree('/');
129
+ const walk = (node) => {
130
+ if (node.isFolder && (0, ids_js_1.idFor)(node.relativePath, 'folder') === id)
131
+ return node.relativePath;
132
+ for (const child of node.children) {
133
+ const hit = walk(child);
134
+ if (hit !== undefined)
135
+ return hit;
136
+ }
137
+ return undefined;
138
+ };
139
+ const found = walk(tree.tree);
140
+ if (found === undefined)
141
+ throw new types_js_1.ApiError(404, `Folder with ID '${id}' was not found.`);
142
+ return found;
143
+ };
144
+ exports.FILE_HANDLERS = {
145
+ 'POST /files/files': async ({ services, request }) => {
146
+ const drive = (0, ports_js_1.requireDrive)(services);
147
+ const upload = request.file;
148
+ if (!upload?.name)
149
+ throw new types_js_1.ApiError(400, 'A file named `file` is required.');
150
+ const parent = await parentOf(drive, request.query?.parentFolderUri);
151
+ const path = `${parent}/${upload.name}`.replace(/\/{2,}/g, '/');
152
+ await drive.save(path, upload.contents);
153
+ return { status: 201, body: fileBody(await bodyOf(drive, path)) };
154
+ },
155
+ 'GET /files/files/{}': async ({ services, params }) => {
156
+ const drive = (0, ports_js_1.requireDrive)(services);
157
+ const path = await pathForFileId(drive, params.id);
158
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
159
+ },
160
+ 'PATCH /files/files/{}': async ({ services, params, request }) => {
161
+ const drive = (0, ports_js_1.requireDrive)(services);
162
+ const path = await pathForFileId(drive, params.id);
163
+ const body = (request.body ?? {});
164
+ const name = body.name ?? path.split('/').pop();
165
+ const target = `${path.split('/').slice(0, -1).join('/')}/${name}`.replace(/\/{2,}/g, '/');
166
+ if (target !== path)
167
+ await drive.rename(path, target);
168
+ return { status: 200, body: fileBody(await bodyOf(drive, target)) };
169
+ },
170
+ 'GET /files/files/{}/content': async ({ services, params }) => {
171
+ const drive = (0, ports_js_1.requireDrive)(services);
172
+ const path = await pathForFileId(drive, params.id);
173
+ const read = await drive.read(path);
174
+ // `contents`, not `body`: ApiResponse reserves that field for a raw body,
175
+ // e.g. the driver route that answers with the file itself. A host that maps
176
+ // `body` JSON-encodes the string and declares text/html over a quoted value.
177
+ return {
178
+ status: 200,
179
+ contents: read.contents,
180
+ headers: {
181
+ 'content-type': contentTypeOf(path.split('/').pop())
182
+ }
183
+ };
184
+ },
185
+ 'PUT /files/files/{}/content': async ({ services, params, request }) => {
186
+ const drive = (0, ports_js_1.requireDrive)(services);
187
+ const path = await pathForFileId(drive, params.id);
188
+ // a host may hand the bytes over as the multipart part or as the body
189
+ const body = request.body;
190
+ const contents = request.file?.contents ??
191
+ (typeof body === 'string'
192
+ ? body
193
+ : body?.contents);
194
+ if (contents === undefined || contents === null)
195
+ throw new types_js_1.ApiError(400, 'File content is required.');
196
+ await drive.update(path, contents);
197
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
198
+ }
199
+ };
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ /**
3
+ * The values that identify the emulated estate, in one place.
4
+ *
5
+ * They live apart from the handlers because two handler modules need them: the
6
+ * folder family derives a folder id, the compute family derives a context and a
7
+ * server id, and a module that imports the other's handler map to reach them
8
+ * would be a cycle.
9
+ */
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.normalisePath = exports.idFor = exports.EMULATED_USER = exports.EMULATED_NOW = void 0;
12
+ /** The emulated clock: a fixed instant, so a body is reproducible. */
13
+ exports.EMULATED_NOW = '2026-01-01T00:00:00.000Z';
14
+ /** The caller the emulated estate reports when a host does not name one. */
15
+ exports.EMULATED_USER = { id: 'emulated-user', name: 'Emulated User' };
16
+ /**
17
+ * A uuid shape from a string, deterministically.
18
+ *
19
+ * Two 32-bit FNV-1a passes give enough of a hash to fill a uuid's fields, and the
20
+ * version/variant nibbles are set so the result is a well-formed v4-shaped id.
21
+ * Collisions are possible in principle and irrelevant here: the id is a handle
22
+ * the emulator hands back, not a uniqueness guarantee.
23
+ */
24
+ const idFor = (path, kind = 'folder') => {
25
+ const hash = (input, seed) => {
26
+ let value = seed;
27
+ for (let index = 0; index < input.length; index++) {
28
+ value ^= input.charCodeAt(index);
29
+ value = Math.imul(value, 16777619) >>> 0;
30
+ }
31
+ return value.toString(16).padStart(8, '0');
32
+ };
33
+ const raw = hash(`${kind}:${path}`, 2166136261) +
34
+ hash(`${kind}:${path}`, 2246822519) +
35
+ hash(`${kind}:${path}`, 3266489917) +
36
+ hash(`${kind}:${path}`, 668265263);
37
+ const hex = raw.slice(0, 32);
38
+ return [
39
+ hex.slice(0, 8),
40
+ hex.slice(8, 12),
41
+ `4${hex.slice(13, 16)}`,
42
+ `a${hex.slice(17, 20)}`,
43
+ hex.slice(20, 32)
44
+ ].join('-');
45
+ };
46
+ exports.idFor = idFor;
47
+ /**
48
+ * One folder path, however it was spelled.
49
+ *
50
+ * The adapter joins a root of '/' to a path of '/app' and sends '//app', which is
51
+ * a different string and - because an id is derived from the path - a different
52
+ * id. A client that then asks for that id is asking about a folder the drive does
53
+ * not have, so every path is collapsed to one spelling before anything derives
54
+ * from it.
55
+ */
56
+ const normalisePath = (path) => {
57
+ const collapsed = `/${path}`.replace(/\/{2,}/g, '/');
58
+ return collapsed.length > 1 ? collapsed.replace(/\/+$/, '') : collapsed;
59
+ };
60
+ exports.normalisePath = normalisePath;