@sasjs/api 0.35.0 → 0.36.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/build/browser.js CHANGED
@@ -1,4 +1,4 @@
1
- /* @sasjs/api 0.35.0 - the SASjs Server API, for a service worker. https://github.com/sasjs/api */
1
+ /* @sasjs/api 0.36.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;
@@ -4388,7 +4388,6 @@ var SASjsApi = (() => {
4388
4388
  });
4389
4389
 
4390
4390
  // src/viya/overlay.ts
4391
- var 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.";
4392
4391
  var NEEDS_AUTH = "The token endpoint is answered by the host that mounts the emulator, which owns the token port.";
4393
4392
  var VIYA_OVERLAY = {
4394
4393
  // answered here
@@ -4400,38 +4399,21 @@ var SASjsApi = (() => {
4400
4399
  "GET /folders/folders/@myRecycleBin": { implemented: true },
4401
4400
  "GET /identities/users/@currentUser": { implemented: true },
4402
4401
  "GET /types/types": { implemented: true },
4403
- // declined: the session and file ports
4404
- "GET /compute/contexts": { implemented: false, reason: NEEDS_RUNTIME },
4405
- "POST /compute/contexts/{}/sessions": {
4406
- implemented: false,
4407
- reason: NEEDS_RUNTIME
4408
- },
4409
- "DELETE /compute/sessions/{}": { implemented: false, reason: NEEDS_RUNTIME },
4410
- "POST /compute/sessions/{}/jobs": {
4411
- implemented: false,
4412
- reason: NEEDS_RUNTIME
4413
- },
4414
- "GET /compute/sessions/{}/jobs/{}": {
4415
- implemented: false,
4416
- reason: NEEDS_RUNTIME
4417
- },
4418
- "GET /compute/sessions/{}/jobs/{}/log/content": {
4419
- implemented: false,
4420
- reason: NEEDS_RUNTIME
4421
- },
4422
- "GET /compute/sessions/{}/jobs/{}/state": {
4423
- implemented: false,
4424
- reason: NEEDS_RUNTIME
4425
- },
4426
- "GET /compute/sessions/{}/state": {
4427
- implemented: false,
4428
- reason: NEEDS_RUNTIME
4429
- },
4430
- "POST /files/files": { implemented: false, reason: NEEDS_RUNTIME },
4431
- "GET /files/files/{}": { implemented: false, reason: NEEDS_RUNTIME },
4432
- "PATCH /files/files/{}": { implemented: false, reason: NEEDS_RUNTIME },
4433
- "GET /files/files/{}/content": { implemented: false, reason: NEEDS_RUNTIME },
4434
- "PUT /files/files/{}/content": { implemented: false, reason: NEEDS_RUNTIME },
4402
+ // answered here: compute
4403
+ "GET /compute/contexts": { implemented: true },
4404
+ "POST /compute/contexts/{}/sessions": { implemented: true },
4405
+ "DELETE /compute/sessions/{}": { implemented: true },
4406
+ "POST /compute/sessions/{}/jobs": { implemented: true },
4407
+ "GET /compute/sessions/{}/jobs/{}": { implemented: true },
4408
+ "GET /compute/sessions/{}/jobs/{}/log/content": { implemented: true },
4409
+ "GET /compute/sessions/{}/jobs/{}/state": { implemented: true },
4410
+ "GET /compute/sessions/{}/state": { implemented: true },
4411
+ // answered here: files
4412
+ "POST /files/files": { implemented: true },
4413
+ "GET /files/files/{}": { implemented: true },
4414
+ "PATCH /files/files/{}": { implemented: true },
4415
+ "GET /files/files/{}/content": { implemented: true },
4416
+ "PUT /files/files/{}/content": { implemented: true },
4435
4417
  // declined: the host owns the token port
4436
4418
  "POST /SASLogon/oauth/token": { implemented: false, reason: NEEDS_AUTH }
4437
4419
  };
@@ -4450,11 +4432,143 @@ var SASjsApi = (() => {
4450
4432
  };
4451
4433
  assertOverlayEntries(VIYA_OVERLAY);
4452
4434
 
4453
- // src/viya/service.ts
4435
+ // src/viya/ports.ts
4436
+ var requireDrive = (services) => services.drive;
4437
+
4438
+ // src/viya/seed.ts
4439
+ var DEFAULT_SEED = "emulated";
4440
+ var normaliseServerUrl = (url) => {
4441
+ if (!url) return "";
4442
+ const trimmed = url.trim();
4443
+ if (!trimmed) return "";
4444
+ const match = /^(?:([a-z][a-z0-9+.-]*):\/\/)?([^/?#]+)/i.exec(trimmed);
4445
+ if (!match) return trimmed.replace(/\/+$/, "").toLowerCase();
4446
+ const scheme = (match[1] ?? "http").toLowerCase();
4447
+ let authority = match[2].toLowerCase();
4448
+ const credentials = authority.lastIndexOf("@");
4449
+ if (credentials >= 0) authority = authority.slice(credentials + 1);
4450
+ let host = authority;
4451
+ let port = "";
4452
+ if (authority.startsWith("[")) {
4453
+ const close = authority.indexOf("]");
4454
+ if (close >= 0) {
4455
+ host = authority.slice(0, close + 1);
4456
+ if (authority[close + 1] === ":") port = authority.slice(close + 2);
4457
+ }
4458
+ } else {
4459
+ const colon = authority.lastIndexOf(":");
4460
+ if (colon >= 0) {
4461
+ host = authority.slice(0, colon);
4462
+ port = authority.slice(colon + 1);
4463
+ }
4464
+ }
4465
+ const isDefault = scheme === "http" && port === "80" || scheme === "https" && port === "443";
4466
+ return `${scheme}://${host}${port && !isDefault ? `:${port}` : ""}`;
4467
+ };
4468
+ var hash = (input) => {
4469
+ let value = 2166136261;
4470
+ for (let index = 0; index < input.length; index++) {
4471
+ value ^= input.charCodeAt(index);
4472
+ value = Math.imul(value, 16777619) >>> 0;
4473
+ }
4474
+ return value >>> 0;
4475
+ };
4476
+ var seedOf = (settings = {}) => {
4477
+ if (settings.seed !== void 0 && settings.seed !== "")
4478
+ return hash(`seed:${settings.seed}`);
4479
+ const address = normaliseServerUrl(settings.serverUrl);
4480
+ return hash(`url:${address || DEFAULT_SEED}`);
4481
+ };
4482
+ var generator = (seed) => {
4483
+ let state = seed >>> 0;
4484
+ return () => {
4485
+ state = state + 1831565813 >>> 0;
4486
+ let value = state;
4487
+ value = Math.imul(value ^ value >>> 15, value | 1);
4488
+ value ^= value + Math.imul(value ^ value >>> 7, value | 61);
4489
+ return ((value ^ value >>> 14) >>> 0) / 4294967296;
4490
+ };
4491
+ };
4492
+ var drawInt = (next, bound) => Math.floor(next() * bound);
4493
+ var drawFrom = (next, values) => values[drawInt(next, values.length)];
4494
+
4495
+ // src/viya/sessions.ts
4496
+ var logFor = (seed, program) => {
4497
+ const code = Array.isArray(program) ? program.join("\n") : program;
4498
+ const next = generator(seed ^ hash(`code:${code}`));
4499
+ const rows = drawInt(next, 900) + 100;
4500
+ const seconds = (drawInt(next, 90) + 10) / 100;
4501
+ const lines = code.split("\n").map((line, index) => `${String(index + 1).padStart(3, " ")} ${line}`);
4502
+ return [
4503
+ "NOTE: Emulated compute engine - this log is generated, not produced by SAS.",
4504
+ "NOTE: No library was touched: the emulated engine has none.",
4505
+ ...lines,
4506
+ `NOTE: The data set WORK.EMULATED has ${rows} observations and 3 variables.`,
4507
+ `NOTE: DATA statement used (Total process time):`,
4508
+ `NOTE: real time ${seconds.toFixed(2)} seconds`,
4509
+ `NOTE: user cpu time ${(seconds / 2).toFixed(2)} seconds`,
4510
+ `NOTE: ${drawFrom(next, ["The emulated run completed.", "Emulation complete - no SAS was executed."])}`
4511
+ ];
4512
+ };
4513
+ var EmulatedEstate = class {
4514
+ constructor(seed) {
4515
+ this.seed = seed;
4516
+ this.sessions = /* @__PURE__ */ new Map();
4517
+ this.created = 0;
4518
+ }
4519
+ /** A new session: deterministic id, no jobs. */
4520
+ create() {
4521
+ const session = {
4522
+ id: `emulated-${this.seed.toString(16)}-ses${String(this.created++).padStart(4, "0")}`,
4523
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
4524
+ jobs: /* @__PURE__ */ new Map(),
4525
+ submitted: 0
4526
+ };
4527
+ this.sessions.set(session.id, session);
4528
+ return session;
4529
+ }
4530
+ session(id) {
4531
+ return this.sessions.get(id);
4532
+ }
4533
+ remove(id) {
4534
+ return this.sessions.delete(id);
4535
+ }
4536
+ /** A job accepted into a session, with the log the emulator generated for it. */
4537
+ submit(session, job) {
4538
+ const id = `${session.id}-job${String(session.submitted++).padStart(4, "0")}`;
4539
+ const code = job.code ?? "";
4540
+ const submitted = {
4541
+ id,
4542
+ name: job.name ?? id,
4543
+ // the log is a function of the seed and the program alone, so the same
4544
+ // program answers the same lines whatever session it was submitted in
4545
+ log: logFor(this.seed, code),
4546
+ state: "completed",
4547
+ // the real clock, unlike a folder's: a client computes a session's age
4548
+ // from this stamp and expires it, so a fixed instant in the past is a
4549
+ // session that is born expired
4550
+ creationTimeStamp: (/* @__PURE__ */ new Date()).toISOString(),
4551
+ completedTimeStamp: (/* @__PURE__ */ new Date()).toISOString(),
4552
+ sessionId: session.id
4553
+ };
4554
+ session.jobs.set(id, submitted);
4555
+ return submitted;
4556
+ }
4557
+ };
4558
+ var estates = /* @__PURE__ */ new Map();
4559
+ var estateFor = (seed) => {
4560
+ const existing = estates.get(seed);
4561
+ if (existing) return existing;
4562
+ const estate = new EmulatedEstate(seed);
4563
+ estates.set(seed, estate);
4564
+ return estate;
4565
+ };
4566
+
4567
+ // src/viya/ids.ts
4454
4568
  var EMULATED_NOW = "2026-01-01T00:00:00.000Z";
