@oceanum/oceanumlab 4.7.0 → 4.7.2

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 (81) hide show
  1. package/README.md +102 -11
  2. package/lib/DatameshUI.d.ts +1 -6
  3. package/lib/DatameshUI.js +1 -9
  4. package/lib/DatameshWidget.d.ts +18 -2
  5. package/lib/DatameshWidget.js +80 -12
  6. package/lib/StoredNotebooks.d.ts +20 -0
  7. package/lib/StoredNotebooks.js +112 -0
  8. package/lib/Tabs.d.ts +26 -0
  9. package/lib/Tabs.js +45 -0
  10. package/lib/aiBackend.d.ts +1 -1
  11. package/lib/aiBackend.js +1 -1
  12. package/lib/auth/accountWidget.d.ts +35 -0
  13. package/lib/auth/accountWidget.js +95 -0
  14. package/lib/auth/claims.d.ts +3 -0
  15. package/lib/auth/claims.js +25 -0
  16. package/lib/auth/plugin.d.ts +9 -0
  17. package/lib/auth/plugin.js +126 -0
  18. package/lib/auth/serverAuth.d.ts +79 -0
  19. package/lib/auth/serverAuth.js +254 -0
  20. package/lib/auth/startSignIn.d.ts +11 -0
  21. package/lib/auth/startSignIn.js +16 -0
  22. package/lib/auth/tokens.d.ts +102 -0
  23. package/lib/auth/tokens.js +9 -0
  24. package/lib/chatRouter.d.ts +13 -1
  25. package/lib/chatRouter.js +9 -2
  26. package/lib/constants.d.ts +1 -1
  27. package/lib/constants.js +1 -1
  28. package/lib/datameshUiUrl.d.ts +2 -2
  29. package/lib/datameshUiUrl.js +6 -6
  30. package/lib/index.d.ts +8 -1
  31. package/lib/index.js +58 -17
  32. package/lib/share/client.d.ts +84 -0
  33. package/lib/share/client.js +205 -0
  34. package/lib/share/events.d.ts +7 -0
  35. package/lib/share/events.js +9 -0
  36. package/lib/share/notebook.d.ts +184 -0
  37. package/lib/share/notebook.js +277 -0
  38. package/lib/share/oceanumOnly.d.ts +49 -0
  39. package/lib/share/oceanumOnly.js +90 -0
  40. package/lib/share/plugin.d.ts +21 -0
  41. package/lib/share/plugin.js +883 -0
  42. package/lib/share/widgets.d.ts +25 -0
  43. package/lib/share/widgets.js +154 -0
  44. package/package.json +13 -1
  45. package/schema/datamesh-connect.json +3 -12
  46. package/src/DatameshUI.tsx +1 -10
  47. package/src/DatameshWidget.tsx +143 -19
  48. package/src/StoredNotebooks.tsx +206 -0
  49. package/src/Tabs.tsx +102 -0
  50. package/src/__tests__/DatameshWidget.spec.tsx +33 -20
  51. package/src/__tests__/OceanumPanel.spec.tsx +157 -0
  52. package/src/__tests__/StoredNotebooks.spec.tsx +157 -0
  53. package/src/__tests__/Tabs.spec.tsx +168 -0
  54. package/src/__tests__/aiBackend.spec.ts +5 -6
  55. package/src/__tests__/chatRouter.spec.ts +9 -15
  56. package/src/__tests__/datameshUiUrl.spec.ts +4 -3
  57. package/src/__tests__/oceanumOnly.spec.ts +193 -0
  58. package/src/__tests__/pluginArity.spec.ts +24 -0
  59. package/src/__tests__/serverAuth.spec.ts +277 -0
  60. package/src/__tests__/settingsSchema.spec.ts +73 -0
  61. package/src/__tests__/shareClient.spec.ts +314 -0
  62. package/src/__tests__/shareNotebook.spec.ts +451 -0
  63. package/src/__tests__/sharePlugin.spec.ts +426 -0
  64. package/src/aiBackend.ts +1 -1
  65. package/src/auth/accountWidget.ts +113 -0
  66. package/src/auth/claims.ts +30 -0
  67. package/src/auth/plugin.ts +155 -0
  68. package/src/auth/serverAuth.ts +342 -0
  69. package/src/auth/startSignIn.ts +23 -0
  70. package/src/auth/tokens.ts +111 -0
  71. package/src/chatRouter.ts +8 -4
  72. package/src/constants.ts +1 -1
  73. package/src/datameshUiUrl.ts +6 -6
  74. package/src/index.ts +87 -36
  75. package/src/share/client.ts +288 -0
  76. package/src/share/events.ts +10 -0
  77. package/src/share/notebook.ts +416 -0
  78. package/src/share/oceanumOnly.ts +126 -0
  79. package/src/share/plugin.ts +1096 -0
  80. package/src/share/widgets.ts +217 -0
  81. package/style/index.css +266 -13
