@gramlot/gramlot 0.3.24 → 0.3.27

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 (144) hide show
  1. package/dist/components/chat/__init__.py +1 -1
  2. package/dist/components/chat/assets/collection.js +3 -3
  3. package/dist/components/chat/assets/index.js +1 -1
  4. package/dist/components/editors/__init__.py +2 -2
  5. package/dist/components/editors/assets/collection.js +21 -20
  6. package/dist/components/editors/assets/index.js +1 -1
  7. package/dist/components/editors/assets/modules/chunk-74O4WKIV.js +1 -0
  8. package/dist/components/editors/assets/modules/{code-mirror-engine-QX4A5FVO.js → code-mirror-engine-RWQTR5G5.js} +29 -29
  9. package/dist/components/editors/assets/modules/{jodit-engine-MMSPIWM7.js → jodit-engine-MTSA4GZ3.js} +292 -292
  10. package/dist/components/editors/assets/modules/markdown-document-VFC23FAY.js +1 -0
  11. package/dist/components/editors/assets/modules/{prose-mirror-engine-IXTRTG6B.js → prose-mirror-engine-GMZPJPNN.js} +13 -13
  12. package/dist/components/grid/__init__.py +3 -2
  13. package/dist/components/grid/assets/collection.js +77 -17
  14. package/dist/components/grid/assets/index.js +1 -1
  15. package/dist/components/grid/grammar.json +78 -1
  16. package/dist/components/grouplets/__init__.py +2 -2
  17. package/dist/components/grouplets/assets/collection.js +3 -20
  18. package/dist/components/grouplets/assets/index.js +1 -1
  19. package/dist/components/grouplets/assets/modules/chunk-BLMUM44K.js +1 -0
  20. package/dist/components/grouplets/assets/modules/markdown-document-YWNZTOKK.js +1 -0
  21. package/dist/components/inputs/__init__.py +1 -1
  22. package/dist/components/inputs/assets/collection.js +59 -34
  23. package/dist/components/inputs/assets/index.js +1 -1
  24. package/dist/components/inputs/grammar.json +64 -0
  25. package/dist/components/layout/__init__.py +1 -1
  26. package/dist/components/layout/assets/collection.js +67 -57
  27. package/dist/components/layout/assets/index.js +1 -1
  28. package/dist/components/layout/grammar.json +35 -0
  29. package/dist/components/selection_trial/__init__.py +1 -1
  30. package/dist/components/selection_trial/assets/collection.js +3 -3
  31. package/dist/components/selection_trial/assets/index.js +1 -1
  32. package/dist/components/selection_trial/grammar.json +35 -0
  33. package/dist/components/tree/__init__.py +1 -1
  34. package/dist/components/tree/assets/collection.js +26 -23
  35. package/dist/components/tree/assets/index.js +1 -1
  36. package/dist/components/tree/grammar.json +341 -1
  37. package/dist/components/typst/__init__.py +1 -1
  38. package/dist/components/typst/assets/collection.js +3 -3
  39. package/dist/components/typst/assets/index.js +1 -1
  40. package/dist/components/uploads/__init__.py +13 -0
  41. package/dist/components/uploads/assets/collection.js +67 -0
  42. package/dist/components/uploads/assets/index.js +3 -0
  43. package/dist/components/uploads/commands.json +7 -0
  44. package/dist/components/uploads/grammar.json +789 -0
  45. package/dist/{components/editors/assets/modules/chunk-OCFLP2K4.js → gramlot-markdown.js} +12 -12
  46. package/dist/gramlot.js +5455 -573
  47. package/dist/gramlot.min.js +1588 -43
  48. package/dist/runtime-notices.json +28 -0
  49. package/package.json +4 -2
  50. package/src/binding/grid-struct.js +1 -1
  51. package/src/binding/providers.js +4 -1
  52. package/src/binding/remote-resolver.js +1 -8
  53. package/src/binding/runtime.js +40 -1
  54. package/src/binding/validation-context.js +41 -0
  55. package/src/browser-camera-provider.d.ts +8 -0
  56. package/src/browser-camera-provider.js +104 -0
  57. package/src/builder/source.js +13 -2
  58. package/src/components/attachment-manager.js +160 -0
  59. package/src/components/bases.js +19 -6
  60. package/src/components/border-container.js +86 -8
  61. package/src/components/buttons.js +11 -1
  62. package/src/components/choice-editor.js +44 -16
  63. package/src/components/database-choices.js +13 -8
  64. package/src/components/editing-status-styles.js +26 -0
  65. package/src/components/editing-status.js +115 -0
  66. package/src/components/field-state.js +44 -58
  67. package/src/components/grid-cell-editor.js +245 -0
  68. package/src/components/grid-grammar.json +42 -0
  69. package/src/components/grid-structure.js +5 -1
  70. package/src/components/grid-styles.js +60 -1
  71. package/src/components/grid.js +103 -11
  72. package/src/components/grouplet-card.js +11 -3
  73. package/src/components/html-preview.js +17 -4
  74. package/src/components/image-crop-dialog.js +272 -0
  75. package/src/components/image-crop.js +79 -0
  76. package/src/components/image-uploader.js +252 -0
  77. package/src/components/inputs.js +4 -3
  78. package/src/components/jodit-engine.js +1 -1
  79. package/src/components/markdown-document.js +2 -2
  80. package/src/components/parameters.js +6 -2
  81. package/src/components/screen-capture.js +43 -0
  82. package/src/components/selected-container.js +6 -2
  83. package/src/components/tree.js +417 -17
  84. package/src/components/typed-editor.js +19 -9
  85. package/src/components/upload-engine.js +156 -0
  86. package/src/components/uploader.js +208 -0
  87. package/src/components/uploads.js +7 -0
  88. package/src/components/validation.js +1 -1
  89. package/src/editing-session.d.ts +26 -0
  90. package/src/editing-session.js +494 -0
  91. package/src/editor-values.js +57 -0
  92. package/src/experiments/selection-trial.js +18 -2
  93. package/src/format.js +22 -7
  94. package/src/gramlot.d.ts +3 -0
  95. package/src/gramlot.js +9 -5
  96. package/src/handlers/device-handler.d.ts +2 -1
  97. package/src/handlers/rpc-handler.d.ts +3 -3
  98. package/src/index-page-styles.js +1 -0
  99. package/src/index.d.ts +14 -1
  100. package/src/index.js +13 -0
  101. package/src/inout.d.ts +2 -0
  102. package/src/inout.js +6 -0
  103. package/src/markdown-loader.d.ts +1 -0
  104. package/src/markdown-loader.js +4 -0
  105. package/src/markdown.d.ts +1 -0
  106. package/src/markdown.js +2 -0
  107. package/src/media-frame.js +9 -0
  108. package/src/renderer/attributes.js +7 -1
  109. package/src/renderer/gramlot-renderer.d.ts +3 -0
  110. package/src/renderer/gramlot-renderer.js +42 -2
  111. package/src/server/assets.d.ts +1 -1
  112. package/src/server/assets.js +1 -1
  113. package/src/server/gramlot-server.d.ts +8 -1
  114. package/src/server/gramlot-server.js +83 -7
  115. package/src/server/index.d.ts +2 -0
  116. package/src/server/index.js +2 -0
  117. package/src/server/page-base.js +17 -4
  118. package/src/server/page.d.ts +13 -1
  119. package/src/server/page.js +6 -0
  120. package/src/server/source-import.d.ts +2 -0
  121. package/src/server/source-import.js +35 -0
  122. package/src/server/upload.d.ts +20 -0
  123. package/src/server/upload.js +142 -0
  124. package/src/server/visual-editor.d.ts +11 -0
  125. package/src/server/visual-editor.js +159 -0
  126. package/src/source-picker.d.ts +9 -0
  127. package/src/source-picker.js +56 -0
  128. package/src/tree-store.d.ts +24 -0
  129. package/src/tree-store.js +193 -0
  130. package/src/validation-run.js +50 -0
  131. package/src/view/button.js +8 -5
  132. package/src/view/controls.js +9 -42
  133. package/src/view/html.js +10 -2
  134. package/src/visual-editor-canvas.js +29 -0
  135. package/src/visual-editor-catalogue.js +34 -0
  136. package/src/visual-editor-icons.js +10 -0
  137. package/src/visual-editor.d.ts +61 -0
  138. package/src/visual-editor.js +1062 -0
  139. package/themes/gramlot-base/theme.css +141 -0
  140. package/tools/gramlot-tools-inspector.js +1 -1
  141. package/tools/inspector-agent.js +1 -1
  142. package/dist/components/editors/assets/modules/chunk-MMJXUHRQ.js +0 -3
  143. package/src/form-state.d.ts +0 -20
  144. package/src/form-state.js +0 -198
