@sasjs/api 0.24.0 → 0.26.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 (53) hide show
  1. package/README.md +10 -0
  2. package/build/browser.js +703 -94
  3. package/build/cjs/appstream/bundle.js +124 -0
  4. package/build/cjs/appstream/identity.js +69 -0
  5. package/build/cjs/appstream/service.js +226 -0
  6. package/build/cjs/appstream/store.js +69 -0
  7. package/build/cjs/appstream/web.js +248 -0
  8. package/build/cjs/corpus/deploy.js +83 -28
  9. package/build/cjs/corpus/runner.js +30 -18
  10. package/build/cjs/host/dispatch.js +38 -9
  11. package/build/cjs/identity/memory-store.js +51 -1
  12. package/build/cjs/index.js +25 -4
  13. package/build/cjs/routes/generated.js +2 -8
  14. package/build/cjs/routes/overlay.js +2 -2
  15. package/build/esm/appstream/bundle.d.ts +46 -0
  16. package/build/esm/appstream/bundle.d.ts.map +1 -0
  17. package/build/esm/appstream/bundle.js +118 -0
  18. package/build/esm/appstream/identity.d.ts +27 -0
  19. package/build/esm/appstream/identity.d.ts.map +1 -0
  20. package/build/esm/appstream/identity.js +63 -0
  21. package/build/esm/appstream/service.d.ts +96 -0
  22. package/build/esm/appstream/service.d.ts.map +1 -0
  23. package/build/esm/appstream/service.js +218 -0
  24. package/build/esm/appstream/store.d.ts +6 -0
  25. package/build/esm/appstream/store.d.ts.map +1 -0
  26. package/build/esm/appstream/store.js +65 -0
  27. package/build/esm/appstream/web.d.ts +74 -0
  28. package/build/esm/appstream/web.d.ts.map +1 -0
  29. package/build/esm/appstream/web.js +241 -0
  30. package/build/esm/corpus/deploy.d.ts +5 -5
  31. package/build/esm/corpus/deploy.d.ts.map +1 -1
  32. package/build/esm/corpus/deploy.js +83 -28
  33. package/build/esm/corpus/runner.d.ts.map +1 -1
  34. package/build/esm/corpus/runner.js +14 -2
  35. package/build/esm/host/dispatch.d.ts +5 -4
  36. package/build/esm/host/dispatch.d.ts.map +1 -1
  37. package/build/esm/host/dispatch.js +38 -9
  38. package/build/esm/identity/fixture.d.ts +9 -4
  39. package/build/esm/identity/fixture.d.ts.map +1 -1
  40. package/build/esm/identity/memory-store.d.ts +22 -0
  41. package/build/esm/identity/memory-store.d.ts.map +1 -1
  42. package/build/esm/identity/memory-store.js +51 -1
  43. package/build/esm/index.d.ts +8 -2
  44. package/build/esm/index.d.ts.map +1 -1
  45. package/build/esm/index.js +5 -1
  46. package/build/esm/routes/generated.d.ts.map +1 -1
  47. package/build/esm/routes/generated.js +2 -8
  48. package/build/esm/routes/overlay.js +2 -2
  49. package/package.json +5 -4
  50. package/build/cjs/drive/registry.js +0 -38
  51. package/build/esm/drive/registry.d.ts +0 -52
  52. package/build/esm/drive/registry.d.ts.map +0 -1
  53. package/build/esm/drive/registry.js +0 -33
@@ -508,13 +508,7 @@ exports.GENERATED_ROUTES = [
508
508
  summary: 'Remove an app stream entry',
509
509
  params: [
510
510
  {
511
- name: 'appLoc',
512
- in: 'body',
513
- required: true,
514
- type: 'string'
515
- },
516
- {
517
- name: 'streamServiceName',
511
+ name: 'id',
518
512
  in: 'body',
519
513
  required: true,
520
514
  type: 'string'
@@ -532,7 +526,7 @@ exports.GENERATED_ROUTES = [
532
526
  },
533
527
  {
534
528
  status: 404,
535
- description: 'No app is published at that folder'
529
+ description: 'No app is published with that id'
536
530
  }
537
531
  ]
538
532
  },
@@ -251,8 +251,8 @@ exports.OVERLAY = {
251
251
  }
252
252
  },
253
253
  'POST /SASjsApi/drive/deploy/upload': { implemented: true },
254
- // `404` is a pair - the registry name and the appLoc it was published from -
255
- // that matches no entry, and the drive's content is deliberately left alone.
254
+ // `404` is an id the index does not hold - the id is the app, and its label and
255
+ // folder are not handles - and the drive's content is deliberately left alone.
256
256
  'DELETE /SASjsApi/drive/deploy': { implemented: true },
257
257
  // Group - members and the groups themselves
258
258
  'GET /SASjsApi/group': { implemented: true },