@@ -0,0 +1,205 @@
1
+ import { isSpecId } from './notebook';
2
+ const MESSAGES = {
3
+ 'signed-out': 'Sign in to Oceanum.io to continue.',
4
+ expired: 'Your Oceanum session has expired, sign in again.',
5
+ forbidden: 'You have no access to this notebook. It may not exist, or was created under another organisation.',
6
+ 'not-found': 'This notebook no longer exists on Oceanum.io.',
7
+ 'too-large': 'The notebook is too large for Oceanum.io (32 MiB limit).',
8
+ network: 'Could not reach Oceanum.io. Check your connection; very large notebooks can also fail this way.',
9
+ invalid: 'Oceanum.io returned an unexpected response.',
10
+ unsupported: 'This Oceanum.io service does not offer that operation yet.'
11
+ };
12
+ /** A spec store failure with a message that is safe to show to the user. */
13
+ export class SpecStoreError extends Error {
14
+ constructor(kind, status = null) {
15
+ super(kind === 'server'
16
+ ? `Oceanum.io returned an error (HTTP ${status}).`
17
+ : MESSAGES[kind]);
18
+ this.kind = kind;
19
+ this.status = status;
20
+ this.name = 'SpecStoreError';
21
+ }
22
+ }
23
+ /** Map a failed HTTP status to an error. */
24
+ export function errorForStatus(status) {
25
+ switch (status) {
26
+ // The spec store's authentication middleware answers a bad or expired token with 400.
27
+ case 400:
28
+ return new SpecStoreError('expired', status);
29
+ // Casbin answers 403 both for no access and for a record that does not exist.
30
+ case 403:
31
+ return new SpecStoreError('forbidden', status);
32
+ case 404:
33
+ return new SpecStoreError('not-found', status);
34
+ case 405:
35
+ // The route is there but not this method: a store from before it had PATCH.
36
+ return new SpecStoreError('unsupported', status);
37
+ case 413:
38
+ return new SpecStoreError('too-large', status);
39
+ default:
40
+ return new SpecStoreError('server', status);
41
+ }
42
+ }
43
+ function isSummary(value) {
44
+ if (typeof value !== 'object' || value === null) {
45
+ return false;
46
+ }
47
+ const v = value;
48
+ return (isSpecId(v.id) &&
49
+ typeof v.name === 'string' &&
50
+ typeof v.modified === 'string');
51
+ }
52
+ function isRecord(value) {
53
+ return isSummary(value) && 'spec' in value;
54
+ }
55
+ /** Client for the `notebook` spec type of the Oceanum spec store. */
56
+ export class SpecStoreClient {
57
+ constructor(options) {
58
+ var _a;
59
+ this._base = `${options.specsUrl.replace(/\/+$/, '')}/specs/notebook`;
60
+ this._getAccessToken = options.getAccessToken;
61
+ this._fetch = (_a = options.fetch) !== null && _a !== void 0 ? _a : ((input, init) => fetch(input, init));
62
+ }
63
+ /** Every notebook the user may read, including public ones. */
64
+ async list() {
65
+ const data = await this._request('GET', this._base, { auth: 'required' });
66
+ if (!Array.isArray(data) || !data.every(isSummary)) {
67
+ throw new SpecStoreError('invalid');
68
+ }
69
+ return data;
70
+ }
71
+ /** Read a record, anonymously when signed out. */
72
+ async get(id) {
73
+ return this._record(await this._request('GET', this._url(id), { auth: 'optional' }));
74
+ }
75
+ /** Create a record. The server mints the id: use the returned record's. */
76
+ async create(body) {
77
+ return this._record(await this._request('POST', this._base, {
78
+ auth: 'required',
79
+ body: pick(body)
80
+ }));
81
+ }
82
+ /** Replace a record's name, description and notebook. */
83
+ async update(id, body) {
84
+ return this._record(await this._request('PUT', this._url(id), {
85
+ auth: 'required',
86
+ body: pick(body)
87
+ }));
88
+ }
89
+ /**
90
+ * Change some of a record's fields and leave the rest as they are. Needs the same
91
+ * write access as `update`, which the store enforces a patch as.
92
+ */
93
+ async patch(id, changes) {
94
+ if (Object.keys(changes).length === 0) {
95
+ // The store answers an empty patch with 400; there is nothing to send anyway.
96
+ throw new SpecStoreError('invalid');
97
+ }
98
+ return this._record(await this._request('PATCH', this._url(id), {
99
+ auth: 'required',
100
+ body: changes
101
+ }));
102
+ }
103
+ /**
104
+ * Give a record a new name, without sending the notebook back with it.
105
+ *
106
+ * Falls back to reading the record and putting it back where the store has no PATCH
107
+ * (production had none when this was written). That fallback races another writer's
108
+ * change to the notebook, which is the whole reason to prefer a patch.
109
+ */
110
+ async rename(id, name) {
111
+ try {
112
+ return await this.patch(id, { name });
113
+ }
114
+ catch (error) {
115
+ if (!(error instanceof SpecStoreError) || error.kind !== 'unsupported') {
116
+ throw error;
117
+ }
118
+ const record = await this.get(id);
119
+ return this.update(id, {
120
+ name,
121
+ description: record.description,
122
+ spec: record.spec
123
+ });
124
+ }
125
+ }
126
+ /** Delete a record (requires admin access to it). */
127
+ async remove(id) {
128
+ await this._request('DELETE', this._url(id), { auth: 'required' });
129
+ }
130
+ /** Grant a permission on a record (requires admin access to it). */
131
+ async addPermission(id, grant) {
132
+ await this._request('POST', `${this._url(id)}/permissions`, {
133
+ auth: 'required',
134
+ body: {
135
+ type: grant.type,
136
+ entity: grant.entity,
137
+ permission: grant.permission
138
+ }
139
+ });
140
+ }
141
+ /**
142
+ * Remove a permission (requires admin access). The server matches the exact grant and
143
+ * answers 404 when there is no such permission.
144
+ */
145
+ async removePermission(id, grant) {
146
+ await this._request('DELETE', `${this._url(id)}/permissions`, {
147
+ auth: 'required',
148
+ body: {
149
+ type: grant.type,
150
+ entity: grant.entity,
151
+ permission: grant.permission
152
+ }
153
+ });
154
+ }
155
+ _url(id) {
156
+ if (!isSpecId(id)) {
157
+ throw new SpecStoreError('invalid');
158
+ }
159
+ return `${this._base}/${id}`;
160
+ }
161
+ _record(data) {
162
+ if (!isRecord(data)) {
163
+ throw new SpecStoreError('invalid');
164
+ }
165
+ return data;
166
+ }
167
+ async _request(method, url, options) {
168
+ const token = await this._getAccessToken();
169
+ if (token === null && options.auth === 'required') {
170
+ throw new SpecStoreError('signed-out');
171
+ }
172
+ const headers = {};
173
+ if (token !== null) {
174
+ headers['Authorization'] = `Bearer ${token}`;
175
+ }
176
+ const init = { method, headers };
177
+ if (options.body !== undefined) {
178
+ headers['Content-Type'] = 'application/json';
179
+ init.body = JSON.stringify(options.body);
180
+ }
181
+ let response;
182
+ try {
183
+ response = await this._fetch(url, init);
184
+ }
185
+ catch (_a) {
186
+ throw new SpecStoreError('network');
187
+ }
188
+ if (!response.ok) {
189
+ throw errorForStatus(response.status);
190
+ }
191
+ if (response.status === 204) {
192
+ return null;
193
+ }
194
+ try {
195
+ return await response.json();
196
+ }
197
+ catch (_b) {
198
+ throw new SpecStoreError('invalid');
199
+ }
200
+ }
201
+ }
202
+ /** Only the fields the server accepts; in particular never send an `id`. */
203
+ function pick(body) {
204
+ return { name: body.name, description: body.description, spec: body.spec };
205
+ }
@@ -0,0 +1,7 @@
1
+ import { Signal } from '@lumino/signaling';
2
+ /**
3
+ * Emits after this extension creates, renames or deletes a notebook record, so the
4
+ * Notebooks tab can list again. A plain module-level signal: the tab and the commands
5
+ * live in different plugins, and the change is the only thing they need to share.
6
+ */
7
+ export declare const notebooksChanged: Signal<object, void>;
@@ -0,0 +1,9 @@
1
+ import { Signal } from '@lumino/signaling';
2
+ /**
3
+ * Emits after this extension creates, renames or deletes a notebook record, so the
4
+ * Notebooks tab can list again. A plain module-level signal: the tab and the commands
5
+ * live in different plugins, and the change is the only thing they need to share.
6
+ */
7
+ // The sender is a throwaway object, not null: Lumino keys its receivers by sender in a
8
+ // WeakMap, which refuses null.
9
+ export const notebooksChanged = new Signal({});
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Notebook records in the Oceanum spec store: the link a local notebook keeps to its
3
+ * record, the body that is stored, and the names, paths and addresses around them.
4
+ *
5
+ * Ported from oceanum-notebook's share-oceanum package, which notebook.oceanum.io will
6
+ * drop in favour of this one.
7
+ */
8
+ import type { INotebookContent } from '@jupyterlab/nbformat';
9
+ /** Notebook metadata key linking a local notebook to its spec store record. */
10
+ export declare const METADATA_KEY = "oceanum";
11
+ /** Folder that notebooks opened from Oceanum.io are written to. */
12
+ export declare const OCEANUM_DIR = "Oceanum";
13
+ /** Query parameter carrying a shared notebook id. */
14
+ export declare const QUERY_PARAM = "oceanum-notebook";
15
+ /**
16
+ * Largest request body we send. Cloud Run rejects requests over 32 MiB; keep a margin
17
+ * for headers and the server's own encoding.
18
+ */
19
+ export declare const MAX_BODY_BYTES: number;
20
+ /** The `oceanum` notebook metadata value. */
21
+ export interface IOceanumLink {
22
+ spec_id: string;
23
+ /** Spec store the id belongs to, so a development id is never PUT to production. */
24
+ specs_url: string;
25
+ description?: string;
26
+ }
27
+ /** A spec store request body for `POST`/`PUT /specs/notebook`. */
28
+ export interface ISpecBody {
29
+ name: string;
30
+ description: string | null;
31
+ spec: INotebookContent;
32
+ }
33
+ /**
34
+ * The fields a `PATCH /specs/notebook/{id}` may change. A field left out keeps its
35
+ * stored value, so a rename need not send the notebook back.
36
+ *
37
+ * The store refuses anything else outright rather than ignoring it, and refuses a patch
38
+ * that carries no field at all, so never send an empty one. `spec` is replaced whole:
39
+ * there is no way to change one key of a stored notebook.
40
+ */
41
+ export interface ISpecPatch {
42
+ name?: string;
43
+ description?: string | null;
44
+ spec?: INotebookContent;
45
+ }
46
+ /** A spec store list entry (the list omits `spec`). */
47
+ export interface ISpecSummary {
48
+ id: string;
49
+ name: string;
50
+ description: string | null;
51
+ /**
52
+ * When the record was created, or last patched. A `PUT` does not touch it, so for a
53
+ * record nothing has patched this is still a creation time.
54
+ */
55
+ modified: string;
56
+ /** Null unless the caller created the record: the store hides other creators. */
57
+ creator: string | null;
58
+ }
59
+ /** A full spec store record. */
60
+ export interface ISpecRecord extends ISpecSummary {
61
+ spec: unknown;
62
+ }
63
+ export type BuildResult = {
64
+ ok: true;
65
+ body: ISpecBody;
66
+ bytes: number;
67
+ strippedOutputs: boolean;
68
+ } | {
69
+ ok: false;
70
+ bytes: number;
71
+ };
72
+ /** Whether `value` is a UUID, and so safe to put in a spec store URL. */
73
+ export declare function isSpecId(value: unknown): value is string;
74
+ /**
75
+ * Read the link from an `oceanum` metadata value, or `null` if it is missing, malformed,
76
+ * or belongs to a different spec store.
77
+ */
78
+ export declare function readLink(value: unknown, specsUrl: string): IOceanumLink | null;
79
+ /** The notebook name stored on Oceanum.io for a local path. */
80
+ export declare function nameFromPath(path: string): string;
81
+ /**
82
+ * The notebook with every cell's `trusted` metadata removed.
83
+ *
84
+ * JupyterLab trusts a cell whose metadata says `trusted: true` and then renders its HTML
85
+ * and Markdown unsanitised, running any script in them. A notebook from the spec store
86
+ * (anyone with write access can edit a record) must arrive untrusted; its outputs
87
+ * become trusted again when the reader re-runs the cells.
88
+ */
89
+ export declare function withoutTrust(content: INotebookContent): INotebookContent;
90
+ /**
91
+ * Build the spec store body for a notebook. The `oceanum` link is not stored in the
92
+ * record. If the body is over `maxBytes`, code-cell outputs and execution counts are
93
+ * dropped; if it is still too large, the result is not ok.
94
+ */
95
+ export declare function buildSpecBody(content: INotebookContent, path: string, specsUrl: string, maxBytes?: number): BuildResult;
96
+ /**
97
+ * The notebook stored in a record, with its `oceanum` link set. Throws if the record
98
+ * does not hold an nbformat 4 notebook.
99
+ */
100
+ export declare function notebookFromRecord(record: ISpecRecord, specsUrl: string): INotebookContent;
101
+ /** Make a record name safe to use as a single path segment. */
102
+ export declare function sanitizeName(name: string): string;
103
+ /**
104
+ * A path `Oceanum/<name>.ipynb` that does not collide with `existing` (file names in the
105
+ * `Oceanum` folder), appending ` (1)`, ` (2)`, ... as needed.
106
+ */
107
+ export declare function uniqueNotebookPath(name: string, existing: Iterable<string>): string;
108
+ /**
109
+ * The names in `existing` that `uniqueNotebookPath` could have given a record called
110
+ * `name`, in the order it would have tried them: `<base>.ipynb`, then `<base> (1).ipynb`,
111
+ * `<base> (2).ipynb` and so on.
112
+ *
113
+ * Opening a record looks through these for the copy a previous session left, so the same
114
+ * record keeps one local file. Without that the second copy is named `<base> (1)`, and
115
+ * since a record takes its name from the file on every save, opening a notebook twice
116
+ * would quietly rename it on Oceanum.
117
+ */
118
+ export declare function notebookNamesFor(name: string, existing: Iterable<string>): string[];
119
+ /**
120
+ * Split a listing into the caller's own notebooks and the rest, newest first.
121
+ *
122
+ * The store only sends `creator` on records the caller created, so anything else it
123
+ * returns is shared with them — directly, or because it is public. Addresses are
124
+ * compared case-insensitively: the store matches entities as case-sensitive globs, so
125
+ * the two sides can differ in case.
126
+ */
127
+ export declare function partitionSummaries(items: readonly ISpecSummary[], email: string | null): {
128
+ mine: ISpecSummary[];
129
+ shared: ISpecSummary[];
130
+ };
131
+ /** Parse a spec store timestamp, which is UTC but usually has no zone designator. */
132
+ export declare function parseTimestamp(value: string): Date | null;
133
+ /**
134
+ * Whether `email` can be granted access. Glob characters are refused: the server
135
+ * matches user entities as globs.
136
+ */
137
+ export declare function isShareableEmail(email: string): boolean;
138
+ /** Addresses typed into the share dialog, split into the ones we can grant and the rest. */
139
+ export interface IParsedShareEmails {
140
+ /** Valid, lower-cased and de-duplicated, in the order first written. */
141
+ emails: string[];
142
+ /** Everything that is not a shareable address, as written, for reporting back. */
143
+ invalid: string[];
144
+ }
145
+ /**
146
+ * Split what the user typed into individual addresses. Commas, semicolons and any
147
+ * whitespace all separate, so one-per-line and a comma-separated list both work.
148
+ *
149
+ * Bare addresses only: a mail client's "To:" line carries display names, and
150
+ * `"Alice B" <alice@example.com>` splits into tokens that are not addresses. Those
151
+ * come back in `invalid` so the user is told, rather than being silently dropped.
152
+ *
153
+ * Addresses are lower-cased because the spec store matches the user entity as a
154
+ * case-sensitive glob against the Auth0 email claim, which Auth0 stores lower case.
155
+ */
156
+ export declare function parseShareEmails(raw: string): IParsedShareEmails;
157
+ /**
158
+ * How to report share failures.
159
+ *
160
+ * `original` means hand the underlying error to the reporter untouched — it holds the
161
+ * only explanation the user gets, and the reporter reads its type to decide whether to
162
+ * offer sign-in. `partial` is only for the case the original error cannot describe on
163
+ * its own: some addresses worked and some did not, so the message has to name them.
164
+ */
165
+ export type ShareReport = {
166
+ kind: 'original';
167
+ } | {
168
+ kind: 'partial';
169
+ named: string[];
170
+ };
171
+ /**
172
+ * Decide how to report a set of failed grants.
173
+ *
174
+ * `entities` are the failed grants' entities, in order; the public grant's entity is
175
+ * the empty string, which names nobody.
176
+ */
177
+ export declare function reportForShareFailures(grantCount: number, entities: readonly string[], needsSignIn: boolean): ShareReport;
178
+ /**
179
+ * The link that opens a shared notebook in this deployment.
180
+ *
181
+ * JupyterLite is static files, so its page is `lab/index.html`; a JupyterLab server
182
+ * serves the application at `lab` and has no `index.html` to route.
183
+ */
184
+ export declare function shareLink(baseUrl: string, pageHref: string, id: string): string;
@@ -0,0 +1,277 @@
1
+ /** Notebook metadata key linking a local notebook to its spec store record. */
2
+ export const METADATA_KEY = 'oceanum';
3
+ /** Folder that notebooks opened from Oceanum.io are written to. */
4
+ export const OCEANUM_DIR = 'Oceanum';
5
+ /** Query parameter carrying a shared notebook id. */
6
+ export const QUERY_PARAM = 'oceanum-notebook';
7
+ /**
8
+ * Largest request body we send. Cloud Run rejects requests over 32 MiB; keep a margin
9
+ * for headers and the server's own encoding.
10
+ */
11
+ export const MAX_BODY_BYTES = 30 * 1024 * 1024;
12
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13
+ /** Whether `value` is a UUID, and so safe to put in a spec store URL. */
14
+ export function isSpecId(value) {
15
+ return typeof value === 'string' && UUID_RE.test(value);
16
+ }
17
+ function isObject(value) {
18
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
19
+ }
20
+ /**
21
+ * Read the link from an `oceanum` metadata value, or `null` if it is missing, malformed,
22
+ * or belongs to a different spec store.
23
+ */
24
+ export function readLink(value, specsUrl) {
25
+ if (!isObject(value) ||
26
+ !isSpecId(value.spec_id) ||
27
+ value.specs_url !== specsUrl) {
28
+ return null;
29
+ }
30
+ const link = { spec_id: value.spec_id, specs_url: specsUrl };
31
+ if (typeof value.description === 'string') {
32
+ link.description = value.description;
33
+ }
34
+ return link;
35
+ }
36
+ /** The notebook name stored on Oceanum.io for a local path. */
37
+ export function nameFromPath(path) {
38
+ var _a;
39
+ const base = (_a = path.split('/').pop()) !== null && _a !== void 0 ? _a : '';
40
+ return base.replace(/\.ipynb$/i, '') || 'Untitled';
41
+ }
42
+ function byteLength(text) {
43
+ return new TextEncoder().encode(text).length;
44
+ }
45
+ function withoutLink(content) {
46
+ const metadata = { ...content.metadata };
47
+ delete metadata[METADATA_KEY];
48
+ return { ...content, metadata };
49
+ }
50
+ /**
51
+ * The notebook with every cell's `trusted` metadata removed.
52
+ *
53
+ * JupyterLab trusts a cell whose metadata says `trusted: true` and then renders its HTML
54
+ * and Markdown unsanitised, running any script in them. A notebook from the spec store
55
+ * (anyone with write access can edit a record) must arrive untrusted; its outputs
56
+ * become trusted again when the reader re-runs the cells.
57
+ */
58
+ export function withoutTrust(content) {
59
+ const cells = content.cells.map(cell => {
60
+ if (!isObject(cell.metadata) || !('trusted' in cell.metadata)) {
61
+ return cell;
62
+ }
63
+ const metadata = { ...cell.metadata };
64
+ delete metadata.trusted;
65
+ return { ...cell, metadata };
66
+ });
67
+ return { ...content, cells };
68
+ }
69
+ function withoutOutputs(content) {
70
+ const cells = content.cells.map(cell => cell.cell_type === 'code'
71
+ ? { ...cell, outputs: [], execution_count: null }
72
+ : cell);
73
+ return { ...content, cells };
74
+ }
75
+ /**
76
+ * Build the spec store body for a notebook. The `oceanum` link is not stored in the
77
+ * record. If the body is over `maxBytes`, code-cell outputs and execution counts are
78
+ * dropped; if it is still too large, the result is not ok.
79
+ */
80
+ export function buildSpecBody(content, path, specsUrl, maxBytes = MAX_BODY_BYTES) {
81
+ var _a;
82
+ const link = readLink((_a = content.metadata) === null || _a === void 0 ? void 0 : _a[METADATA_KEY], specsUrl);
83
+ const make = (spec) => {
84
+ var _a;
85
+ return ({
86
+ name: nameFromPath(path),
87
+ description: (_a = link === null || link === void 0 ? void 0 : link.description) !== null && _a !== void 0 ? _a : null,
88
+ spec
89
+ });
90
+ };
91
+ const full = make(withoutTrust(withoutLink(content)));
92
+ const fullBytes = byteLength(JSON.stringify(full));
93
+ if (fullBytes <= maxBytes) {
94
+ return { ok: true, body: full, bytes: fullBytes, strippedOutputs: false };
95
+ }
96
+ const stripped = make(withoutOutputs(full.spec));
97
+ const strippedBytes = byteLength(JSON.stringify(stripped));
98
+ if (strippedBytes <= maxBytes) {
99
+ return {
100
+ ok: true,
101
+ body: stripped,
102
+ bytes: strippedBytes,
103
+ strippedOutputs: true
104
+ };
105
+ }
106
+ return { ok: false, bytes: strippedBytes };
107
+ }
108
+ /**
109
+ * The notebook stored in a record, with its `oceanum` link set. Throws if the record
110
+ * does not hold an nbformat 4 notebook.
111
+ */
112
+ export function notebookFromRecord(record, specsUrl) {
113
+ const spec = record.spec;
114
+ if (!isObject(spec) ||
115
+ spec.nbformat !== 4 ||
116
+ !Array.isArray(spec.cells) ||
117
+ !isObject(spec.metadata)) {
118
+ throw new Error('This Oceanum.io record is not a valid notebook.');
119
+ }
120
+ const link = { spec_id: record.id, specs_url: specsUrl };
121
+ if (record.description) {
122
+ link.description = record.description;
123
+ }
124
+ const content = withoutTrust(spec);
125
+ return {
126
+ ...content,
127
+ metadata: { ...content.metadata, [METADATA_KEY]: { ...link } }
128
+ };
129
+ }
130
+ /** Make a record name safe to use as a single path segment. */
131
+ export function sanitizeName(name) {
132
+ const clean = name
133
+ .trim()
134
+ .replace(/\.ipynb$/i, '')
135
+ .replace(/[/\\]/g, '-')
136
+ .trim();
137
+ return clean === '' || clean === '.' || clean === '..' ? 'Untitled' : clean;
138
+ }
139
+ /**
140
+ * A path `Oceanum/<name>.ipynb` that does not collide with `existing` (file names in the
141
+ * `Oceanum` folder), appending ` (1)`, ` (2)`, ... as needed.
142
+ */
143
+ export function uniqueNotebookPath(name, existing) {
144
+ const taken = new Set(existing);
145
+ const base = sanitizeName(name);
146
+ let candidate = `${base}.ipynb`;
147
+ for (let i = 1; taken.has(candidate); i++) {
148
+ candidate = `${base} (${i}).ipynb`;
149
+ }
150
+ return `${OCEANUM_DIR}/${candidate}`;
151
+ }
152
+ /**
153
+ * The names in `existing` that `uniqueNotebookPath` could have given a record called
154
+ * `name`, in the order it would have tried them: `<base>.ipynb`, then `<base> (1).ipynb`,
155
+ * `<base> (2).ipynb` and so on.
156
+ *
157
+ * Opening a record looks through these for the copy a previous session left, so the same
158
+ * record keeps one local file. Without that the second copy is named `<base> (1)`, and
159
+ * since a record takes its name from the file on every save, opening a notebook twice
160
+ * would quietly rename it on Oceanum.
161
+ */
162
+ export function notebookNamesFor(name, existing) {
163
+ const base = sanitizeName(name);
164
+ const prefix = `${base} (`;
165
+ const suffix = ').ipynb';
166
+ const plain = [];
167
+ const numbered = [];
168
+ for (const candidate of existing) {
169
+ if (candidate === `${base}.ipynb`) {
170
+ plain.push(candidate);
171
+ continue;
172
+ }
173
+ if (!candidate.startsWith(prefix) || !candidate.endsWith(suffix)) {
174
+ continue;
175
+ }
176
+ const index = candidate.slice(prefix.length, candidate.length - suffix.length);
177
+ if (/^\d+$/.test(index)) {
178
+ numbered.push({ name: candidate, index: Number(index) });
179
+ }
180
+ }
181
+ numbered.sort((a, b) => a.index - b.index);
182
+ return [...plain, ...numbered.map(entry => entry.name)];
183
+ }
184
+ /**
185
+ * Split a listing into the caller's own notebooks and the rest, newest first.
186
+ *
187
+ * The store only sends `creator` on records the caller created, so anything else it
188
+ * returns is shared with them — directly, or because it is public. Addresses are
189
+ * compared case-insensitively: the store matches entities as case-sensitive globs, so
190
+ * the two sides can differ in case.
191
+ */
192
+ export function partitionSummaries(items, email) {
193
+ var _a;
194
+ const me = (_a = email === null || email === void 0 ? void 0 : email.toLowerCase()) !== null && _a !== void 0 ? _a : null;
195
+ const sorted = [...items].sort((a, b) => b.modified.localeCompare(a.modified));
196
+ const isMine = (item) => { var _a; return me !== null && ((_a = item.creator) === null || _a === void 0 ? void 0 : _a.toLowerCase()) === me; };
197
+ return {
198
+ mine: sorted.filter(isMine),
199
+ shared: sorted.filter(item => !isMine(item))
200
+ };
201
+ }
202
+ /** Parse a spec store timestamp, which is UTC but usually has no zone designator. */
203
+ export function parseTimestamp(value) {
204
+ const zoned = /(Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`;
205
+ const date = new Date(zoned);
206
+ return Number.isNaN(date.getTime()) ? null : date;
207
+ }
208
+ /**
209
+ * Whether `email` can be granted access. Glob characters are refused: the server
210
+ * matches user entities as globs.
211
+ */
212
+ export function isShareableEmail(email) {
213
+ return /^[^\s@*?[\]]+@[^\s@*?[\]]+\.[^\s@*?[\]]+$/.test(email);
214
+ }
215
+ /**
216
+ * Split what the user typed into individual addresses. Commas, semicolons and any
217
+ * whitespace all separate, so one-per-line and a comma-separated list both work.
218
+ *
219
+ * Bare addresses only: a mail client's "To:" line carries display names, and
220
+ * `"Alice B" <alice@example.com>` splits into tokens that are not addresses. Those
221
+ * come back in `invalid` so the user is told, rather than being silently dropped.
222
+ *
223
+ * Addresses are lower-cased because the spec store matches the user entity as a
224
+ * case-sensitive glob against the Auth0 email claim, which Auth0 stores lower case.
225
+ */
226
+ export function parseShareEmails(raw) {
227
+ const emails = [];
228
+ const invalid = [];
229
+ const seen = new Set();
230
+ for (const part of raw.split(/[\s,;]+/)) {
231
+ const entry = part.trim();
232
+ if (entry === '') {
233
+ continue;
234
+ }
235
+ const email = entry.toLowerCase();
236
+ if (!isShareableEmail(email)) {
237
+ // Report it as written, so the user recognises what they typed.
238
+ invalid.push(entry);
239
+ continue;
240
+ }
241
+ if (!seen.has(email)) {
242
+ seen.add(email);
243
+ emails.push(email);
244
+ }
245
+ }
246
+ return { emails, invalid };
247
+ }
248
+ /**
249
+ * Decide how to report a set of failed grants.
250
+ *
251
+ * `entities` are the failed grants' entities, in order; the public grant's entity is
252
+ * the empty string, which names nobody.
253
+ */
254
+ export function reportForShareFailures(grantCount, entities, needsSignIn) {
255
+ const named = entities.filter(entity => entity !== '');
256
+ // A sign-in problem must reach the reporter as the original error or the user is
257
+ // never offered a way back in; an unnamed or total failure has nothing extra worth
258
+ // saying.
259
+ if (needsSignIn || named.length === 0 || entities.length >= grantCount) {
260
+ return { kind: 'original' };
261
+ }
262
+ return { kind: 'partial', named };
263
+ }
264
+ /**
265
+ * The link that opens a shared notebook in this deployment.
266
+ *
267
+ * JupyterLite is static files, so its page is `lab/index.html`; a JupyterLab server
268
+ * serves the application at `lab` and has no `index.html` to route.
269
+ */
270
+ export function shareLink(baseUrl, pageHref, id) {
271
+ const app = new URL(pageHref).pathname.endsWith('/index.html')
272
+ ? 'lab/index.html'
273
+ : 'lab';
274
+ const url = new URL(app, new URL(baseUrl, pageHref));
275
+ url.searchParams.set(QUERY_PARAM, id);
276
+ return url.toString();
277
+ }