@@ -10,7 +10,8 @@ import {fromTytx, toTytx} from '@genrojs/tytx';
10
10
  import {GramlotBuilder} from '../builder/gramlot-builder.js';
11
11
  import {NAME_SYNTAX} from '../builder/name-syntax.js';
12
12
  import {gramlotDev} from './assets.js';
13
- import {ENDPOINT_METHOD, Page, SOURCE_METHOD, resolveDeclared} from './page.js';
13
+ import {ENDPOINT_METHOD, Page, SOURCE_METHOD, UPLOAD_METHOD, resolveDeclared} from './page.js';
14
+ import {UploadRegistry, UploadTarget} from './upload.js';
14
15
  import {InvalidResourceName, SEGMENT, loadOrder} from './resources.js';
15
16
 
16
17
  export class PageExpired extends Error { name = 'PageExpired'; }
@@ -68,8 +69,8 @@ function parseRequest(text) {
68
69
  for (const field of ['id', 'pageId', 'contentType', 'name']) {
69
70
  if (typeof request[field] !== 'string') throw new InvalidRequest(`Request ${field} must be a string`);
70
71
  }
71
- if (!['source', 'data'].includes(request.contentType)) {
72
- throw new InvalidRequest('Request contentType must be source or data');
72
+ if (!['source', 'data', 'upload'].includes(request.contentType)) {
73
+ throw new InvalidRequest('Request contentType must be source, data or upload');
73
74
  }
74
75
  if (!isMapping(request.params)) throw new InvalidRequest('Request params must be a mapping');
75
76
  return request;
@@ -105,8 +106,10 @@ const prefixed = (prefix, url) => url.startsWith('/') && !url.startsWith('//') ?
105
106
  * owner move the expiry to now plus `pageTtl` (GC-230 §010).
106
107
  */
107
108
  export class GramlotServer {
109
+ get markdownUrl() { return this.runtimeUrl.replace(/[^/]+$/, 'gramlot-markdown.js'); }
110
+
108
111
  constructor({runtimeUrl = '/assets/gramlot.js', rpcUrl = '/gramlot/rpc', closeUrl = '/gramlot/close',
109
- rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000, collections = [],
112
+ rootId = 'gramlot-root', pageTtl = 1800, maxPages = 1000, collections = [], uploadsEnabled = false,
110
113
  cssTheme = 'gramlot-base'} = {}) {
111
114
  if (cssTheme !== false && !isThemeName(cssTheme)) {
112
115
  throw new TypeError(`The base theme must be a theme name or false, not ${JSON.stringify(cssTheme)}`);
@@ -118,6 +121,7 @@ export class GramlotServer {
118
121
  }
119
122
  Object.assign(this, {runtimeUrl, rpcUrl, closeUrl, rootId, pageTtl, maxPages, cssTheme});
120
123
  this.pages = new Map();
124
+ this.uploads = uploadsEnabled ? new UploadRegistry() : null;
121
125
  this.collections = [...collections];
122
126
  this.preparedGrammars = new WeakMap();
123
127
  this.environmentPages = new WeakMap();
@@ -235,7 +239,10 @@ export class GramlotServer {
235
239
 
236
240
  prune() {
237
241
  const now = performance.now();
238
- for (const [id, record] of this.pages) if (record.expires <= now) this.pages.delete(id);
242
+ for (const [id, record] of this.pages) if (record.expires <= now) {
243
+ this.pages.delete(id);
244
+ void this.uploads?.closePage(id, record.owner);
245
+ }
239
246
  }
240
247
 
241
248
  /** Describe the root application without registering a page session. */
@@ -329,6 +336,7 @@ export class GramlotServer {
329
336
  head.script(scriptJson({imports: {'@gramlot/gramlot/page': prefixed(prefix, this.runtimeUrl),
330
337
  '@gramlot/gramlot': prefixed(prefix, this.runtimeUrl),
331
338
  '@gramlot/gramlot/components':prefixed(prefix,this.runtimeUrl),
339
+ '@gramlot/gramlot/markdown':prefixed(prefix,this.markdownUrl),
332
340
  ...Object.fromEntries((resources.collections ?? []).map(({name,url})=>[`@gramlot/collections/${encodeURIComponent(name)}`,prefixed(prefix,url)]))}}),
333
341
  {type: 'importmap', nonce});
334
342
  const body = root.body();
@@ -357,7 +365,7 @@ export class GramlotServer {
357
365
  /** Answer the request envelope `text` (TYTX) with the response envelope (TYTX).
358
366
  * Throws only InvalidRequest; every other failure is an outcome in the response,
359
367
  * a value that TYTX cannot serialise included. `identity` is the identity of this call (for
360
- * example the avatar of a login), read only by evaluateAuth; the server keeps nothing of it. */
368
+ * example the avatar of a login), supplied by the host to the fresh Page and evaluateAuth; the server keeps nothing of it between calls. */
361
369
  async call(text, {owner = null, identity = null} = {}) {
362
370
  const request = parseRequest(text);
363
371
  const response = {id: request.id, contentType: request.contentType};
@@ -395,6 +403,8 @@ export class GramlotServer {
395
403
  record.expires = this.#expiry();
396
404
  const page = new record.PageClass();
397
405
  page.pageId = pageId;
406
+ Object.defineProperty(page, 'requestIdentity', {value:identity, writable:false});
407
+ if (contentType === 'upload') return this.#uploadControl(page, pageId, owner, identity, name, params);
398
408
  const source = contentType === 'source';
399
409
  let instance = page;
400
410
  let callable = page.main;
@@ -423,6 +433,68 @@ export class GramlotServer {
423
433
  return builder.toTytx();
424
434
  }
425
435
 
436
+ #uploadOperation(page, operation, owner, identity) {
437
+ const declared = this.nameSyntax.matches(operation) ? resolveDeclared(page, operation, UPLOAD_METHOD) : null;
438
+ if (!declared) throw new EndpointNotFound(`Unknown upload operation: ${operation}`);
439
+ const refused = this.#authOutcome(declared.method[UPLOAD_METHOD].auth, owner, identity);
440
+ if (refused) throw new (refused === 'not_authenticated' ? NotAuthenticated : NotAuthorized)(`Access refused: ${operation}`);
441
+ return declared;
442
+ }
443
+
444
+ async #uploadControl(page, pageId, owner, identity, name, params) {
445
+ if (!this.uploads) throw new EndpointNotFound('Upload is unavailable');
446
+ await this.uploads.expire();
447
+ this.prune();
448
+ if (this.pages.get(pageId)?.owner !== owner) throw new PageExpired('Unknown, expired or unowned page');
449
+ if (name === 'prepare') {
450
+ if (Object.keys(params).sort().join(',') !== 'metadata,operation') throw new TypeError('Invalid upload preparation');
451
+ const {operation, metadata} = params;
452
+ if (typeof operation !== 'string' || !isMapping(metadata) ||
453
+ Object.keys(metadata).sort().join(',') !== 'context,fields,mediaType,name,size' ||
454
+ typeof metadata.name !== 'string' || typeof metadata.mediaType !== 'string' ||
455
+ !Number.isSafeInteger(metadata.size) || metadata.size < 0 || !isMapping(metadata.fields) || !isMapping(metadata.context)) {
456
+ throw new TypeError('Invalid upload metadata');
457
+ }
458
+ const {instance, method} = this.#uploadOperation(page, operation, owner, identity);
459
+ const target = await method.call(instance, metadata);
460
+ let registered = false;
461
+ try {
462
+ this.prune();
463
+ if (this.pages.get(pageId)?.owner !== owner) throw new PageExpired('Unknown, expired or unowned page');
464
+ this.#uploadOperation(page, operation, owner, identity);
465
+ const grant = await this.uploads.prepare({pageId, owner, operation, target, size:metadata.size});
466
+ registered = true;
467
+ this.prune();
468
+ if (this.pages.get(pageId)?.owner !== owner) {
469
+ await this.uploads.closePage(pageId, owner);
470
+ throw new PageExpired('Unknown, expired or unowned page');
471
+ }
472
+ return grant;
473
+ } catch (error) {
474
+ if (target instanceof UploadTarget && !registered) await target.abort();
475
+ throw error;
476
+ }
477
+ }
478
+ if (!['status','cancel'].includes(name) || Object.keys(params).join(',') !== 'transferId') throw new TypeError('Invalid upload control');
479
+ const record = this.uploads.record(params.transferId, pageId, owner);
480
+ this.#uploadOperation(page, record.operation, owner, identity);
481
+ return name === 'status' ? record.transfer.status() : record.transfer.abort();
482
+ }
483
+
484
+ /** Admit a single binary upload; adapters provide the current request identity. */
485
+ admitUpload({pageId, owner = null, identity = null, transferId, authorization}) {
486
+ this.prune();
487
+ if (!this.uploads) throw new EndpointNotFound('Upload is unavailable');
488
+ const record = this.pages.get(pageId);
489
+ if (!record || record.owner !== owner) throw new PageExpired('Unknown, expired or unowned page');
490
+ const page = new record.PageClass();
491
+ page.pageId = pageId;
492
+ Object.defineProperty(page, 'requestIdentity', {value:identity, writable:false});
493
+ const upload = this.uploads.record(transferId, pageId, owner);
494
+ this.#uploadOperation(page, upload.operation, owner, identity);
495
+ return this.uploads.admit(transferId, pageId, owner, authorization);
496
+ }
497
+
426
498
  /** Close the page named by the close message `text`, `{"pageId": string}` as JSON, when `owner`
427
499
  * owns it (GC-230 §125); an unknown or unowned page is left as it is. A text that is not JSON, or
428
500
  * whose pageId is not a string, is an InvalidRequest. */
@@ -440,11 +512,15 @@ export class GramlotServer {
440
512
  }
441
513
 
442
514
  closePage(pageId, {owner = null} = {}) {
443
- if (this.pages.get(pageId)?.owner === owner) this.pages.delete(pageId);
515
+ if (this.pages.get(pageId)?.owner === owner) {
516
+ this.pages.delete(pageId);
517
+ void this.uploads?.closePage(pageId, owner);
518
+ }
444
519
  }
445
520
 
446
521
  /** Forget every registered page; adapters call it on shutdown. */
447
522
  closeAll() {
523
+ for (const [pageId, record] of this.pages) void this.uploads?.closePage(pageId, record.owner);
448
524
  this.pages = new Map();
449
525
  }
450
526
 
@@ -17,3 +17,5 @@ export {InvalidResourceName, parseRequires} from './resources.js';
17
17
  export type {Resources} from './resources.js';
18
18
  export {NAME_SYNTAX, NameSyntax} from '../builder/name-syntax.js';
19
19
  export type {NameSyntaxDescriptor} from '../builder/name-syntax.js';
20
+
21
+ export {UploadTarget} from './upload.js';
@@ -15,3 +15,5 @@ export {gramlotDev, runtimeAsset} from './assets.js';
15
15
  export {checkProtocol} from './conformance.js';
16
16
  export {InvalidResourceName, parseRequires} from './resources.js';
17
17
  export {NAME_SYNTAX, NameSyntax} from '../builder/name-syntax.js';
18
+
19
+ export {UploadTarget} from './upload.js';
@@ -12,7 +12,8 @@ import {NAME_SYNTAX} from '../builder/name-syntax.js';
12
12
  * `__gramlot_source__` and `__gramlot_endpoint__` attributes. */
13
13
  export const SOURCE_METHOD = Symbol('gramlot.source');
14
14
  export const ENDPOINT_METHOD = Symbol('gramlot.endpoint');
15
- const MARKERS = new Map([[SOURCE_METHOD, 'registerSource'], [ENDPOINT_METHOD, 'registerEndpoint']]);
15
+ export const UPLOAD_METHOD = Symbol('gramlot.upload');
16
+ const MARKERS = new Map([[SOURCE_METHOD, 'registerSource'], [ENDPOINT_METHOD, 'registerEndpoint'], [UPLOAD_METHOD, 'registerUpload']]);
16
17
 
17
18
  // The name of a declared method, one segment of NAME_SYNTAX: an ASCII letter, then ASCII letters, digits and `_`.
18
19
  const DECLARED_NAME = /^[A-Za-z][A-Za-z0-9_]*$/;
@@ -34,6 +35,10 @@ export function endpointMethod(page, name) {
34
35
  return declaredMethod(page, name, ENDPOINT_METHOD);
35
36
  }
36
37
 
38
+ export function uploadMethod(page, name) {
39
+ return declaredMethod(page, name, UPLOAD_METHOD);
40
+ }
41
+
37
42
  /**
38
43
  * The method a request names, `{instance, method}`, or null; `method` runs with `this` = `instance`.
39
44
  * `name` is a method of `page` or a path `a.b.c.method` (NAME_SYNTAX) read from `page`: every segment
@@ -62,10 +67,13 @@ function declare(PageClass, methodName, marker, auth) {
62
67
  throw new TypeError(`${register} requires an own method of ${PageClass.name}: ${String(methodName)}`);
63
68
  }
64
69
  if (method[marker]) {
65
- throw new TypeError(`${marker === SOURCE_METHOD ? 'Source method' : 'Endpoint'} already registered: ${methodName}`);
70
+ throw new TypeError(`${marker === SOURCE_METHOD ? 'Source method' : marker === ENDPOINT_METHOD ? 'Endpoint' : 'Upload operation'} already registered: ${methodName}`);
66
71
  }
67
- if (method[SOURCE_METHOD] || method[ENDPOINT_METHOD]) {
68
- throw new TypeError(`${methodName} is declared both as Source method and endpoint`);
72
+ if ([SOURCE_METHOD, ENDPOINT_METHOD, UPLOAD_METHOD].some(existing => method[existing])) {
73
+ const message = marker !== UPLOAD_METHOD && !method[UPLOAD_METHOD]
74
+ ? `${methodName} is declared both as Source method and endpoint`
75
+ : `${methodName} has conflicting declarations`;
76
+ throw new TypeError(message);
69
77
  }
70
78
  method[marker] = {auth};
71
79
  }
@@ -92,6 +100,11 @@ export class Exposed {
92
100
  static registerEndpoint(methodName, {auth = null} = {}) {
93
101
  declare(this, methodName, ENDPOINT_METHOD, auth);
94
102
  }
103
+
104
+ /** Mark an application operation for upload preparation. */
105
+ static registerUpload(methodName, {auth = null} = {}) {
106
+ declare(this, methodName, UPLOAD_METHOD, auth);
107
+ }
95
108
  }
96
109
 
97
110
  /** Server-side page base; unrelated to browser view components. */
@@ -11,17 +11,20 @@ import type {GramlotBuilder} from '../builder/gramlot-builder.js';
11
11
  export const SOURCE_METHOD: unique symbol;
12
12
  /** The marker of an endpoint: `{auth}` on the method. */
13
13
  export const ENDPOINT_METHOD: unique symbol;
14
+ /** The marker of an upload operation. */
15
+ export const UPLOAD_METHOD: unique symbol;
14
16
 
15
17
  /** The registered Source method `name` of `page`, or null. */
16
18
  export function sourceMethod(page: Page, name: string): Function | null;
17
19
  /** The registered endpoint `name` of `page`, or null. */
18
20
  export function endpointMethod(page: Page, name: string): Function | null;
21
+ export function uploadMethod(page: Page, name: string): Function | null;
19
22
  /**
20
23
  * The method a request names, or null; `method` runs with `this` = `instance`. `name` is a method of
21
24
  * `page` or a path `a.b.c.method` read from `page`: every segment is a public attribute whose value is an
22
25
  * `Exposed` instance, and the last one is a method declared with `marker`.
23
26
  */
24
- export function resolveDeclared(page: Page, name: string, marker: typeof SOURCE_METHOD | typeof ENDPOINT_METHOD):
27
+ export function resolveDeclared(page: Page, name: string, marker: typeof SOURCE_METHOD | typeof ENDPOINT_METHOD | typeof UPLOAD_METHOD):
25
28
  {instance: Exposed, method: Function} | null;
26
29
 
27
30
  /**
@@ -41,10 +44,13 @@ export class Exposed {
41
44
  /** Mark the own method `methodName` of this class as an endpoint called with
42
45
  * `contentType: 'data'`, equivalent to the Python `@endpoint`; call it after the class. */
43
46
  static registerEndpoint(methodName: string, options?: {auth?: string | null}): void;
47
+ static registerUpload(methodName: string, options?: {auth?: string | null}): void;
44
48
  }
45
49
 
46
50
  /** Server-side page base; unrelated to browser view components. */
47
51
  export class Page extends Exposed {
52
+ /** Trusted host identity of the current invocation, or null. */
53
+ readonly requestIdentity: unknown;
48
54
  /** The title of the page document. */
49
55
  static title: string;
50
56
  /** Class-local prepared collections; inherited declarations accumulate. */
@@ -85,3 +91,9 @@ export {codeMirrorWithOptions} from '../components/editor-options.js';
85
91
 
86
92
  export {fileSystemTree, FileSystemLogic, FileSystemController, DirectoryResolver} from "../filesystem.js";
87
93
  export {IdeLogic} from "../ide-runtime.js";
94
+
95
+ export {TreeStore, TreeStoreResolver, TreeStoreLogic} from '../tree-store.js';
96
+ export {UploadTarget} from './upload.js';
97
+
98
+ export {VisualEditor} from './visual-editor.js';
99
+ export {SourceImport} from './source-import.js';
@@ -13,3 +13,9 @@ export {codeMirrorWithOptions} from '../components/editor-options.js';
13
13
 
14
14
  export {fileSystemTree, FileSystemLogic, FileSystemController, DirectoryResolver} from "../filesystem.js";
15
15
  export {IdeLogic} from "../ide-runtime.js";
16
+
17
+ export {TreeStore, TreeStoreResolver, TreeStoreLogic} from '../tree-store.js';
18
+ export {UploadTarget} from './upload.js';
19
+
20
+ export {VisualEditor} from './visual-editor.js';
21
+ export {SourceImport} from './source-import.js';
@@ -0,0 +1,2 @@
1
+ import {UploadTarget} from './upload.js';
2
+ export class SourceImport extends UploadTarget { constructor(options?:{catalogue?:"html"|string[]}); }
@@ -0,0 +1,35 @@
1
+ import {validateCatalogue, validateCatalogueSource} from '../visual-editor-catalogue.js';
2
+ import {fromTytx} from '@genrojs/tytx';
3
+ import {SourceBag} from '@genrojs/builders';
4
+ import {UploadTarget} from './upload.js';
5
+ export class SourceImport extends UploadTarget {
6
+ constructor({catalogue = null} = {}) {
7
+ super({maxBytes:5 * 1024 * 1024});
8
+ validateCatalogue(catalogue);
9
+ this.catalogue = catalogue;
10
+ this.decoder = new TextDecoder('utf-8', {fatal:true});
11
+ this.parts = [];
12
+ this.outcome = {state:'pending'};
13
+ }
14
+ write(chunk) { this.parts.push(this.decoder.decode(chunk, {stream:true})); }
15
+ finish() {
16
+ this.parts.push(this.decoder.decode());
17
+ const wire = this.parts.join('');
18
+ this.parts = [];
19
+ const source = fromTytx(wire);
20
+ if (!(source instanceof SourceBag) || source.length !== 1 || source.getNodes()[0].label !== 'pageRoot') {
21
+ throw new TypeError('Expected one pageRoot Source');
22
+ }
23
+ validateCatalogueSource(this.catalogue, source);
24
+ this.outcome = {state:'completed', result:wire};
25
+ return this.outcome;
26
+ }
27
+ abort() {
28
+ if (this.outcome.state !== 'completed') {
29
+ this.parts = [];
30
+ this.outcome = {state:'unsaved'};
31
+ }
32
+ return this.outcome;
33
+ }
34
+ status() { return this.outcome; }
35
+ }
@@ -0,0 +1,20 @@
1
+ /** Application-owned destination for one upload; methods may be asynchronous. */
2
+ export class UploadTarget {
3
+ constructor(options: {maxBytes: number});
4
+ readonly maxBytes: number;
5
+ write(chunk: Uint8Array): void | Promise<void>;
6
+ finish(): UploadOutcome | Promise<UploadOutcome>;
7
+ abort(): UploadOutcome | Promise<UploadOutcome>;
8
+ status(): UploadOutcome | Promise<UploadOutcome>;
9
+ }
10
+ export type UploadOutcome = {state: 'completed'; result: unknown} | {state: 'unsaved' | 'pending' | 'uncertain'};
11
+
12
+ /** Internal serialized transfer returned to a binary adapter. */
13
+ export class UploadTransfer {
14
+ constructor(target: UploadTarget, size: number);
15
+ readonly size: number;
16
+ write(chunk: Uint8Array): Promise<void>;
17
+ finish(): Promise<UploadOutcome>;
18
+ abort(): Promise<UploadOutcome>;
19
+ status(): Promise<UploadOutcome>;
20
+ }
@@ -0,0 +1,142 @@
1
+ /** Application-owned destination for a single upload. */
2
+ export class UploadTarget {
3
+ constructor({maxBytes}) {
4
+ if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
5
+ throw new TypeError('maxBytes must be a nonnegative safe integer');
6
+ }
7
+ this.maxBytes = maxBytes;
8
+ }
9
+ write(chunk) { throw new Error('UploadTarget.write must be implemented'); }
10
+ finish() { throw new Error('UploadTarget.finish must be implemented'); }
11
+ abort() { throw new Error('UploadTarget.abort must be implemented'); }
12
+ status() { throw new Error('UploadTarget.status must be implemented'); }
13
+ }
14
+
15
+ import {toTytx} from '@genrojs/tytx';
16
+
17
+ function checkedOutcome(value) {
18
+ if (value === null || typeof value !== 'object' || Object.getPrototypeOf(value) !== Object.prototype ||
19
+ !['completed', 'unsaved', 'pending', 'uncertain'].includes(value.state)) {
20
+ throw new TypeError('Invalid upload outcome');
21
+ }
22
+ const keys = Object.keys(value).sort().join(',');
23
+ if (keys !== (value.state === 'completed' ? 'result,state' : 'state')) {
24
+ throw new TypeError('Invalid upload outcome fields');
25
+ }
26
+ if (value.state === 'completed') toTytx(value.result);
27
+ return {...value};
28
+ }
29
+
30
+ /** A serialized operation on an application-owned upload target. */
31
+ export class UploadTransfer {
32
+ #tail = Promise.resolve();
33
+ #state = {state:'pending'};
34
+ #received = 0;
35
+ #sealed = false;
36
+ constructor(target, size, onOutcome = null) {
37
+ if (!(target instanceof UploadTarget)) throw new TypeError('Upload operation must return an UploadTarget');
38
+ if (!Number.isSafeInteger(size) || size < 0 || size > target.maxBytes) throw new RangeError('Invalid upload size');
39
+ this.target = target;
40
+ this.size = size;
41
+ this.onOutcome = onOutcome;
42
+ }
43
+ #run(action) {
44
+ const current = this.#tail.then(action);
45
+ this.#tail = current.catch(() => {});
46
+ return current;
47
+ }
48
+ #record(outcome) { this.#state = checkedOutcome(outcome); if (this.#state.state === 'completed') this.onOutcome?.(); return {...this.#state}; }
49
+ #terminal() { return ['completed', 'unsaved'].includes(this.#state.state); }
50
+ write(chunk) {
51
+ return this.#run(async () => {
52
+ if (!(chunk instanceof Uint8Array)) throw new TypeError('Upload chunks must be Uint8Array');
53
+ if (this.#state.state !== 'pending' || this.#sealed) throw new Error('Upload is not writable');
54
+ if (this.#received + chunk.byteLength > this.size) throw new RangeError('Upload exceeds declared size');
55
+ try { await this.target.write(chunk); }
56
+ catch (error) { this.#state = {state:'uncertain'}; this.#sealed = true; this.onOutcome?.(); throw error; }
57
+ this.#received += chunk.byteLength;
58
+ });
59
+ }
60
+ finish() {
61
+ return this.#run(async () => {
62
+ if (this.#state.state !== 'pending' || this.#sealed) throw new Error('Upload cannot be finished');
63
+ if (this.#received !== this.size) throw new RangeError('Upload size does not match declaration');
64
+ this.#sealed = true;
65
+ try { return this.#record(await this.target.finish()); }
66
+ catch (error) { this.#state = {state:'uncertain'}; this.onOutcome?.(); throw error; }
67
+ });
68
+ }
69
+ abort() {
70
+ return this.#run(async () => {
71
+ if (this.#terminal()) return {...this.#state};
72
+ this.#sealed = true;
73
+ try { return this.#record(await this.target.abort()); }
74
+ catch (error) { this.#state = {state:'uncertain'}; throw error; }
75
+ });
76
+ }
77
+ status() {
78
+ return this.#run(async () => {
79
+ if (this.#terminal()) return {...this.#state};
80
+ try { return this.#record(await this.target.status()); }
81
+ catch (error) { this.#state = {state:'uncertain'}; throw error; }
82
+ });
83
+ }
84
+ }
85
+
86
+ /** Private server registry: grants are one-use and bound to a page and its owner. */
87
+ export class UploadRegistry {
88
+ constructor({capacity = 1000, grantTtl = 300000, retention = 1800000} = {}) {
89
+ this.records = new Map();
90
+ Object.assign(this, {capacity, grantTtl, retention});
91
+ }
92
+ async expire() {
93
+ const now = performance.now();
94
+ for (const [id, record] of this.records) {
95
+ if (record.expires <= now || (!record.started && record.grantExpires <= now)) {
96
+ const expires = record.expires;
97
+ try { await record.transfer.abort(); } catch {} // The outcome can remain uncertain.
98
+ if (record.expires === expires) this.records.delete(id);
99
+ }
100
+ }
101
+ }
102
+ async prepare({pageId, owner, operation, target, size}) {
103
+ await this.expire();
104
+ if (this.records.size >= this.capacity) throw new Error('Upload registry capacity reached');
105
+ const transferId = crypto.randomUUID();
106
+ const transfer = new UploadTransfer(target, size, () => {
107
+ const record = this.records.get(transferId);
108
+ if (record) record.expires = performance.now() + this.retention;
109
+ });
110
+ const authorization = crypto.randomUUID() + crypto.randomUUID();
111
+ const now = performance.now();
112
+ this.records.set(transferId, {pageId, owner, operation, transfer, authorization,
113
+ started:false, grantExpires:now + this.grantTtl, expires:now + this.retention});
114
+ return {transferId, authorization};
115
+ }
116
+ record(transferId, pageId, owner) {
117
+ const record = this.records.get(transferId);
118
+ if (!record || record.pageId !== pageId || record.owner !== owner) throw new Error('Unknown or unauthorized upload');
119
+ return record;
120
+ }
121
+ admit(transferId, pageId, owner, authorization) {
122
+ const record = this.record(transferId, pageId, owner);
123
+ if (record.started || record.grantExpires <= performance.now() || record.authorization !== authorization) {
124
+ throw new Error('Invalid upload authorization');
125
+ }
126
+ record.started = true;
127
+ record.authorization = null;
128
+ record.expires = performance.now() + this.retention;
129
+ return record.transfer;
130
+ }
131
+ touch(transferId, pageId, owner) {
132
+ this.record(transferId, pageId, owner).expires = performance.now() + this.retention;
133
+ }
134
+ async closePage(pageId, owner) {
135
+ for (const [id, record] of this.records) {
136
+ if (record.pageId === pageId && record.owner === owner) {
137
+ this.records.delete(id);
138
+ try { await record.transfer.abort(); } catch {} // The page can no longer query this outcome.
139
+ }
140
+ }
141
+ }
142
+ }
@@ -0,0 +1,11 @@
1
+ import type {SourceBagNode} from '@genrojs/builders';
2
+ export interface PageCodeDocument {language:'python'|'javascript'; key:string; path:string; content:string; revision:string; writable:boolean;}
3
+ export class VisualEditor {
4
+ constructor(parent:SourceBagNode, options?:{datapath?:string; dataRoot?:string; editorId?:string; uploadOperation?:string; codeDocument?:PageCodeDocument; catalogue?:"html"|string[]; fileCommands?:boolean; canvasCss?:string[]; [attribute:string]:unknown});
5
+ pane:SourceBagNode;
6
+ frame:SourceBagNode;
7
+ toolbar:SourceBagNode;
8
+ rail:SourceBagNode;
9
+ design:SourceBagNode;
10
+ codeDocument(document:PageCodeDocument, frame?:SourceBagNode):void;
11
+ }