javascript-solid-server 0.0.195 → 0.0.197

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.195",
3
+ "version": "0.0.197",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -90,11 +90,20 @@ function findGitDir(repoPath) {
90
90
  }
91
91
 
92
92
  /**
93
- * Auto-initialize a bare git repo at repoAbs to accept a first push, but
94
- * only when it's safe to do so. The caller must invoke this *after* the
95
- * standard ACL Write check has passed (i.e. inside the existing
96
- * preHandler-gated path for `git-receive-pack`), so authorization is
97
- * already enforced.
93
+ * Auto-initialize a regular (non-bare) git repo at repoAbs to accept a
94
+ * first push, but only when it's safe to do so. The caller must invoke
95
+ * this *after* the standard ACL Write check has passed (i.e. inside the
96
+ * existing preHandler-gated path for `git-receive-pack`), so
97
+ * authorization is already enforced.
98
+ *
99
+ * Regular (not bare): the repo has a `.git/` subdirectory plus a
100
+ * working tree. Combined with the `receive.denyCurrentBranch
101
+ * updateInstead` config the main handler sets on every push, the
102
+ * working tree is auto-extracted on each push. This means pushed files
103
+ * appear as static resources at the corresponding pod URL — the "apps
104
+ * live in pods" install pattern works end-to-end. (Bare repos store
105
+ * content in pack files only, so a pushed `index.html` wouldn't be
106
+ * servable as HTTP.)
98
107
  *
99
108
  * Safe iff one of:
100
109
  * - the target path does not exist (we create it), or
@@ -123,7 +132,7 @@ function findGitDir(repoPath) {
123
132
  * @param {object} [log] - optional Fastify request logger for diagnostics
124
133
  * @returns {{gitDir: string, isRegular: boolean}|null}
125
134
  */