4455
4569
  var EMULATED_USER = { id: "emulated-user", name: "Emulated User" };
4456
4570
  var idFor = (path, kind = "folder") => {
4457
- const hash = (input, seed) => {
4571
+ const hash2 = (input, seed) => {
4458
4572
  let value = seed;
4459
4573
  for (let index = 0; index < input.length; index++) {
4460
4574
  value ^= input.charCodeAt(index);
@@ -4462,7 +4576,7 @@ var SASjsApi = (() => {
4462
4576
  }
4463
4577
  return value.toString(16).padStart(8, "0");
4464
4578
  };
4465
- const raw = hash(`${kind}:${path}`, 2166136261) + hash(`${kind}:${path}`, 2246822519) + hash(`${kind}:${path}`, 3266489917) + hash(`${kind}:${path}`, 668265263);
4579
+ const raw = hash2(`${kind}:${path}`, 2166136261) + hash2(`${kind}:${path}`, 2246822519) + hash2(`${kind}:${path}`, 3266489917) + hash2(`${kind}:${path}`, 668265263);
4466
4580
  const hex = raw.slice(0, 32);
4467
4581
  return [
4468
4582
  hex.slice(0, 8),
@@ -4472,7 +4586,389 @@ var SASjsApi = (() => {
4472
4586
  hex.slice(20, 32)
4473
4587
  ].join("-");
4474
4588
  };
4475
- var linksFor = (uri, collection = false) => {
4589
+ var normalisePath = (path) => {
4590
+ const collapsed = `/${path}`.replace(/\/{2,}/g, "/");
4591
+ return collapsed.length > 1 ? collapsed.replace(/\/+$/, "") : collapsed;
4592
+ };
4593
+
4594
+ // src/viya/compute.ts
4595
+ var DEFAULT_CONTEXT_NAME = "Emulated Compute Context";
4596
+ var EMULATED_CONTEXT_ID = idFor("emulated-context", "context");
4597
+ var relLinks = (type, rels) => rels.map(([rel, href]) => ({ href, uri: href, rel, method: "GET", type }));
4598
+ var linksFor = (uri, type, collection = false, itemType = false) => [
4599
+ // the collection link comes first, because that is the order the capture
4600
+ // recorded and the item shape assertion walks the first element
4601
+ ...collection ? [
4602
+ {
4603
+ href: `${uri}/members`,
4604
+ uri: `${uri}/members`,
4605
+ rel: "members",
4606
+ method: "GET",
4607
+ type,
4608
+ itemType: type
4609
+ }
4610
+ ] : [],
4611
+ {
4612
+ href: uri,
4613
+ uri,
4614
+ rel: "self",
4615
+ method: "GET",
4616
+ type,
4617
+ // the log's capture records itemType on its first link, so it is stamped
4618
+ // there rather than invented as a members link the estate does not have
4619
+ ...itemType ? { itemType: type } : {}
4620
+ }
4621
+ ];
4622
+ var estateOf = (services) => estateFor(seedOf(services.viya));
4623
+ var contextNameFrom = (filter) => {
4624
+ if (!filter) return DEFAULT_CONTEXT_NAME;
4625
+ const match = /name\s*,\s*'([^']*)'|name\s*,\s*"([^"]*)"/i.exec(filter);
4626
+ return match?.[1] ?? match?.[2] ?? DEFAULT_CONTEXT_NAME;
4627
+ };
4628
+ var contextBody = (name) => ({
4629
+ id: EMULATED_CONTEXT_ID,
4630
+ name,
4631
+ createdBy: EMULATED_USER.id,
4632
+ version: 2,
4633
+ links: linksFor(
4634
+ `/compute/contexts/${EMULATED_CONTEXT_ID}`,
4635
+ "application/vnd.sas.compute.context"
4636
+ )
4637
+ });
4638
+ var sessionBody = (services, session, autoExecLines) => {
4639
+ const { id } = session;
4640
+ const uri = `/compute/sessions/${id}`;
4641
+ return {
4642
+ id,
4643
+ applicationName: "emulated",
4644
+ owner: EMULATED_USER.id,
4645
+ serverId: idFor(
4646
+ normaliseServerUrl(services.viya?.serverUrl) || "emulated",
4647
+ "server"
4648
+ ),
4649
+ state: "idle",
4650
+ attributes: {
4651
+ homeDirectory: "/tmp/emulated",
4652
+ sessionInactiveTimeout: 3600
4653
+ },
4654
+ environment: { autoExecLines },
4655
+ // the real clock: the adapter computes a session's age from this stamp and
4656
+ // expires it against sessionInactiveTimeout
4657
+ creationTimeStamp: session.createdAt,
4658
+ serviceAPIVersion: 1,
4659
+ sessionConditionCode: 0,
4660
+ stateElapsedTime: 0,
4661
+ version: 2,
4662
+ links: relLinks("application/vnd.sas.compute.session", [
4663
+ ["self", uri],
4664
+ ["state", `${uri}/state`],
4665
+ ["log", `${uri}/log`],
4666
+ ["jobs", `${uri}/jobs`]
4667
+ ])
4668
+ };
4669
+ };
4670
+ var jobBody = (job) => {
4671
+ const uri = `/compute/sessions/${job.sessionId}/jobs/${job.id}`;
4672
+ return {
4673
+ id: job.id,
4674
+ name: job.name,
4675
+ sessionId: job.sessionId,
4676
+ state: job.state,
4677
+ creationTimeStamp: job.creationTimeStamp,
4678
+ completedTimeStamp: job.completedTimeStamp,
4679
+ jobConditionCode: 0,
4680
+ stateElapsedTime: 1,
4681
+ listingStatistics: {
4682
+ lineCount: job.log.length,
4683
+ modifiedTimeStamp: job.completedTimeStamp
4684
+ },
4685
+ logStatistics: {
4686
+ lineCount: job.log.length,
4687
+ modifiedTimeStamp: job.completedTimeStamp
4688
+ },
4689
+ statistics: { systemCpuTime: 0.01, userCpuTime: 0.02 },
4690
+ version: 2,
4691
+ links: relLinks("application/vnd.sas.compute.job", [
4692
+ ["self", uri],
4693
+ ["state", `${uri}/state`],
4694
+ ["log", `${uri}/log`],
4695
+ ["up", `/compute/sessions/${job.sessionId}`]
4696
+ ])
4697
+ };
4698
+ };
4699
+ var sessionOf = (services, id) => {
4700
+ const session = estateOf(services).session(id);
4701
+ if (!session)
4702
+ throw new ApiError(404, `Session with ID '${id}' was not found.`);
4703
+ return session;
4704
+ };
4705
+ var jobOf = (services, sessionId, jobId) => {
4706
+ const job = sessionOf(services, sessionId).jobs.get(jobId);
4707
+ if (!job) throw new ApiError(404, `Job with ID '${jobId}' was not found.`);
4708
+ return job;
4709
+ };
4710
+ var segmentsOf = (params) => params.segments;
4711
+ var COMPUTE_HANDLERS = {
4712
+ "GET /compute/contexts": async ({ request }) => {
4713
+ const limit = Number(request.query?.limit ?? 0) || 0;
4714
+ return {
4715
+ status: 200,
4716
+ body: {
4717
+ accept: "application/json",
4718
+ name: "contexts",
4719
+ start: 0,
4720
+ limit,
4721
+ count: 1,
4722
+ version: 2,
4723
+ items: [contextBody(contextNameFrom(request.query?.filter))],
4724
+ links: linksFor(
4725
+ "/compute/contexts",
4726
+ "application/vnd.sas.compute.context",
4727
+ true
4728
+ )
4729
+ }
4730
+ };
4731
+ },
4732
+ "POST /compute/contexts/{}/sessions": async ({
4733
+ services,
4734
+ params,
4735
+ request
4736
+ }) => {
4737
+ if (params.id !== EMULATED_CONTEXT_ID)
4738
+ throw new ApiError(404, `Context with ID '${params.id}' was not found.`);
4739
+ const body = request.body ?? {};
4740
+ const session = estateOf(services).create();
4741
+ return {
4742
+ status: 201,
4743
+ body: sessionBody(
4744
+ services,
4745
+ session,
4746
+ body.environment?.autoExecLines ?? []
4747
+ )
4748
+ };
4749
+ },
4750
+ "GET /compute/sessions/{}/state": async ({ services, params }) => {
4751
+ sessionOf(services, params.id);
4752
+ return { status: 200, body: "idle" };
4753
+ },
4754
+ "DELETE /compute/sessions/{}": async ({ services, params }) => {
4755
+ sessionOf(services, params.id);
4756
+ estateOf(services).remove(params.id);
4757
+ return { status: 204, body: void 0 };
4758
+ },
4759
+ "POST /compute/sessions/{}/jobs": async ({ services, params, request }) => {
4760
+ const session = sessionOf(services, params.id);
4761
+ const job = estateOf(services).submit(
4762
+ session,
4763
+ request.body ?? {}
4764
+ );
4765
+ return { status: 201, body: jobBody(job) };
4766
+ },
4767
+ "GET /compute/sessions/{}/jobs/{}": async ({ services, params }) => {
4768
+ const [sessionId, jobId] = segmentsOf(params);
4769
+ return { status: 200, body: jobBody(jobOf(services, sessionId, jobId)) };
4770
+ },
4771
+ "GET /compute/sessions/{}/jobs/{}/state": async ({ services, params }) => {
4772
+ const [sessionId, jobId] = segmentsOf(params);
4773
+ return {
4774
+ status: 200,
4775
+ body: jobOf(services, sessionId, jobId).state
4776
+ };
4777
+ },
4778
+ "GET /compute/sessions/{}/jobs/{}/log/content": async ({
4779
+ services,
4780
+ params,
4781
+ request
4782
+ }) => {
4783
+ const [sessionId, jobId] = segmentsOf(params);
4784
+ const job = jobOf(services, sessionId, jobId);
4785
+ const start = Number(request.query?.start ?? 0) || 0;
4786
+ const limit = Number(request.query?.limit ?? 0) || 0;
4787
+ const lines = job.log.slice(start, limit ? start + limit : void 0);
4788
+ return {
4789
+ status: 200,
4790
+ body: {
4791
+ accept: "application/json",
4792
+ name: "content",
4793
+ start,
4794
+ limit: limit || lines.length,
4795
+ count: job.log.length,
4796
+ version: 2,
4797
+ items: lines.map((line) => ({ line, type: "NOTE", version: 2 })),
4798
+ links: linksFor(
4799
+ `/compute/sessions/${job.sessionId}/jobs/${job.id}/log`,
4800
+ "application/vnd.sas.compute.job.log",
4801
+ false,
4802
+ true
4803
+ )
4804
+ }
4805
+ };
4806
+ }
4807
+ };
4808
+
4809
+ // src/viya/files.ts
4810
+ var contentTypeOf = (name) => {
4811
+ if (/\.sas$/i.test(name)) return "text/plain";
4812
+ if (/\.(json)$/i.test(name)) return "application/json";
4813
+ if (/\.(csv|txt|log)$/i.test(name)) return "text/plain";
4814
+ if (/\.(html?)$/i.test(name)) return "text/html";
4815
+ if (/\.(png)$/i.test(name)) return "image/png";
4816
+ if (/\.(jpe?g)$/i.test(name)) return "image/jpeg";
4817
+ return "application/octet-stream";
4818
+ };
4819
+ var fileBody = (file) => {
4820
+ const id = idFor(file.path, "file");
4821
+ const uri = `/files/files/${id}`;
4822
+ const contentType = contentTypeOf(file.name);
4823
+ return {
4824
+ id,
4825
+ name: file.name,
4826
+ contentType,
4827
+ contentDisposition: `attachment; filename="${file.name}"`,
4828
+ encoding: "UTF-8",
4829
+ size: file.size,
4830
+ fileStatus: "complete",
4831
+ fileVersion: 1,
4832
+ version: 2,
4833
+ typeDefName: "file",
4834
+ createdBy: EMULATED_USER.id,
4835
+ modifiedBy: EMULATED_USER.id,
4836
+ creationTimeStamp: EMULATED_NOW,
4837
+ modifiedTimeStamp: EMULATED_NOW,
4838
+ quarantine: false,
4839
+ searchable: true,
4840
+ virusDetected: false,
4841
+ urlDetected: false,
4842
+ properties: {
4843
+ "content.download": "true",
4844
+ "content.openInBrowser": "true",
4845
+ "content.preview": "false",
4846
+ sasIconKey: "file",
4847
+ typeRegistrant: EMULATED_USER.id
4848
+ },
4849
+ links: [
4850
+ {
4851
+ href: uri,
4852
+ uri,
4853
+ rel: "self",
4854
+ method: "GET",
4855
+ type: "application/vnd.sas.file"
4856
+ },
4857
+ {
4858
+ href: `${uri}/content`,
4859
+ uri: `${uri}/content`,
4860
+ rel: "content",
4861
+ method: "GET",
4862
+ type: "application/vnd.sas.file.content"
4863
+ }
4864
+ ]
4865
+ };
4866
+ };
4867
+ var utf8Length2 = (text2) => {
4868
+ let bytes3 = 0;
4869
+ for (const character of text2) {
4870
+ const point = character.codePointAt(0);
4871
+ bytes3 += point < 128 ? 1 : point < 2048 ? 2 : point < 65536 ? 3 : 4;
4872
+ }
4873
+ return bytes3;
4874
+ };
4875
+ var sizeOf = (contents) => typeof contents === "string" ? utf8Length2(contents) : contents.byteLength;
4876
+ var filesIn = async (drive) => {
4877
+ const walk2 = (node, found) => {
4878
+ if (!node.isFolder)
4879
+ found.push({ name: node.name, path: node.relativePath, size: 0 });
4880
+ for (const child of node.children) walk2(child, found);
4881
+ return found;
4882
+ };
4883
+ return walk2((await drive.tree("/")).tree, []);
4884
+ };
4885
+ var pathForFileId = async (drive, id) => {
4886
+ const file = (await filesIn(drive)).find(
4887
+ (candidate) => idFor(candidate.path, "file") === id
4888
+ );
4889
+ if (!file) throw new ApiError(404, `File with ID '${id}' was not found.`);
4890
+ return file.path;
4891
+ };
4892
+ var bodyOf = async (drive, path) => {
4893
+ const read = await drive.read(path);
4894
+ return {
4895
+ name: path.split("/").pop(),
4896
+ path,
4897
+ size: sizeOf(read.contents)
4898
+ };
4899
+ };
4900
+ var parentOf = async (drive, uri) => {
4901
+ if (!uri) return "/";
4902
+ const id = uri.split("/").pop();
4903
+ const tree = await drive.tree("/");
4904
+ const walk2 = (node) => {
4905
+ if (node.isFolder && idFor(node.relativePath, "folder") === id)
4906
+ return node.relativePath;
4907
+ for (const child of node.children) {
4908
+ const hit = walk2(child);
4909
+ if (hit !== void 0) return hit;
4910
+ }
4911
+ return void 0;
4912
+ };
4913
+ const found = walk2(tree.tree);
4914
+ if (found === void 0)
4915
+ throw new ApiError(404, `Folder with ID '${id}' was not found.`);
4916
+ return found;
4917
+ };
4918
+ var FILE_HANDLERS = {
4919
+ "POST /files/files": async ({ services, request }) => {
4920
+ const drive = requireDrive(services);
4921
+ const upload = request.file;
4922
+ if (!upload?.name)
4923
+ throw new ApiError(400, "A file named `file` is required.");
4924
+ const parent = await parentOf(drive, request.query?.parentFolderUri);
4925
+ const path = `${parent}/${upload.name}`.replace(/\/{2,}/g, "/");
4926
+ await drive.save(path, upload.contents);
4927
+ return { status: 201, body: fileBody(await bodyOf(drive, path)) };
4928
+ },
4929
+ "GET /files/files/{}": async ({ services, params }) => {
4930
+ const drive = requireDrive(services);
4931
+ const path = await pathForFileId(drive, params.id);
4932
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
4933
+ },
4934
+ "PATCH /files/files/{}": async ({ services, params, request }) => {
4935
+ const drive = requireDrive(services);
4936
+ const path = await pathForFileId(drive, params.id);
4937
+ const body = request.body ?? {};
4938
+ const name = body.name ?? path.split("/").pop();
4939
+ const target = `${path.split("/").slice(0, -1).join("/")}/${name}`.replace(
4940
+ /\/{2,}/g,
4941
+ "/"
4942
+ );
4943
+ if (target !== path) await drive.rename(path, target);
4944
+ return { status: 200, body: fileBody(await bodyOf(drive, target)) };
4945
+ },
4946
+ "GET /files/files/{}/content": async ({ services, params }) => {
4947
+ const drive = requireDrive(services);
4948
+ const path = await pathForFileId(drive, params.id);
4949
+ const read = await drive.read(path);
4950
+ return {
4951
+ status: 200,
4952
+ contents: read.contents,
4953
+ headers: {
4954
+ "content-type": contentTypeOf(path.split("/").pop())
4955
+ }
4956
+ };
4957
+ },
4958
+ "PUT /files/files/{}/content": async ({ services, params, request }) => {
4959
+ const drive = requireDrive(services);
4960
+ const path = await pathForFileId(drive, params.id);
4961
+ const body = request.body;
4962
+ const contents = request.file?.contents ?? (typeof body === "string" ? body : body?.contents);
4963
+ if (contents === void 0 || contents === null)
4964
+ throw new ApiError(400, "File content is required.");
4965
+ await drive.update(path, contents);
4966
+ return { status: 200, body: fileBody(await bodyOf(drive, path)) };
4967
+ }
4968
+ };
4969
+
4970
+ // src/viya/service.ts
4971
+ var linksFor2 = (uri, collection = false) => {
4476
4972
  const self = {
4477
4973
  href: uri,
4478
4974
  uri,
@@ -4507,7 +5003,7 @@ var SASjsApi = (() => {
4507
5003
  modifiedTimeStamp: EMULATED_NOW,
4508
5004
  memberCount: listing.files.length + listing.folders.length,
4509
5005
  parentFolderUri: `/folders/folders/${idFor(parent)}`,
4510
- links: linksFor(`/folders/folders/${id}`)
5006
+ links: linksFor2(`/folders/folders/${id}`)
4511
5007
  };
4512
5008
  };
4513
5009
  var recycleBin = () => {
@@ -4526,21 +5022,13 @@ var SASjsApi = (() => {
4526
5022
  memberCount: 0,
4527
5023
  parentFolderUri: "",
4528
5024
  properties: { allowMove: "false" },
4529
- links: linksFor(`/folders/folders/${id}`)
5025
+ links: linksFor2(`/folders/folders/${id}`)
4530
5026
  };
4531
5027
  };
4532
- var requireDrive = (services) => {
4533
- if (!services.drive)
4534
- throw new ApiError(
4535
- 501,
4536
- "This host has no drive, so it cannot answer a folder operation."
4537
- );
4538
- return services.drive;
4539
- };
4540
5028
  var pathFromQuery = (request) => {
4541
5029
  const path = request.query?.path;
4542
5030
  if (!path) throw new ApiError(400, "The path parameter is required.");
4543
- return path;
5031
+ return normalisePath(path);
4544
5032
  };
4545
5033
  var RECYCLE_BIN_ALIAS = "/folders/folders/@myRecycleBin";
4546
5034
  var isRecycleBin = (uri) => !!uri && (uri === RECYCLE_BIN_ALIAS || uri.endsWith(`/${idFor("@myRecycleBin")}`));
@@ -4636,7 +5124,7 @@ var SASjsApi = (() => {
4636
5124
  count: 0,
4637
5125
  version: 2,
4638
5126
  items: [],
4639
- links: linksFor(`/folders/folders/${idFor("@myRecycleBin")}`, true)
5127
+ links: linksFor2(`/folders/folders/${idFor("@myRecycleBin")}`, true)
4640
5128
  }
4641
5129
  };
4642
5130
  const path = await pathForId(drive, params.id);
@@ -4653,7 +5141,7 @@ var SASjsApi = (() => {
4653
5141
  modifiedTimeStamp: EMULATED_NOW,
4654
5142
  parentFolderUri: `/folders/folders/${idFor(path)}`,
4655
5143
  uri: `${path}/${name}`.replace(/\/{2,}/g, "/"),
4656
- links: linksFor(
5144
+ links: linksFor2(
4657
5145
  `/folders/folders/${idFor(`${path}/${name}`.replace(/\/{2,}/g, "/"))}`
4658
5146
  )
4659
5147
  })),
@@ -4670,7 +5158,7 @@ var SASjsApi = (() => {
4670
5158
  parentFolderUri: `/folders/folders/${idFor(path)}`,
4671
5159
  added: EMULATED_NOW,
4672
5160
  uri: `${path}/${name}`.replace(/\/{2,}/g, "/"),
4673
- links: linksFor(
5161
+ links: linksFor2(
4674
5162
  `/files/files/${idFor(`${path}/${name}`.replace(/\/{2,}/g, "/"), "file")}`
4675
5163
  )
4676
5164
  }))
@@ -4686,7 +5174,7 @@ var SASjsApi = (() => {
4686
5174
  count: page.length,
4687
5175
  version: 2,
4688
5176
  items: page,
4689
- links: linksFor(`/folders/folders/${idFor(path)}`, true)
5177
+ links: linksFor2(`/folders/folders/${idFor(path)}`, true)
4690
5178
  }
4691
5179
  };
4692
5180
  },
@@ -4696,7 +5184,7 @@ var SASjsApi = (() => {
4696
5184
  if (!body.name) throw new ApiError(400, "A folder name is required.");
4697
5185
  const parentUri = request.query?.parentFolderUri ?? body.parentFolderUri;
4698
5186
  const parent = parentUri ? await pathForId(drive, String(parentUri).split("/").pop()) : "/";
4699
- const path = `${parent}/${body.name}`.replace(/\/{2,}/g, "/");
5187
+ const path = normalisePath(`${parent}/${body.name}`);
4700
5188
  await drive.mkdir(path);
4701
5189
  return { status: 201, body: await folderBody(drive, path) };
4702
5190
  },
@@ -4719,10 +5207,12 @@ var SASjsApi = (() => {
4719
5207
  drive,
4720
5208
  body.parentFolderUri.split("/").pop()
4721
5209
  );
4722
- const target = `${parent}/${name}`.replace(/\/{2,}/g, "/");
5210
+ const target = normalisePath(`${parent}/${name}`);
4723
5211
  if (target !== path) await drive.rename(path, target);
4724
5212
  return { status: 200, body: await folderBody(drive, target) };
4725
- }
5213
+ },
5214
+ ...COMPUTE_HANDLERS,
5215
+ ...FILE_HANDLERS
4726
5216
  };
4727
5217
 
4728
5218
  // src/viya/dispatch.ts