@@ -0,0 +1,46 @@
1
+ import type { DeployTree } from '../drive/deploy.js';
2
+ import type { PublishAppRequest } from './service.js';
3
+ /** The file, at the root of an app bundle, that says the bundle is an app. */
4
+ export declare const APP_MANIFEST = "sasjs.app.json";
5
+ export interface AppManifest {
6
+ /** The label the app is listed under. Defaults to the last segment of the folder. */
7
+ name?: string;
8
+ /** The folder under `<appLoc>/services` holding the compiled web assets. */
9
+ streamWebFolder: string;
10
+ /** An asset inside the app, used as its tile image. */
11
+ logo?: string;
12
+ /** Origins allowed to frame the app, as CSP `frame-ancestors` sources. */
13
+ frameAncestors?: string | string[];
14
+ }
15
+ export interface AppBundle {
16
+ /** The tree to deploy: the manifest, when there is one, is not in it. */
17
+ tree: DeployTree;
18
+ manifest?: AppManifest;
19
+ }
20
+ /** A manifest, checked field by field, naming the field that is wrong. */
21
+ export declare const parseAppManifest: (value: unknown) => AppManifest;
22
+ /**
23
+ * The deploy tree split from its manifest.
24
+ *
25
+ * A tree that is not a tree is passed through untouched: the deploy is the thing
26
+ * that refuses a malformed tree, with the message its own cases pin, and saying
27
+ * it here as well would be two wordings of one refusal.
28
+ */
29
+ export declare const splitAppBundle: (tree: unknown) => AppBundle;
30
+ /** What a deploy request says about the app it publishes. */
31
+ export interface DeployPublish {
32
+ appLoc: string;
33
+ streamWebFolder?: string;
34
+ streamServiceName?: string;
35
+ streamLogo?: string;
36
+ }
37
+ /**
38
+ * The publish a deploy asks for, or `undefined` when it publishes nothing.
39
+ *
40
+ * The request wins over the bundle where both speak - a caller naming a folder or
41
+ * a label is correcting the archive, not repeating it - and the bundle fills what
42
+ * the request leaves out, so a deploy that carries a manifest needs neither
43
+ * `streamWebFolder` nor `streamServiceName`.
44
+ */
45
+ export declare const publishRequestFor: (deploy: DeployPublish, manifest?: AppManifest) => PublishAppRequest | undefined;
46
+ //# sourceMappingURL=bundle.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"bundle.d.ts","sourceRoot":"","sources":["../../../src/appstream/bundle.ts"],"names":[],"mappings":"AA2BA,OAAO,KAAK,EAAgB,UAAU,EAAE,MAAM,oBAAoB,CAAA;AAClE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAErD,8EAA8E;AAC9E,eAAO,MAAM,YAAY,mBAAmB,CAAA;AAE5C,MAAM,WAAW,WAAW;IAC1B,qFAAqF;IACrF,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,4EAA4E;IAC5E,eAAe,EAAE,MAAM,CAAA;IACvB,uDAAuD;IACvD,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,0EAA0E;IAC1E,cAAc,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;CACnC;AAED,MAAM,WAAW,SAAS;IACxB,yEAAyE;IACzE,IAAI,EAAE,UAAU,CAAA;IAChB,QAAQ,CAAC,EAAE,WAAW,CAAA;CACvB;AAiBD,0EAA0E;AAC1E,eAAO,MAAM,gBAAgB,GAAI,OAAO,OAAO,KAAG,WAyCjD,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAI,MAAM,OAAO,KAAG,SAoC9C,CAAA;AAED,6DAA6D;AAC7D,MAAM,WAAW,aAAa;IAC5B,MAAM,EAAE,MAAM,CAAA;IACd,eAAe,CAAC,EAAE,MAAM,CAAA;IACxB,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,UAAU,CAAC,EAAE,MAAM,CAAA;CACpB;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,iBAAiB,GAC5B,QAAQ,aAAa,EACrB,WAAW,WAAW,KACrB,iBAAiB,GAAG,SAiBtB,CAAA"}
@@ -0,0 +1,118 @@
1
+ /**
2
+ * An app as one bundle: the deployment and the statement of what it publishes.
3
+ *
4
+ * A deploy writes a tree to a folder, and a tree of an app already holds
5
+ * everything the app is - its services under `services/`, the compiled web assets
6
+ * under `services/<streamWebFolder>`, and whatever jobs and data files it was
7
+ * built with. What a tree cannot say is that the folder IS an app: which of its
8
+ * folders holds the web build, what it should be called, and whether it may be
9
+ * framed. That statement is a small file at the root of the archive:
10
+ *
11
+ * sasjs.app.json
12
+ * services/
13
+ * web/ the compiled app: index.html, main.<hash>.js, assets/
14
+ * build.sas the services the app calls
15
+ * jobs/
16
+ *
17
+ * So one zip deploys the app and the folders under it in a single request, and
18
+ * the app is indexed as part of that deploy rather than by a second call that can
19
+ * fail on its own. The manifest is consumed here: it is metadata, not an asset,
20
+ * so it is stripped from the tree before the tree is written and never appears in
21
+ * the app's served files.
22
+ *
23
+ * The manifest is optional. A deploy that names `streamWebFolder` in its payload
24
+ * publishes without one, which is what an existing client does; a bundle that
25
+ * carries a manifest needs no arguments beyond the folder it deploys to.
26
+ */
27
+ import { ApiError } from '../types.js';
28
+ /** The file, at the root of an app bundle, that says the bundle is an app. */
29
+ export const APP_MANIFEST = 'sasjs.app.json';
30
+ const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
31
+ const text = (value, field) => {
32
+ if (value === undefined)
33
+ return undefined;
34
+ if (typeof value !== 'string' || value.trim() === '')
35
+ throw new ApiError(400, `"${field}" must be a non-empty string in ${APP_MANIFEST}.`);
36
+ return value.trim();
37
+ };
38
+ /** A manifest, checked field by field, naming the field that is wrong. */
39
+ export const parseAppManifest = (value) => {
40
+ if (!isObject(value))
41
+ throw new ApiError(400, `${APP_MANIFEST} must be an object.`);
42
+ const streamWebFolder = text(value.streamWebFolder, 'streamWebFolder');
43
+ if (streamWebFolder === undefined)
44
+ throw new ApiError(400, `${APP_MANIFEST} must state "streamWebFolder": the folder under services/ holding the compiled app.`);
45
+ const name = text(value.name, 'name');
46
+ const logo = text(value.logo, 'logo');
47
+ const frameAncestors = value.frameAncestors;
48
+ if (frameAncestors !== undefined &&
49
+ (typeof frameAncestors !== 'string' || frameAncestors === '') &&
50
+ !(Array.isArray(frameAncestors) &&
51
+ frameAncestors.length > 0 &&
52
+ frameAncestors.every((source) => typeof source === 'string' && source !== '')))
53
+ throw new ApiError(400, `"frameAncestors" in ${APP_MANIFEST} must be a string or a non-empty list of strings.`);
54
+ return {
55
+ ...(name === undefined ? {} : { name }),
56
+ streamWebFolder,
57
+ ...(logo === undefined ? {} : { logo }),
58
+ ...(frameAncestors === undefined
59
+ ? {}
60
+ : { frameAncestors: frameAncestors })
61
+ };
62
+ };
63
+ /**
64
+ * The deploy tree split from its manifest.
65
+ *
66
+ * A tree that is not a tree is passed through untouched: the deploy is the thing
67
+ * that refuses a malformed tree, with the message its own cases pin, and saying
68
+ * it here as well would be two wordings of one refusal.
69
+ */
70
+ export const splitAppBundle = (tree) => {
71
+ if (!isObject(tree) || !Array.isArray(tree.members))
72
+ return { tree: tree };
73
+ const members = tree.members;
74
+ const at = members.findIndex((member) => isObject(member) && member.type === 'file' && member.name === APP_MANIFEST);
75
+ if (at === -1)
76
+ return { tree: tree };
77
+ const member = members[at];
78
+ if (typeof member.code !== 'string')
79
+ throw new ApiError(400, `${APP_MANIFEST} carries no text.`);
80
+ let parsed;
81
+ try {
82
+ parsed = JSON.parse(member.code);
83
+ }
84
+ catch (error) {
85
+ throw new ApiError(400, `${APP_MANIFEST} is not valid JSON: ${error.message}`);
86
+ }
87
+ return {
88
+ tree: {
89
+ ...tree,
90
+ members: members.filter((_, index) => index !== at)
91
+ },
92
+ manifest: parseAppManifest(parsed)
93
+ };
94
+ };
95
+ /**
96
+ * The publish a deploy asks for, or `undefined` when it publishes nothing.
97
+ *
98
+ * The request wins over the bundle where both speak - a caller naming a folder or
99
+ * a label is correcting the archive, not repeating it - and the bundle fills what
100
+ * the request leaves out, so a deploy that carries a manifest needs neither
101
+ * `streamWebFolder` nor `streamServiceName`.
102
+ */
103
+ export const publishRequestFor = (deploy, manifest) => {
104
+ const streamWebFolder = deploy.streamWebFolder ?? manifest?.streamWebFolder;
105
+ if (streamWebFolder === undefined)
106
+ return undefined;
107
+ const name = deploy.streamServiceName ?? manifest?.name;
108
+ const logo = deploy.streamLogo ?? manifest?.logo;
109
+ return {
110
+ appLoc: deploy.appLoc,
111
+ streamWebFolder,
112
+ ...(name === undefined ? {} : { name }),
113
+ ...(logo === undefined ? {} : { logo }),
114
+ ...(manifest?.frameAncestors === undefined
115
+ ? {}
116
+ : { frameAncestors: manifest.frameAncestors })
117
+ };
118
+ };
@@ -0,0 +1,27 @@
1
+ /**
2
+ * An app's id is a UUID assigned once, when the app is first published.
3
+ *
4
+ * Not a hash of anything. Hashing a location was tried and removed: it made the id
5
+ * a function of the path, which forced rules on what a path may look like (lowercase
6
+ * only, no spaces) to keep the hash unambiguous, and it needed a hash implementation
7
+ * that worked identically in Node and in the browser worker the mock drive runs in.
8
+ * A UUID needs none of that: it is generated once, stored, and looked up by `appLoc`
9
+ * when the same folder is published again, so republishing restores the id while the
10
+ * path stays free to be whatever the drive allows.
11
+ *
12
+ * The readable NAME is the label - what a person sees and what a URL shows. The id
13
+ * is the key: what the registry, the routes and the permission rules point at.
14
+ */
15
+ export declare const normaliseAppLoc: (appLoc: string) => string;
16
+ /**
17
+ * A new id: a version 4 UUID.
18
+ *
19
+ * `crypto.randomUUID` exists in Node and in a browser worker on https or localhost,
20
+ * which is where the mock drive runs. The fallback builds the same thing from
21
+ * `getRandomValues` rather than from `Math.random`, so a weaker environment does not
22
+ * quietly produce a weaker id.
23
+ */
24
+ export declare const newAppId: () => string;
25
+ /** Whether a string is a well-formed id: a version 4 UUID. */
26
+ export declare const isAppId: (value: unknown) => value is string;
27
+ //# sourceMappingURL=identity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"identity.d.ts","sourceRoot":"","sources":["../../../src/appstream/identity.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,MAAM,KAAG,MAgBhD,CAAA;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,QAAQ,QAAO,MAkC3B,CAAA;AAOD,8DAA8D;AAC9D,eAAO,MAAM,OAAO,GAAI,OAAO,OAAO,KAAG,KAAK,IAAI,MACD,CAAA"}
@@ -0,0 +1,63 @@
1
+ import { normaliseDrivePath } from '../drive/paths.js';
2
+ import { ApiError } from '../types.js';
3
+ /**
4
+ * An app's id is a UUID assigned once, when the app is first published.
5
+ *
6
+ * Not a hash of anything. Hashing a location was tried and removed: it made the id
7
+ * a function of the path, which forced rules on what a path may look like (lowercase
8
+ * only, no spaces) to keep the hash unambiguous, and it needed a hash implementation
9
+ * that worked identically in Node and in the browser worker the mock drive runs in.
10
+ * A UUID needs none of that: it is generated once, stored, and looked up by `appLoc`
11
+ * when the same folder is published again, so republishing restores the id while the
12
+ * path stays free to be whatever the drive allows.
13
+ *
14
+ * The readable NAME is the label - what a person sees and what a URL shows. The id
15
+ * is the key: what the registry, the routes and the permission rules point at.
16
+ */
17
+ export const normaliseAppLoc = (appLoc) => {
18
+ // An absent location is not the root: coercing it to one would register every
19
+ // caller that forgot to pass an appLoc against the root app's entry.
20
+ if (typeof appLoc !== 'string' || appLoc === '')
21
+ throw new Error(`App location must be a non-empty string, got ${JSON.stringify(appLoc)}.`);
22
+ const normalised = normaliseDrivePath(appLoc);
23
+ // one refusal for one rule: the deploy route refuses an escaping location with
24
+ // this wording and this status, and a host calling in here gets the same
25
+ if (normalised === null)
26
+ throw new ApiError(400, 'appLoc cannot be outside drive.');
27
+ return normalised;
28
+ };
29
+ /**
30
+ * A new id: a version 4 UUID.
31
+ *
32
+ * `crypto.randomUUID` exists in Node and in a browser worker on https or localhost,
33
+ * which is where the mock drive runs. The fallback builds the same thing from
34
+ * `getRandomValues` rather than from `Math.random`, so a weaker environment does not
35
+ * quietly produce a weaker id.
36
+ */
37
+ export const newAppId = () => {
38
+ const webCrypto = globalThis.crypto;
39
+ if (typeof webCrypto?.randomUUID === 'function')
40
+ return webCrypto.randomUUID();
41
+ if (typeof webCrypto?.getRandomValues !== 'function')
42
+ throw new Error('No cryptographic source of randomness is available.');
43
+ const bytes = new Uint8Array(16);
44
+ webCrypto.getRandomValues(bytes);
45
+ // version 4, variant 10xx
46
+ bytes[6] = (bytes[6] & 0x0f) | 0x40;
47
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
48
+ const hex = Array.from(bytes)
49
+ .map((byte) => byte.toString(16).padStart(2, '0'))
50
+ .join('');
51
+ return [
52
+ hex.slice(0, 8),
53
+ hex.slice(8, 12),
54
+ hex.slice(12, 16),
55
+ hex.slice(16, 20),
56
+ hex.slice(20)
57
+ ].join('-');
58
+ };
59
+ // no `i` flag: `newAppId` mints lower case and every lookup compares exactly, so
60
+ // a guard that accepts upper case would vouch for an id no lookup can find
61
+ const APP_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
62
+ /** Whether a string is a well-formed id: a version 4 UUID. */
63
+ export const isAppId = (value) => typeof value === 'string' && APP_ID.test(value);
@@ -0,0 +1,96 @@
1
+ export interface AppStreamEntry {
2
+ /** The identity: a version 4 UUID, minted once and kept for the life of the app. */
3
+ id: string;
4
+ /** The label a person reads. Not unique, not a key, not in any URL. */
5
+ name: string;
6
+ /** The folder the app was deployed to - the one app one folder rule. */
7
+ appLoc: string;
8
+ /** The folder holding the web assets, relative to `appLoc/services`. */
9
+ streamWebFolder: string;
10
+ /** An asset inside the app, served from the app's own URL. */
11
+ logo?: string;
12
+ /** Origins allowed to frame the app, as CSP `frame-ancestors` sources. */
13
+ frameAncestors?: string[];
14
+ /** When this publish happened, ISO 8601. */
15
+ publishedAt: string;
16
+ }
17
+ /**
18
+ * The published apps, as a host stores them.
19
+ *
20
+ * A whole-list read and write because the index is small and a host that has a
21
+ * file, a table or a browser store should not have to implement a query language
22
+ * to hold it. Mutations are serialised by the service, so a store only has to be
23
+ * atomic for a single call.
24
+ */
25
+ export interface AppStreamStore {
26
+ read(): Promise<AppStreamEntry[]>;
27
+ write(entries: AppStreamEntry[]): Promise<void>;
28
+ }
29
+ export interface PublishAppRequest {
30
+ appLoc: string;
31
+ streamWebFolder: string;
32
+ /** The label. Defaults to the last segment of `appLoc`. */
33
+ name?: string;
34
+ logo?: string;
35
+ frameAncestors?: string | string[];
36
+ /** The publish time, for a caller that has a clock of its own (or a test). */
37
+ publishedAt?: string;
38
+ }
39
+ export interface AppStreamService {
40
+ /** Every published app this caller may see, ordered by name. */
41
+ list(allow?: (entry: AppStreamEntry) => boolean): Promise<AppStreamEntry[]>;
42
+ /** One app by id, or the `404` a client that mistyped an id expects. */
43
+ get(id: string): Promise<AppStreamEntry>;
44
+ /** The app published at a folder, if any - the redeploy lookup. */
45
+ forAppLoc(appLoc: string): Promise<AppStreamEntry | undefined>;
46
+ /**
47
+ * Publishes a folder, minting an id the first time and keeping it afterwards.
48
+ *
49
+ * The entry IS the publish: a field the request does not state is absent from
50
+ * the entry rather than inherited from the previous publish, so republishing
51
+ * from a bundle that dropped its logo drops the logo. The label is the one
52
+ * exception - it carries over unless this publish names one - because a redeploy
53
+ * that says nothing about the name is not asking for a rename.
54
+ */
55
+ publish(request: PublishAppRequest): Promise<AppStreamEntry>;
56
+ /** Removes the app the id names, and returns what was removed. */
57
+ unpublish(id: string): Promise<AppStreamEntry>;
58
+ }
59
+ /** What a publish answers: enough for a client to print the app's URL. */
60
+ export declare const appSummary: (entry: AppStreamEntry) => {
61
+ id: string;
62
+ name: string;
63
+ url: string;
64
+ };
65
+ /** The label an app gets when the publish does not name one. */
66
+ export declare const defaultAppName: (appLoc: string) => string;
67
+ /** A publish request with every field in the shape the index stores. */
68
+ export interface CheckedPublish extends Omit<PublishAppRequest, 'frameAncestors'> {
69
+ frameAncestors?: string[];
70
+ }
71
+ /**
72
+ * A publish request, checked and normalised, with no default applied.
73
+ *
74
+ * Separate from `publish` so a host can refuse a publish BEFORE it writes the
75
+ * deployment: the drive and the index are two writes, and a request the index
76
+ * would refuse must not leave the files behind. `name` is left absent when the
77
+ * caller did not state one, because a redeploy inherits the label it had.
78
+ */
79
+ export declare const checkPublishRequest: (request: PublishAppRequest) => CheckedPublish;
80
+ /**
81
+ * The index, over a store.
82
+ *
83
+ * Every mutation reads the whole list, changes it and writes it back, so two
84
+ * publishes that overlap would discard each other's entry - the loser's change
85
+ * vanishing silently, which is the worst way for an index to be wrong. One queue
86
+ * removes the interleaving without a lock.
87
+ */
88
+ export declare const createAppStreamService: (store: AppStreamStore) => AppStreamService;
89
+ /** An index with no storage behind it: what a browser host and the corpus start from. */
90
+ export declare class MemoryAppStreamStore implements AppStreamStore {
91
+ private entries;
92
+ constructor(entries?: AppStreamEntry[]);
93
+ read(): Promise<AppStreamEntry[]>;
94
+ write(entries: AppStreamEntry[]): Promise<void>;
95
+ }
96
+ //# sourceMappingURL=service.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service.d.ts","sourceRoot":"","sources":["../../../src/appstream/service.ts"],"names":[],"mappings":"AA0BA,MAAM,WAAW,cAAc;IAC7B,oFAAoF;IACpF,EAAE,EAAE,MAAM,CAAA;IACV,uEAAuE;IACvE,IAAI,EAAE,MAAM,CAAA;IACZ,wEAAwE;IACxE,MAAM,EAAE,MAAM,CAAA;IACd,wEAAwE;IACxE,eAAe,EAAE,MAAM,CAAA;IACvB,8DAA8D;IAC9D,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,0EAA0E;IAC1E,cAAc,CAAC,EAAE,MAAM,EAAE,CAAA;IACzB,4CAA4C;IAC5C,WAAW,EAAE,MAAM,CAAA;CACpB;AAED;;;;;;;GAOG;AACH,MAAM,WAAW,cAAc;IAC7B,IAAI,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC,CAAA;IACjC,KAAK,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CAChD;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAA;IACd,eAAe,EAAE,MAAM,CAAA;IACvB,2DAA2D;IAC3D,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,cAAc,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAA;IAClC,8EAA8E;IAC9E,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB;AAED,MAAM,WAAW,gBAAgB;IAC/B,gEAAgE;IAChE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,OAAO,GAAG,OAAO,CAAC,cAAc,EAAE,CAAC,CAAA;IAC3E,wEAAwE;IACxE,GAAG,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,CAAA;IACxC,mEAAmE;IACnE,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,GAAG,SAAS,CAAC,CAAA;IAC9D;;;;;;;;OAQG;IACH,OAAO,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,cAAc,CAAC,CAAA;IAC5D,kEAAkE;IAClE,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,cAAc,CAAC,CAAA;CAC/C;AAED,0EAA0E;AAC1E,eAAO,MAAM,UAAU,GACrB,OAAO,cAAc,KACpB;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,GAAG,EAAE,MAAM,CAAA;CAIxC,CAAA;AAaF,gEAAgE;AAChE,eAAO,MAAM,cAAc,GAAI,QAAQ,MAAM,KAAG,MAI/C,CAAA;AA0BD,wEAAwE;AACxE,MAAM,WAAW,cAAe,SAAQ,IAAI,CAC1C,iBAAiB,EACjB,gBAAgB,CACjB;IACC,cAAc,CAAC,EAAE,MAAM,EAAE,CAAA;CAC1B;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,mBAAmB,GAC9B,SAAS,iBAAiB,KACzB,cAuBF,CAAA;AAqCD;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,GACjC,OAAO,cAAc,KACpB,gBAgHF,CAAA;AAED,yFAAyF;AACzF,qBAAa,oBAAqB,YAAW,cAAc;IACzD,OAAO,CAAC,OAAO,CAAkB;gBAErB,OAAO,GAAE,cAAc,EAAO;IAIpC,IAAI,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;IAIjC,KAAK,CAAC,OAAO,EAAE,cAAc,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAGtD"}
@@ -0,0 +1,218 @@
1
+ /**
2
+ * The app index: what has been published, keyed by a UUID.
3
+ *
4
+ * An app is one deployed folder (`appLoc`), the web assets inside it
5
+ * (`appLoc/services/<streamWebFolder>`) and a UUID assigned when it is first
6
+ * published. The id is the key the routes, the listing and the permission rules
7
+ * point at; the name is a label a person reads, and carries no uniqueness rule at
8
+ * all - two apps may be called the same thing without colliding, because nothing
9
+ * is looked up by name.
10
+ *
11
+ * The service is the decisions, and a host supplies the storage. That split is
12
+ * the point of this package: sasjs/server keeps the index in a JSON file beside
13
+ * its drive, the browser build keeps it in the drive it already has, and both
14
+ * answer the same listing because both call this file.
15
+ *
16
+ * One app per folder. Publishing a folder that is already published is the same
17
+ * app published again: it keeps its id (so its URL survives a redeploy) and takes
18
+ * the values the new publish states - except the label, which carries over when
19
+ * the new publish does not name one, so a redeploy that has forgotten what the
20
+ * app is called does not rename it to its folder. Nothing is derived from the
21
+ * path, so a capital, a space or a `..` in a folder name is the drive's business
22
+ * rather than an identity question.
23
+ */
24
+ import { ApiError } from '../types.js';
25
+ import { newAppId, normaliseAppLoc } from './identity.js';
26
+ /** What a publish answers: enough for a client to print the app's URL. */
27
+ export const appSummary = (entry) => ({
28
+ id: entry.id,
29
+ name: entry.name,
30
+ url: `/app/${entry.id}/`
31
+ });
32
+ /** A folder holding web assets: one segment, so it cannot climb out of the app. */
33
+ const webFolderOf = (value) => {
34
+ if (typeof value !== 'string' || value === '')
35
+ throw new ApiError(400, '"streamWebFolder" is required');
36
+ if (value === '.' || value === '..' || /[\\/]/.test(value))
37
+ throw new ApiError(400, 'streamWebFolder must be a single path segment.');
38
+ return value;
39
+ };
40
+ /** The label an app gets when the publish does not name one. */
41
+ export const defaultAppName = (appLoc) => {
42
+ const segment = appLoc.split('/').filter(Boolean).pop();
43
+ return segment ? segment : 'app';
44
+ };
45
+ /**
46
+ * Whether two spellings name one folder.
47
+ *
48
+ * A location that cannot be a folder matches nothing rather than throwing: an
49
+ * index written by hand, or by an older shape, holds one bad entry at most, and
50
+ * that entry must not stop every publish and every redeploy lookup on the host.
51
+ */
52
+ const sameAppLoc = (left, right) => {
53
+ try {
54
+ return normaliseAppLoc(left) === normaliseAppLoc(right);
55
+ }
56
+ catch (_) {
57
+ return false;
58
+ }
59
+ };
60
+ /** The same folder spellings `normaliseAppLoc` collapses, as a `400` rather than a throw. */
61
+ const appLocOf = (value) => {
62
+ try {
63
+ return normaliseAppLoc(value);
64
+ }
65
+ catch (error) {
66
+ throw new ApiError(400, error.message);
67
+ }
68
+ };
69
+ /**
70
+ * A publish request, checked and normalised, with no default applied.
71
+ *
72
+ * Separate from `publish` so a host can refuse a publish BEFORE it writes the
73
+ * deployment: the drive and the index are two writes, and a request the index
74
+ * would refuse must not leave the files behind. `name` is left absent when the
75
+ * caller did not state one, because a redeploy inherits the label it had.
76
+ */
77
+ export const checkPublishRequest = (request) => {
78
+ const appLoc = appLocOf(request.appLoc);
79
+ // the drive root is not a folder an app can live in: a deploy to `/` writes
80
+ // `//index.html`, which nothing can read, so it is refused rather than indexed
81
+ if (appLoc === '/')
82
+ throw new ApiError(400, 'An app cannot be published at the drive root.');
83
+ const logo = logoOf(request.logo);
84
+ const frameAncestors = frameAncestorsOf(request.frameAncestors);
85
+ return {
86
+ appLoc,
87
+ streamWebFolder: webFolderOf(request.streamWebFolder),
88
+ ...(request.name === undefined
89
+ ? {}
90
+ : { name: nameOf(request.name, appLoc) }),
91
+ ...(logo === undefined ? {} : { logo }),
92
+ ...(frameAncestors === undefined ? {} : { frameAncestors }),
93
+ ...(request.publishedAt === undefined
94
+ ? {}
95
+ : { publishedAt: request.publishedAt })
96
+ };
97
+ };
98
+ const nameOf = (value, appLoc) => {
99
+ if (value === undefined)
100
+ return defaultAppName(appLoc);
101
+ if (typeof value !== 'string' || value.trim() === '')
102
+ throw new ApiError(400, '"name" must be a non-empty string');
103
+ return value.trim();
104
+ };
105
+ const logoOf = (value) => {
106
+ if (value === undefined)
107
+ return undefined;
108
+ if (typeof value !== 'string' || value === '')
109
+ throw new ApiError(400, '"logo" must be a non-empty string');
110
+ return value;
111
+ };
112
+ const frameAncestorsOf = (value) => {
113
+ if (value === undefined)
114
+ return undefined;
115
+ const list = Array.isArray(value) ? value : [value];
116
+ if (list.length === 0 ||
117
+ list.some((source) => typeof source !== 'string' || source === ''))
118
+ throw new ApiError(400, '"frameAncestors" must be a string or a non-empty list of strings');
119
+ return [...list];
120
+ };
121
+ /**
122
+ * The index, over a store.
123
+ *
124
+ * Every mutation reads the whole list, changes it and writes it back, so two
125
+ * publishes that overlap would discard each other's entry - the loser's change
126
+ * vanishing silently, which is the worst way for an index to be wrong. One queue
127
+ * removes the interleaving without a lock.
128
+ */
129
+ export const createAppStreamService = (store) => {
130
+ let queue = Promise.resolve();
131
+ const mutate = (work) => {
132
+ // `then(work, work)`: a failed mutation must not poison the queue
133
+ const run = queue.then(work, work);
134
+ queue = run.catch(() => undefined);
135
+ return run;
136
+ };
137
+ const readable = (allow) => store.read().then((entries) => entries
138
+ .filter((entry) => (allow ? allow(entry) : true))
139
+ .map((entry) => ({ ...entry }))
140
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0)));
141
+ return {
142
+ list: readable,
143
+ async get(id) {
144
+ const entry = (await store.read()).find((candidate) => candidate.id === id);
145
+ if (!entry)
146
+ throw new ApiError(404, 'No app is published with that id.');
147
+ return { ...entry };
148
+ },
149
+ async forAppLoc(appLoc) {
150
+ // spelled inconsistently by a caller is still one folder; a location that
151
+ // cannot name a folder simply has no app
152
+ let normalised;
153
+ try {
154
+ normalised = normaliseAppLoc(appLoc);
155
+ }
156
+ catch (_) {
157
+ return undefined;
158
+ }
159
+ const entry = (await store.read()).find((candidate) => sameAppLoc(candidate.appLoc, normalised));
160
+ return entry ? { ...entry } : undefined;
161
+ },
162
+ publish(request) {
163
+ return mutate(async () => {
164
+ const checked = checkPublishRequest(request);
165
+ const appLoc = checked.appLoc;
166
+ const streamWebFolder = checked.streamWebFolder;
167
+ const entries = await store.read();
168
+ // the folder is the app, so a redeploy is the same app published again:
169
+ // it keeps the id its URL depends on, and takes the values this publish
170
+ // states rather than the ones the previous publish left behind
171
+ const existing = entries.find((entry) => sameAppLoc(entry.appLoc, appLoc));
172
+ const logo = checked.logo;
173
+ const frameAncestors = checked.frameAncestors;
174
+ const entry = {
175
+ id: existing ? existing.id : newAppId(),
176
+ // the label is the one field a redeploy inherits: everything else is
177
+ // what this publish states
178
+ name: nameOf(checked.name ?? existing?.name, appLoc),
179
+ appLoc,
180
+ streamWebFolder,
181
+ ...(logo === undefined ? {} : { logo }),
182
+ ...(frameAncestors === undefined ? {} : { frameAncestors }),
183
+ publishedAt: checked.publishedAt ?? new Date().toISOString()
184
+ };
185
+ await store.write([
186
+ ...entries.filter((candidate) => !sameAppLoc(candidate.appLoc, appLoc)),
187
+ entry
188
+ ]);
189
+ return { ...entry };
190
+ });
191
+ },
192
+ unpublish(id) {
193
+ return mutate(async () => {
194
+ const entries = await store.read();
195
+ const index = entries.findIndex((entry) => entry.id === id);
196
+ // the id is the app, and the only handle: a label is shared by design and
197
+ // a folder is where the app was published rather than what it is
198
+ if (index === -1)
199
+ throw new ApiError(404, 'No app is published with that id.');
200
+ const [removed] = entries.splice(index, 1);
201
+ await store.write(entries);
202
+ return { ...removed };
203
+ });
204
+ }
205
+ };
206
+ };
207
+ /** An index with no storage behind it: what a browser host and the corpus start from. */
208
+ export class MemoryAppStreamStore {
209
+ constructor(entries = []) {
210
+ this.entries = entries.map((entry) => ({ ...entry }));
211
+ }
212
+ async read() {
213
+ return this.entries.map((entry) => ({ ...entry }));
214
+ }
215
+ async write(entries) {
216
+ this.entries = entries.map((entry) => ({ ...entry }));
217
+ }
218
+ }
@@ -0,0 +1,6 @@
1
+ import type { DriveService } from '../drive/service.js';
2
+ import type { AppStreamStore } from './service.js';
3
+ /** Where the index lives when a host does not choose: hidden, and not an app's. */
4
+ export declare const APP_STREAM_INDEX = "/.sasjs/apps.json";
5
+ export declare const createDriveAppStreamStore: (drive: DriveService, filePath?: string) => AppStreamStore;
6
+ //# sourceMappingURL=store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../../src/appstream/store.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AACvD,OAAO,KAAK,EAAkB,cAAc,EAAE,MAAM,cAAc,CAAA;AAElE,mFAAmF;AACnF,eAAO,MAAM,gBAAgB,sBAAsB,CAAA;AAgBnD,eAAO,MAAM,yBAAyB,GACpC,OAAO,YAAY,EACnB,WAAU,MAAyB,KAClC,cAsDD,CAAA"}