126
- function tryAutoInitBareRepo(repoAbs, log) {
135
+ function tryAutoInitRepo(repoAbs, log) {
127
136
  try {
128
137
  if (existsSync(repoAbs)) {
129
138
  if (!statSync(repoAbs).isDirectory()) return null;
@@ -131,18 +140,24 @@ function tryAutoInitBareRepo(repoAbs, log) {
131
140
  } else {
132
141
  mkdirSync(repoAbs, { recursive: true });
133
142
  }
134
- const result = spawnSync('git', ['init', '--bare', repoAbs], {
143
+ // Pin the initial branch to `main` regardless of the server's
144
+ // `init.defaultBranch` config. `receive.denyCurrentBranch
145
+ // updateInstead` only extracts the working tree when the push
146
+ // targets the branch HEAD points at, so a deterministic default
147
+ // keeps `git push pod HEAD:main` working on every deployment. See
148
+ // #471.
149
+ const result = spawnSync('git', ['init', '-b', 'main', repoAbs], {
135
150
  stdio: ['ignore', 'pipe', 'pipe']
136
151
  });
137
152
  if (result.status !== 0) {
138
153
  log?.warn?.(
139
154
  { repoAbs, status: result.status, stderr: result.stderr?.toString?.().slice(0, 500) },
140
- 'git auto-init: `git init --bare` exited non-zero'
155
+ 'git auto-init: `git init` exited non-zero'
141
156
  );
142
157
  return null;
143
158
  }
144
159
  const info = findGitDir(repoAbs);
145
- if (info) log?.info?.({ repoAbs }, 'git auto-init: bare repo created on first push');
160
+ if (info) log?.info?.({ repoAbs }, 'git auto-init: repo created on first push');
146
161
  return info;
147
162
  } catch (err) {
148
163
  log?.warn?.({ err, repoAbs }, 'git auto-init: refusing to init (filesystem error)');
@@ -213,14 +228,17 @@ export async function handleGit(request, reply) {
213
228
  }
214
229
 
215
230
  // Find git directory. On a push (`git-receive-pack`) to a path that
216
- // doesn't yet contain a repo, auto-init a bare one if the location is
217
- // safe to claim — the standard preHandler has already verified ACL
218
- // Write on this path, so authorization is enforced. See
219
- // tryAutoInitBareRepo for the safety conditions (empty / non-existent
220
- // path only; refuses to clobber existing files).
231
+ // doesn't yet contain a repo, auto-init one if the location is safe
232
+ // to claim — the standard preHandler has already verified ACL Write
233
+ // on this path, so authorization is enforced. See tryAutoInitRepo
234
+ // for the safety conditions (empty / non-existent path only; refuses
235
+ // to clobber existing files). Auto-init creates a regular (non-bare)
236
+ // repo so the `denyCurrentBranch updateInstead` config below
237
+ // auto-extracts the working tree on each push — pushed files become
238
+ // static resources at the corresponding pod URL.
221
239
  let gitInfo = findGitDir(repoAbs);
222
240
  if (!gitInfo && isGitWriteOperation(request.url)) {
223
- gitInfo = tryAutoInitBareRepo(repoAbs, request.log);
241
+ gitInfo = tryAutoInitRepo(repoAbs, request.log);
224
242
  }
225
243
  if (!gitInfo) {
226
244
  setGitCorsHeaders(reply);
@@ -99,156 +99,12 @@ function dataIsland(resourceUrl, jsonLdString) {
99
99
  *
100
100
  * Net effect: when JSS serves an HTML wrapper with an embedded data
101
101
  * island, the page renders with one HTTP round-trip instead of two.
102
- *
103
- * Extended kludges (kept here so the inline reader stays single-script
104
- * and the HTML wrapper stays self-contained; remove these once the
105
- * upstream bugs they work around are fixed):
106
- *
107
- * A. Origin rewrite — remap the data island's data-uri and embedded
108
- * @id origins to the current page origin so the same HTML wrapper
109
- * renders identically from any host (origin pod, GitHub Pages
110
- * mirror, static export). No-op when origins already match.
111
- *
112
- * B. window.fetch interceptor with JSON-LD↔turtle conversion. JSS
113
- * serves canonical application/ld+json data islands. Mashlib's
114
- * fetcher would honor them via its registered JsonLdHandler —
115
- * except solid-panes/outline/manager.js does its own fetch with
116
- * Accept: text/turtle and parses the body as turtle
117
- * unconditionally (the legacy mashlib container-load path).
118
- * Patching $rdf.parse from outside the bundle does not reach
119
- * solid-panes' import-scoped binding (webpack ESM namespace
120
- * isolation). Shim: at the fetch boundary, when the request
121
- * matches the data island URI, use rdflib's own $rdf.parse +
122
- * $rdf.serialize to convert JSON-LD→turtle in flight for
123
- * container URIs; serve raw JSON-LD for everything else.
124
- * Generic for any RDF shape because rdflib does the conversion.
125
- *
126
- * C. jsonld-parser chunk preload. Mashlib's webpack publicPath is
127
- * hardcoded to '/', so the dynamic import of the JSON-LD parser
128
- * chunk (chunk 841 in mashlib 2.x — stable across 2.0.0→2.2.0)
129
- * 404s on any non-root deploy (see SolidOS/mashlib#287). Inject
130
- * a script tag that loads the chunk from `mashlibBase`; the
131
- * chunk self-registers into `self.webpackChunkMashlib` so
132
- * webpack's runtime never issues the broken fetch.
133
- *
134
- * @param {string} [mashlibBase='/'] - Base URL where mashlib's chunks
135
- * are reachable. CDN deploys pass `https://unpkg.com/mashlib@X/dist/`;
136
- * local deploys default to `/` (JSS serves chunks at root).
137
102
  */
138
- export function roundTripOptimizationScript(mashlibBase = '/') {
103
+ export function roundTripOptimizationScript() {
139
104
  return `<script>
140
105
  (function () {
141
106
  if (typeof window === 'undefined') return;
142
107
 
143
- // Kludge A: origin rewrite — remap data island URIs to the current
144
- // page origin so the wrapper renders identically from any host.
145
- // Best-effort; skipped if globals are missing (e.g. headless test).
146
- if (window.location && typeof document !== 'undefined'
147
- && document.getElementById && typeof URL === 'function') {
148
- try {
149
- var __di_el = document.getElementById('dataisland');
150
- if (__di_el && __di_el.getAttribute) {
151
- var __di_uri = __di_el.getAttribute('data-uri');
152
- if (__di_uri) {
153
- var __di_origUrl = new URL(__di_uri);
154
- var __di_origin = window.location.origin;
155
- if (__di_origUrl.origin !== __di_origin && __di_el.setAttribute) {
156
- __di_el.setAttribute('data-uri',
157
- __di_origin + __di_origUrl.pathname
158
- + __di_origUrl.search + __di_origUrl.hash);
159
- if (__di_el.textContent) {
160
- __di_el.textContent = __di_el.textContent
161
- .split(__di_origUrl.origin).join(__di_origin);
162
- }
163
- }
164
- }
165
- }
166
- } catch (e) { /* leave the island alone on malformed input */ }
167
- }
168
-
169
- // Kludge C: preload the jsonld parser chunk from the same base
170
- // that hosts mashlib. The chunk self-registers into
171
- // self.webpackChunkMashlib so the broken /841.mashlib.min.js
172
- // publicPath:'/' fetch never happens. Best-effort.
173
- try {
174
- if (typeof document !== 'undefined' && document.createElement
175
- && document.head && document.head.appendChild) {
176
- var __di_chunk = document.createElement('script');
177
- __di_chunk.src = ${JSON.stringify(mashlibBase + '841.mashlib.min.js')};
178
- __di_chunk.async = true;
179
- document.head.appendChild(__di_chunk);
180
- }
181
- } catch (e) { /* ignore */ }
182
-
183
- // Kludge B: window.fetch interceptor with JSON-LD↔turtle conversion
184
- // via rdflib (loaded by mashlib). Container URIs get turtle (to feed
185
- // solid-panes' hardcoded turtle parse); everything else gets JSON-LD
186
- // (mashlib's JsonLdHandler dispatches natively on Content-Type).
187
- // Best-effort; skipped if window.fetch missing.
188
- if (typeof window.fetch === 'function' && typeof document !== 'undefined'
189
- && document.getElementById) {
190
- var __di_convertToTurtle = function (jsonStr, baseUri) {
191
- return new Promise(function (resolve, reject) {
192
- var $r = window.$rdf;
193
- if (!$r || typeof $r.parse !== 'function'
194
- || typeof $r.serialize !== 'function'
195
- || typeof $r.graph !== 'function') {
196
- reject(new Error('rdflib not available'));
197
- return;
198
- }
199
- try {
200
- var __di_tempStore = $r.graph();
201
- $r.parse(jsonStr, __di_tempStore, baseUri,
202
- 'application/ld+json', function (pErr) {
203
- if (pErr) { reject(pErr); return; }
204
- try {
205
- $r.serialize(null, __di_tempStore, baseUri, 'text/turtle',
206
- function (sErr, ttl) {
207
- if (sErr) { reject(sErr); return; }
208
- resolve(ttl);
209
- });
210
- } catch (sx) { reject(sx); }
211
- });
212
- } catch (px) { reject(px); }
213
- });
214
- };
215
- var __di_islandResponse = function (body, ct) {
216
- return new Response(body, {
217
- status: 200, statusText: 'OK',
218
- headers: { 'content-type': ct }
219
- });
220
- };
221
- var __di_origFetch = window.fetch.bind(window);
222
- window.fetch = function (input, init) {
223
- try {
224
- var __di_url = (typeof input === 'string') ? input
225
- : (input && input.url) || String(input);
226
- var __di_el2 = document.getElementById('dataisland');
227
- var __di_dataUri = __di_el2 && __di_el2.getAttribute
228
- && __di_el2.getAttribute('data-uri');
229
- var __di_norm = function (u) {
230
- return String(u).split('#')[0].replace(/\\/$/, '');
231
- };
232
- if (__di_dataUri && __di_norm(__di_url) === __di_norm(__di_dataUri)) {
233
- var __di_isContainer = /\\/(?:[?#].*)?$/.test(String(__di_url));
234
- if (__di_isContainer) {
235
- return __di_convertToTurtle(__di_el2.textContent, __di_dataUri)
236
- .then(function (ttl) {
237
- return __di_islandResponse(ttl, 'text/turtle');
238
- })
239
- .catch(function () {
240
- return __di_islandResponse(__di_el2.textContent,
241
- 'application/ld+json');
242
- });
243
- }
244
- return Promise.resolve(__di_islandResponse(__di_el2.textContent,
245
- 'application/ld+json'));
246
- }
247
- } catch (e) { /* fall through to network */ }
248
- return __di_origFetch(input, init);
249
- };
250
- }
251
-
252
108
  // Initialize defensively: another script may have set a truthy
253
109
  // window.__dataIsland that lacks a .get function — or, worse,
254
110
  // assigned a primitive (string, number, etc.) where attaching
@@ -408,12 +264,7 @@ export function roundTripOptimizationScript(mashlibBase = '/') {
408
264
  */
409
265
  export function generateDatabrowserHtml(resourceUrl, cdnVersion = null, opts = {}) {
410
266
  const island = dataIsland(resourceUrl, opts.embedJsonLd);
411
- const mashlibBase = cdnVersion
412
- ? `https://unpkg.com/mashlib@${cdnVersion}/dist/`
413
- : '/';
414
- const reader = opts.roundTripOptimization === false
415
- ? ''
416
- : roundTripOptimizationScript(mashlibBase);
267
+ const reader = opts.roundTripOptimization === false ? '' : roundTripOptimizationScript();
417
268
  if (cdnVersion) {
418
269
  // CDN mode - use script.onload to ensure mashlib is fully loaded before init
419
270
  // This avoids race conditions with defer + DOMContentLoaded
@@ -455,15 +306,7 @@ export function generateDatabrowserHtml(resourceUrl, cdnVersion = null, opts = {
455
306
  export function generateModuleDatabrowserHtml(moduleUrl, resourceUrl = '', opts = {}) {
456
307
  const cssUrl = moduleUrl.replace(/\.js$/, '.css');
457
308
  const island = dataIsland(resourceUrl, opts.embedJsonLd);
458
- // Derive the chunk base from the module URL (strip the filename).
459
- // mashlib's bundled chunks sit alongside the entry point — but if
460
- // a host (e.g. solid.social) serves only the entry and not chunks,
461
- // the broken /841.mashlib.min.js request 404s harmlessly and the
462
- // page falls back to the existing inline-reader paths.
463
- const mashlibBase = moduleUrl.replace(/[^/]*$/, '');
464
- const reader = opts.roundTripOptimization === false
465
- ? ''
466
- : roundTripOptimizationScript(mashlibBase);
309
+ const reader = opts.roundTripOptimization === false ? '' : roundTripOptimizationScript();
467
310
  return `<!doctype html><html lang="en"><head><meta charset="utf-8"/>
468
311
  <meta name="viewport" content="width=device-width, initial-scale=1">
469
312
  <title>Solid Data Browser</title>
@@ -15,7 +15,7 @@ import { createServer } from '../src/server.js';
15
15
  import { createServer as createNetServer } from 'net';
16
16
  import fs from 'fs-extra';
17
17
  import path from 'path';
18
- import { existsSync, statSync, writeFileSync } from 'fs';
18
+ import { existsSync, statSync, writeFileSync, readFileSync } from 'fs';
19
19
 
20
20
  const TEST_HOST = 'localhost';
21
21
  const DATA_DIR = './test-data-git-auto-init';
@@ -56,7 +56,7 @@ describe('Git auto-init on first push', () => {
56
56
  await fs.remove(DATA_DIR);
57
57
  });
58
58
 
59
- it('auto-inits a bare repo on push-advertise to a non-existent path', async () => {
59
+ it('auto-inits a regular repo on push-advertise to a non-existent path', async () => {
60
60
  const repoPath = 'public/apps/penny';
61
61
  const url = `${baseUrl}/${repoPath}/info/refs?service=git-receive-pack`;
62
62
 
@@ -66,13 +66,33 @@ describe('Git auto-init on first push', () => {
66
66
  const repoAbs = path.resolve(DATA_DIR, repoPath);
67
67
  assert.ok(existsSync(repoAbs), 'directory must be created');
68
68
  assert.ok(statSync(repoAbs).isDirectory(), 'created path must be a directory');
69
- // Bare repo: HEAD + objects/ + refs/ live at the path itself.
70
- assert.ok(existsSync(path.join(repoAbs, 'HEAD')), 'bare repo HEAD must exist');
71
- assert.ok(existsSync(path.join(repoAbs, 'objects')), 'bare repo objects/ must exist');
72
- assert.ok(existsSync(path.join(repoAbs, 'refs')), 'bare repo refs/ must exist');
69
+ // Regular (non-bare) repo: .git/ subdirectory holds the internals.
70
+ // Working tree lives at the path itself so pushed files become
71
+ // static resources.
72
+ const dotGit = path.join(repoAbs, '.git');
73
+ assert.ok(existsSync(dotGit), '.git subdirectory must exist');
74
+ assert.ok(statSync(dotGit).isDirectory(), '.git must be a directory');
75
+ assert.ok(existsSync(path.join(dotGit, 'HEAD')), '.git/HEAD must exist');
76
+ assert.ok(existsSync(path.join(dotGit, 'objects')), '.git/objects must exist');
77
+ assert.ok(existsSync(path.join(dotGit, 'refs')), '.git/refs must exist');
73
78
  });
74
79
 
75
- it('auto-inits a bare repo when the target directory exists but is empty', async () => {
80
+ it('pins the initial branch to `main` regardless of server config', async () => {
81
+ // `updateInstead` only extracts the working tree when the push
82
+ // targets the branch HEAD points at. If `git init` honoured the
83
+ // server's `init.defaultBranch`, a server configured for e.g.
84
+ // `gh-pages` would silently fail to extract files pushed to `main`.
85
+ // Pin the auto-init'd HEAD so `git push pod HEAD:main` works
86
+ // everywhere. See #471.
87
+ const repoPath = 'public/apps/penny';
88
+ const headPath = path.resolve(DATA_DIR, repoPath, '.git', 'HEAD');
89
+ assert.ok(existsSync(headPath), 'prereq: repo from earlier test still exists');
90
+ const head = readFileSync(headPath, 'utf8').trim();
91
+ assert.strictEqual(head, 'ref: refs/heads/main',
92
+ `HEAD must point at refs/heads/main, got: ${head}`);
93
+ });
94
+
95
+ it('auto-inits a regular repo when the target directory exists but is empty', async () => {
76
96
  const repoPath = 'public/empty-dir';
77
97
  await fs.ensureDir(path.resolve(DATA_DIR, repoPath));
78
98
 
@@ -81,7 +101,7 @@ describe('Git auto-init on first push', () => {
81
101
  assert.strictEqual(res.status, 200);
82
102
 
83
103
  const repoAbs = path.resolve(DATA_DIR, repoPath);
84
- assert.ok(existsSync(path.join(repoAbs, 'HEAD')), 'bare repo HEAD must exist');
104
+ assert.ok(existsSync(path.join(repoAbs, '.git', 'HEAD')), '.git/HEAD must exist');
85
105
  });
86
106
 
87
107
  it('refuses to auto-init when the target directory contains user content', async () => {
@@ -96,8 +116,7 @@ describe('Git auto-init on first push', () => {
96
116
 
97
117
  // User's file must be intact and no .git should have been created.
98
118
  assert.ok(existsSync(path.join(repoAbs, 'index.html')), 'user file must survive');
99
- assert.ok(!existsSync(path.join(repoAbs, 'HEAD')), 'no bare-repo files should appear');
100
- assert.ok(!existsSync(path.join(repoAbs, 'objects')), 'no bare-repo objects/ should appear');
119
+ assert.ok(!existsSync(path.join(repoAbs, '.git')), 'no .git directory should appear');
101
120
  });
102
121
 
103
122
  it('does NOT auto-init on a fetch (`git-upload-pack`)', async () => {
@@ -151,8 +170,8 @@ describe('Git auto-init on first push', () => {
151
170
  const repoPath = 'public/apps/penny';
152
171
  const repoAbs = path.resolve(DATA_DIR, repoPath);
153
172
  // Repo was created by the first test in this suite; capture its
154
- // initial HEAD inode/mtime to verify we don't recreate the repo.
155
- const headPath = path.join(repoAbs, 'HEAD');
173
+ // initial HEAD inode to verify we don't recreate the repo.
174
+ const headPath = path.join(repoAbs, '.git', 'HEAD');
156
175
  assert.ok(existsSync(headPath), 'prereq: repo from earlier test still exists');
157
176
  const before = statSync(headPath);
158
177