trebol-dev 0.2.0 → 0.3.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.
@@ -0,0 +1 @@
1
+ {"demo": true}
package/app/app.trb CHANGED
@@ -41,11 +41,17 @@ hist: none ; the history of the file being designed
41
41
 
42
42
  ; the file API answers only the designer's own pages, which say so with this header
43
43
  api-get: func [url] [fetch/with url [headers: [X-Trebol-Dev "1"]]]
44
- api-put: func [url content] [fetch/with url [method: 'PUT body: content headers: [X-Trebol-Dev "1"]]]
44
+ ; the answer comes whole (status and body), so a save the server refuses is not an error
45
+ api-put: func [url content] [fetch/with url [method: 'PUT body: content headers: [X-Trebol-Dev "1"] full: true]]
46
+ ; the version of a file's text the server knows it by: the SHA-256 of its bytes
47
+ text-version: func [t [string!]] [lowercase enbase/base checksum t 'sha256 16]
45
48
 
46
49
  read-files: function [] [
47
- ; no file API answers on a web page: the demo project, saved by downloading
48
- either error? r: try [api-get "/api/files"] [
50
+ ; the listing is asked for next to the page: under trebol-dev the server answers it with the
51
+ ; project; on a web page (the demo trebol build made) it is the file api/files.json, which says
52
+ ; demo, so the page asks for nothing that is not there. With neither: the demo project too,
53
+ ; saved by downloading
54
+ either any [error? r: try [api-get "api/files.json"] r/demo] [
49
55
  set 'demo copy demo-files
50
56
  set 'demo-saved copy demo-files
51
57
  project-name/text: "demo: Save downloads the file"
@@ -88,7 +94,24 @@ save-file: function [] [
88
94
  put demo-saved path text
89
95
  download last split path #"/" text
90
96
  ] [
91
- api-put rejoin ["/api/file?path=" enhex path] text
97
+ url: rejoin ["/api/file?path=" enhex path]
98
+ ; base: the text as last read or saved here; the server refuses it if the file changed since
99
+ r: api-put rejoin [url "&base=" text-version saved] text
100
+ if r/status = 412 [
101
+ either confirm/role rejoin [
102
+ path " was changed outside the designer since it was opened. Save over that change?"
103
+ " No reads the file again, and undo brings back what is here."
104
+ ] 'danger [
105
+ r: api-put url text
106
+ ] [
107
+ t: api-get url
108
+ set 'saved t
109
+ write-text t
110
+ toast rejoin [path " is read again"]
111
+ exit
112
+ ]
113
+ ]
114
+ unless r/status = 200 [do make error! rejoin ["Not saved: " r/status " " r/body]]
92
115
  ]
93
116
  set 'saved text
94
117
  toast "Saved"
@@ -109,30 +109,46 @@ redraw-machines: function [] [
109
109
  ]
110
110
  ]
111
111
 
112
- ; what the engine says is wrong with each machine: the first mistake it finds, where it is written
112
+ ; what the engine says is wrong with each machine: the first mistake it finds, where it is written; or,
113
+ ; when it is made, its warnings (a state no way leads to yet), each starting with warning:
113
114
  machine-problems-of: function [] [
114
115
  collect [
115
116
  foreach m ms [
117
+ named: either m/name [rejoin [m/name ": "]] [""]
116
118
  if all [m/kind <> 'fragment late: late-use-problem d ms m] [
117
- keep make map! reduce ['at any [late/1 ""] 'message rejoin [either m/name [rejoin [m/name ": "]] [""] late/2]]
119
+ keep make map! reduce ['at any [late/1 ""] 'message rejoin [named late/2]]
118
120
  continue
119
121
  ]
120
122
  e: either m/kind = 'fragment [fragment-problem m] [try [machine-engine/make-machine engine-block ms m]]
121
123
  if error? e [
122
124
  msg: e/message
123
125
  if find/match msg "machine: " [msg: skip msg 9]
124
- keep make map! reduce ['at any [e/at ""] 'message rejoin [either m/name [rejoin [m/name ": "]] [""] msg]]
126
+ keep make map! reduce ['at any [e/at ""] 'message rejoin [named msg]]
127
+ ]
128
+ if object? e [
129
+ foreach [p msg] e/warnings [
130
+ keep make map! reduce ['at any [loaded-at p ""] 'message rejoin ["warning: " named msg] 'warning true]
131
+ ]
125
132
  ]
126
133
  ]
127
134
  ]
128
135
  ]
129
136
 
137
+ ; "No problems", "2 problems", "1 problem, 1 warning", "No problems, 2 warnings"
138
+ problem-count-text: function [n [integer!] w [integer!]] [
139
+ t: copy either n = 0 ["No problems"] [rejoin [n either n = 1 [" problem"] [" problems"]]]
140
+ if w > 0 [append t rejoin [", " w either w = 1 [" warning"] [" warnings"]]]
141
+ t
142
+ ]
143
+
130
144
  show-machine-problems: function [] [
131
145
  machine-problems/data: machine-problems-of
132
146
  machine-problems/hidden: empty? machine-problems/data
133
147
  if d [
134
- n: (length? problems/data) + length? machine-problems/data
135
- problem-count/text: either n = 0 ["No problems"] [rejoin [n either n = 1 [" problem"] [" problems"]]]
148
+ w: 0
149
+ foreach p machine-problems/data [if select p 'warning [w: w + 1]]
150
+ n: (length? problems/data) + (length? machine-problems/data) - w
151
+ problem-count/text: problem-count-text n w
136
152
  ]
137
153
  ]
138
154
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trebol-dev",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "The visual designer for Trebol: lays out screens with Trebol's faces and writes the Trebol code back, keeping yours as you wrote it.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -38,7 +38,7 @@
38
38
  "build:graph": "esbuild editor/machine-graph.js --bundle --minify --format=esm --target=es2022 --legal-comments=eof --outfile=app/machine-graph.js && { printf '/*! elkjs 0.12.1, https://github.com/kieler/elkjs, EPL-2.0 OR GPL-3.0-or-later */\\n'; cat node_modules/elkjs/lib/elk-worker.min.js; } > app/elk-worker.js"
39
39
  },
40
40
  "dependencies": {
41
- "trebol": "^0.4.0"
41
+ "trebol": "^0.5.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "@codemirror/commands": "^6.11.1",
package/server/files.js CHANGED
@@ -4,7 +4,8 @@
4
4
  // itself may ask: the Host must be a local name (no DNS rebinding) and requests carry the
5
5
  // X-Trebol-Dev header, which a page of another site cannot send without the server agreeing.
6
6
 
7
- import { readFile, writeFile, readdir, realpath } from 'node:fs/promises';
7
+ import { createHash } from 'node:crypto';
8
+ import { readFile, writeFile, readdir, realpath, rename, rm } from 'node:fs/promises';
8
9
  import { basename, dirname, extname, relative, resolve, sep } from 'node:path';
9
10
 
10
11
  /** Folders never listed nor read: tools' output and other people's code. */
@@ -61,11 +62,37 @@ export async function listFiles(root) {
61
62
  return out.sort();
62
63
  }
63
64
 
64
- function send(res, status, body, type = 'text/plain; charset=utf-8') {
65
- res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store' });
65
+ function send(res, status, body, type = 'text/plain; charset=utf-8', more = {}) {
66
+ res.writeHead(status, { 'content-type': type, 'cache-control': 'no-store', ...more });
66
67
  res.end(body);
67
68
  }
68
69
 
70
+ /** The version of a file's text: the SHA-256 of its UTF-8 bytes, in lowercase hex. */
71
+ export function versionOf(text) {
72
+ return createHash('sha256').update(text, 'utf8').digest('hex');
73
+ }
74
+
75
+ /** The version a save says it read (?base=), lowercase, or null when it names none. */
76
+ function baseOf(url) {
77
+ const b = url.searchParams.get('base');
78
+ return b === null || b.trim() === '' ? null : b.trim().toLowerCase();
79
+ }
80
+
81
+ /**
82
+ * Writes text to path all at once: into a file beside it, then renamed over it, so a reader
83
+ * never sees half of it and a failed write leaves the old file whole.
84
+ */
85
+ async function writeWhole(path, text) {
86
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
87
+ try {
88
+ await writeFile(tmp, text, 'utf8');
89
+ await rename(tmp, path);
90
+ } catch (e) {
91
+ await rm(tmp, { force: true });
92
+ throw e;
93
+ }
94
+ }
95
+
69
96
  async function bodyOf(req) {
70
97
  const chunks = [];
71
98
  let size = 0;
@@ -77,15 +104,18 @@ async function bodyOf(req) {
77
104
  return Buffer.concat(chunks).toString('utf8');
78
105
  }
79
106
 
80
- /** Answers /api/files and /api/file; gives false for every other request. */
107
+ /**
108
+ * Answers /api/files.json (the listing, which on a page of trebol build is the static file
109
+ * app/api/files.json saying demo) and /api/file; gives false for every other request.
110
+ */
81
111
  export async function handleApi(req, res, url) {
82
- if (url.pathname !== '/api/files' && url.pathname !== '/api/file') return false;
112
+ if (url.pathname !== '/api/files.json' && url.pathname !== '/api/file') return false;
83
113
  if (!trusted(req)) {
84
114
  send(res, 403, 'Only the designer may ask for the files of the project.');
85
115
  return true;
86
116
  }
87
117
  const root = projectRoot();
88
- if (url.pathname === '/api/files') {
118
+ if (url.pathname === '/api/files.json') {
89
119
  if (req.method !== 'GET') return send(res, 405, 'GET only'), true;
90
120
  send(res, 200, JSON.stringify({ name: basename(root), files: await listFiles(root) }), 'application/json');
91
121
  return true;
@@ -98,12 +128,22 @@ export async function handleApi(req, res, url) {
98
128
  if (req.method === 'GET') {
99
129
  const text = await readFile(path, 'utf8').catch(() => null);
100
130
  if (text === null) send(res, 404, 'No such file.');
101
- else send(res, 200, text);
131
+ else send(res, 200, text, undefined, { etag: `"${versionOf(text)}"` });
102
132
  } else if (req.method === 'PUT') {
103
133
  const text = await bodyOf(req);
104
134
  if (text === null) return send(res, 413, 'Too big.'), true;
105
- await writeFile(path, text, 'utf8');
106
- send(res, 200, 'Saved.');
135
+ // base names the version the designer read: when the file changed since, the edit made
136
+ // outside is not lost, the designer is told and asks the person
137
+ const base = baseOf(url);
138
+ if (base !== null) {
139
+ const now = await readFile(path, 'utf8').catch(() => null);
140
+ if (now === null || versionOf(now) !== base) {
141
+ const more = now === null ? {} : { etag: `"${versionOf(now)}"` };
142
+ return send(res, 412, now === null ? 'The file is gone.' : 'The file changed since it was read.', undefined, more), true;
143
+ }
144
+ }
145
+ await writeWhole(path, text);
146
+ send(res, 200, 'Saved.', undefined, { etag: `"${versionOf(text)}"` });
107
147
  } else {
108
148
  send(res, 405, 'GET or PUT only');
109
149
  }