javascript-solid-server 0.0.196 → 0.0.198
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/bin/jss.js +25 -0
- package/package.json +1 -1
- package/src/cli/install.js +283 -0
- package/src/handlers/git.js +7 -1
- package/src/mashlib/index.js +3 -160
- package/test/git-auto-init.test.js +16 -1
package/bin/jss.js
CHANGED
|
@@ -307,6 +307,31 @@ program
|
|
|
307
307
|
}
|
|
308
308
|
});
|
|
309
309
|
|
|
310
|
+
/**
|
|
311
|
+
* Install command — install a Solid app from the default registry
|
|
312
|
+
* (`github.com/solid-apps/<name>`) into a running pod.
|
|
313
|
+
*
|
|
314
|
+
* Phase 1 of #464 / scoped in #478. Hardcodes the default registry;
|
|
315
|
+
* later phases add <org>/<repo>, full URLs, refs, renames, did:nostr
|
|
316
|
+
* resolution, NIP-98 auth, curated default sets, and --bundle.
|
|
317
|
+
*/
|
|
318
|
+
program
|
|
319
|
+
.command('install <names...>')
|
|
320
|
+
.description('Install a Solid app from github.com/solid-apps/<name> into a running pod')
|
|
321
|
+
.option('--pod <url>', 'Target pod URL', 'http://localhost:4443')
|
|
322
|
+
.option('--user <name>', 'Username for IDP auth', 'me')
|
|
323
|
+
.option('--password <pw>', 'Password (default: $JSS_SINGLE_USER_PASSWORD or "me")')
|
|
324
|
+
.option('--nostr-privkey <hex>', 'Sign install pushes with NIP-98 using this 64-char hex Nostr privkey instead of fetching a bearer token (default: $NOSTR_PRIVKEY)')
|
|
325
|
+
.action(async (names, options) => {
|
|
326
|
+
try {
|
|
327
|
+
const { runInstall } = await import('../src/cli/install.js');
|
|
328
|
+
await runInstall(names, options);
|
|
329
|
+
} catch (err) {
|
|
330
|
+
// runInstall prints its own per-app error lines; we just exit non-zero.
|
|
331
|
+
process.exit(1);
|
|
332
|
+
}
|
|
333
|
+
});
|
|
334
|
+
|
|
310
335
|
/**
|
|
311
336
|
* Init command - interactive configuration
|
|
312
337
|
*/
|
package/package.json
CHANGED
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `jss install <name>` — install a Solid app into a running pod.
|
|
3
|
+
*
|
|
4
|
+
* Phase 1 of #464 (see #478 for the scoped issue). Hardcodes the
|
|
5
|
+
* default registry to `github.com/solid-apps/<name>`. Later phases
|
|
6
|
+
* add `<org>/<repo>` shorthand, full URLs, `#<ref>` pinning,
|
|
7
|
+
* `=<name>` rename, `--did` resolution, `--nostr-privkey` NIP-98
|
|
8
|
+
* auth, a curated default set, and `--bundle`.
|
|
9
|
+
*
|
|
10
|
+
* The install is a thin shell over the auto-init + updateInstead +
|
|
11
|
+
* regular-repo machinery already in `src/handlers/git.js`:
|
|
12
|
+
*
|
|
13
|
+
* 1. POST <pod>/idp/credentials with the supplied creds → bearer token
|
|
14
|
+
* 2. `git clone <source> /tmp/<name>` (full clone — shallow pushes
|
|
15
|
+
* are rejected by JSS git-receive)
|
|
16
|
+
* 3. Push the clone to `<pod>/public/apps/<name>` with the bearer
|
|
17
|
+
* header, on BOTH `HEAD:main` and `HEAD:gh-pages` so it works
|
|
18
|
+
* regardless of the operator's `init.defaultBranch`. Whichever
|
|
19
|
+
* matches server-side HEAD triggers `updateInstead` and extracts
|
|
20
|
+
* the working tree; the other creates a stranded ref.
|
|
21
|
+
*
|
|
22
|
+
* Idempotent on re-run (existing repo at the path accepts the push
|
|
23
|
+
* normally). Skip-on-existing-non-repo translates auto-init's
|
|
24
|
+
* "won't init a non-empty path" 404 into a friendly message.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import { spawnSync } from 'child_process';
|
|
28
|
+
import { existsSync } from 'fs';
|
|
29
|
+
import { join } from 'path';
|
|
30
|
+
import { nip98Token } from '../nostr/event.js';
|
|
31
|
+
|
|
32
|
+
// ANSI helpers — keep zero-dep so this works in any embedded usage.
|
|
33
|
+
const c = (n) => (s) => `\x1b[${n}m${s}\x1b[0m`;
|
|
34
|
+
const green = c(32);
|
|
35
|
+
const yellow = c(33);
|
|
36
|
+
const red = c(31);
|
|
37
|
+
const dim = c(2);
|
|
38
|
+
const bold = c(1);
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Parse an app spec. Accepts (Phase 2 of #464):
|
|
42
|
+
* - bare name → github.com/solid-apps/<name> (default registry)
|
|
43
|
+
* - "<org>/<repo>" → github.com/<org>/<repo>
|
|
44
|
+
* - "https://..." full URL → as-is (must point at a git repo)
|
|
45
|
+
* Each form may carry an optional "#<ref>" suffix to pin a tag or branch:
|
|
46
|
+
* chrome#v1.2 / solid-apps/chrome#main / https://...#v2
|
|
47
|
+
* And an optional "=<name>" suffix to override the pod-path name:
|
|
48
|
+
* litecut/litecut.github.io=litecut
|
|
49
|
+
*/
|
|
50
|
+
function parseAppSpec(input) {
|
|
51
|
+
// Pull off the rename suffix first, then the ref suffix.
|
|
52
|
+
let base = input;
|
|
53
|
+
let renameName = null;
|
|
54
|
+
const eqIx = base.lastIndexOf('=');
|
|
55
|
+
if (eqIx > 0) {
|
|
56
|
+
renameName = base.slice(eqIx + 1);
|
|
57
|
+
base = base.slice(0, eqIx);
|
|
58
|
+
}
|
|
59
|
+
let ref = null;
|
|
60
|
+
const hashIx = base.lastIndexOf('#');
|
|
61
|
+
if (hashIx > 0) {
|
|
62
|
+
ref = base.slice(hashIx + 1) || null;
|
|
63
|
+
base = base.slice(0, hashIx);
|
|
64
|
+
}
|
|
65
|
+
let source, name;
|
|
66
|
+
if (/^https?:\/\//.test(base)) {
|
|
67
|
+
source = base.replace(/\.git$/, '').replace(/\/$/, '');
|
|
68
|
+
name = source.split('/').pop();
|
|
69
|
+
} else if (base.includes('/')) {
|
|
70
|
+
const cleaned = base.replace(/\.git$/, '').replace(/^\/+|\/+$/g, '');
|
|
71
|
+
if (cleaned.split('/').length !== 2) {
|
|
72
|
+
return { error: 'expected <org>/<repo> shorthand' };
|
|
73
|
+
}
|
|
74
|
+
source = `https://github.com/${cleaned}`;
|
|
75
|
+
name = cleaned.split('/').pop();
|
|
76
|
+
} else {
|
|
77
|
+
source = `https://github.com/solid-apps/${base}`;
|
|
78
|
+
name = base;
|
|
79
|
+
}
|
|
80
|
+
if (renameName) name = renameName;
|
|
81
|
+
if (!/^[a-z0-9][a-z0-9_.-]*$/i.test(name)) {
|
|
82
|
+
return { error: `invalid pod-path name "${name}"` };
|
|
83
|
+
}
|
|
84
|
+
if (ref && !/^[a-z0-9][a-z0-9_./-]*$/i.test(ref)) {
|
|
85
|
+
return { error: `invalid ref "${ref}"` };
|
|
86
|
+
}
|
|
87
|
+
return { source, name, ref };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Fetch a bearer token from the pod's IDP, or null if the pod runs
|
|
92
|
+
* with `--public` (no auth required for writes).
|
|
93
|
+
*/
|
|
94
|
+
async function fetchToken({ pod, user, password }) {
|
|
95
|
+
// First check whether the pod accepts unauthenticated writes — if so,
|
|
96
|
+
// we don't need a token. Probe with HEAD on /public/ (which any pod
|
|
97
|
+
// exposes); if writes there require auth, we'll need the token.
|
|
98
|
+
// For Phase 1 we just always try to fetch a token; if the IDP isn't
|
|
99
|
+
// running, we fall through with a clear error.
|
|
100
|
+
try {
|
|
101
|
+
const r = await fetch(`${pod}/idp/credentials`, {
|
|
102
|
+
method: 'POST',
|
|
103
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
|
104
|
+
body: new URLSearchParams({ username: user, password })
|
|
105
|
+
});
|
|
106
|
+
if (r.status === 404) {
|
|
107
|
+
// No IDP — pod is likely in --public mode. Proceed without a token.
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
|
111
|
+
const j = await r.json();
|
|
112
|
+
if (!j.access_token) throw new Error('no access_token in response');
|
|
113
|
+
return j.access_token;
|
|
114
|
+
} catch (e) {
|
|
115
|
+
throw new Error(`Could not authenticate against ${pod}: ${e.message}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Install one app spec to one pod. Returns a status object the caller
|
|
121
|
+
* uses for per-app output + exit-code aggregation.
|
|
122
|
+
*/
|
|
123
|
+
async function installOne({ spec, pod, token, nostrPrivkey }) {
|
|
124
|
+
const { source, name, ref } = spec;
|
|
125
|
+
const dest = `${pod}/public/apps/${name}`;
|
|
126
|
+
const tmp = join('/tmp', `jss-install-${name}-${process.pid}`);
|
|
127
|
+
|
|
128
|
+
// Clean any stale tmp from a prior failed run.
|
|
129
|
+
if (existsSync(tmp)) spawnSync('rm', ['-rf', tmp], { stdio: 'ignore' });
|
|
130
|
+
|
|
131
|
+
// Clone (no --depth: shallow pushes are rejected by JSS git-receive).
|
|
132
|
+
// --branch picks a tag or branch when pinned (e.g. `foo/bar#v2`).
|
|
133
|
+
const cloneArgs = ['clone', '--quiet'];
|
|
134
|
+
if (ref) cloneArgs.push('--branch', ref);
|
|
135
|
+
cloneArgs.push(source, tmp);
|
|
136
|
+
const clone = spawnSync('git', cloneArgs, {
|
|
137
|
+
stdio: ['ignore', 'pipe', 'pipe']
|
|
138
|
+
});
|
|
139
|
+
if (clone.status !== 0) {
|
|
140
|
+
const err = clone.stderr?.toString?.().trim() || '';
|
|
141
|
+
return { name, status: 'failed', reason: `clone failed${err ? `: ${err.slice(0, 300)}` : ''}` };
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Build the Authorization header for the push. NIP-98 (Phase 4)
|
|
145
|
+
// signs a Nostr event with the user's Schnorr key — no IDP creds
|
|
146
|
+
// needed; JSS verifies via src/auth/token.js and returns a
|
|
147
|
+
// did:nostr:<hex> identity for ACL matching.
|
|
148
|
+
//
|
|
149
|
+
// Git makes BOTH an advertise GET (`info/refs?service=git-receive-pack`)
|
|
150
|
+
// and a receive POST (`git-receive-pack`) on the same http.extraHeader.
|
|
151
|
+
// JSS is lenient for git clients (src/auth/nostr.js): it accepts a
|
|
152
|
+
// NIP-98 event whose `u` is a prefix of the request URL, and whose
|
|
153
|
+
// `method` is `*` as a wildcard. Sign the base URL with method `*`
|
|
154
|
+
// so the same event passes auth on both requests.
|
|
155
|
+
const authHeader = () => {
|
|
156
|
+
if (nostrPrivkey) {
|
|
157
|
+
const b64 = nip98Token(dest, '*', nostrPrivkey);
|
|
158
|
+
return `Authorization: Nostr ${b64}`;
|
|
159
|
+
}
|
|
160
|
+
if (token) return `Authorization: Bearer ${token}`;
|
|
161
|
+
return null;
|
|
162
|
+
};
|
|
163
|
+
|
|
164
|
+
// Dual push: HEAD:main and HEAD:gh-pages. Whichever matches server-
|
|
165
|
+
// side HEAD triggers updateInstead and extracts the working tree.
|
|
166
|
+
// The other just creates a stranded ref (harmless). Idempotent.
|
|
167
|
+
// Each push gets a freshly-signed NIP-98 event (the signature is
|
|
168
|
+
// tied to a specific u + method + timestamp window).
|
|
169
|
+
const pushArgs = (branch) => {
|
|
170
|
+
const args = ['-C', tmp];
|
|
171
|
+
const auth = authHeader();
|
|
172
|
+
if (auth) args.push('-c', `http.extraHeader=${auth}`);
|
|
173
|
+
args.push('push', dest, `HEAD:${branch}`);
|
|
174
|
+
return args;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const pushMain = spawnSync('git', pushArgs('main'), { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
178
|
+
const errMain = pushMain.stderr?.toString?.() || '';
|
|
179
|
+
|
|
180
|
+
// Auto-init refuses on a non-empty target dir → 404 / "not found".
|
|
181
|
+
// Distinguish "path already in use" from real errors.
|
|
182
|
+
if (pushMain.status !== 0 && (errMain.includes('not found') || errMain.includes('404'))) {
|
|
183
|
+
spawnSync('rm', ['-rf', tmp], { stdio: 'ignore' });
|
|
184
|
+
return { name, status: 'skipped', reason: 'path already in use' };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const pushPages = spawnSync('git', pushArgs('gh-pages'), { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
188
|
+
|
|
189
|
+
if (pushMain.status !== 0 && pushPages.status !== 0) {
|
|
190
|
+
const err = (errMain + '\n' + (pushPages.stderr?.toString?.() || '')).trim();
|
|
191
|
+
spawnSync('rm', ['-rf', tmp], { stdio: 'ignore' });
|
|
192
|
+
return { name, status: 'failed', reason: `push failed: ${err.slice(0, 400)}` };
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
spawnSync('rm', ['-rf', tmp], { stdio: 'ignore' });
|
|
196
|
+
return { name, status: 'installed', dest: `${dest}/` };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Public entry point. Called from bin/jss.js's `install` subcommand
|
|
201
|
+
* action. Throws to signal a non-zero exit; returns normally for
|
|
202
|
+
* partial success (per-app errors are reported but don't fail-fast).
|
|
203
|
+
*/
|
|
204
|
+
export async function runInstall(names, options) {
|
|
205
|
+
const pod = (options.pod || 'http://localhost:4443').replace(/\/$/, '');
|
|
206
|
+
const user = options.user || 'me';
|
|
207
|
+
const password = options.password || process.env.JSS_SINGLE_USER_PASSWORD || 'me';
|
|
208
|
+
const nostrPrivkey = options.nostrPrivkey || process.env.NOSTR_PRIVKEY || null;
|
|
209
|
+
|
|
210
|
+
if (!names || names.length === 0) {
|
|
211
|
+
throw new Error('expected at least one app name. Try: `jss install chrome`');
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Validate Nostr privkey if supplied (64 lowercase-hex chars).
|
|
215
|
+
if (nostrPrivkey && !/^[0-9a-f]{64}$/i.test(nostrPrivkey)) {
|
|
216
|
+
console.error(red('✗ --nostr-privkey must be 64 hex chars'));
|
|
217
|
+
throw new Error('invalid --nostr-privkey');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
// Validate every spec up front so we report invalid names before
|
|
221
|
+
// doing any network work.
|
|
222
|
+
const specs = [];
|
|
223
|
+
for (const n of names) {
|
|
224
|
+
const spec = parseAppSpec(n);
|
|
225
|
+
if (spec.error) {
|
|
226
|
+
console.error(red(`✗ ${n}: ${spec.error}`));
|
|
227
|
+
throw new Error(`invalid app spec: ${n}`);
|
|
228
|
+
}
|
|
229
|
+
specs.push(spec);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
console.log(bold(`\nInstalling ${specs.length} app${specs.length === 1 ? '' : 's'} → `) + green(pod));
|
|
233
|
+
if (nostrPrivkey) console.log(dim(' (signing with Nostr privkey — NIP-98)'));
|
|
234
|
+
console.log('');
|
|
235
|
+
|
|
236
|
+
// With --nostr-privkey we sign each push as NIP-98; no bearer token
|
|
237
|
+
// needed. Otherwise fetch the bearer token from the pod's IDP.
|
|
238
|
+
let token = null;
|
|
239
|
+
if (!nostrPrivkey) try {
|
|
240
|
+
token = await fetchToken({ pod, user, password });
|
|
241
|
+
} catch (e) {
|
|
242
|
+
console.error(red(`✗ ${e.message}`));
|
|
243
|
+
console.error(dim(' Is the pod running? Try: `jss start`'));
|
|
244
|
+
throw e;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// Decode hex privkey once for installOne (nip98Token wants bytes).
|
|
248
|
+
const privkeyBytes = nostrPrivkey
|
|
249
|
+
? Uint8Array.from(Buffer.from(nostrPrivkey, 'hex'))
|
|
250
|
+
: null;
|
|
251
|
+
|
|
252
|
+
let okCount = 0;
|
|
253
|
+
let failCount = 0;
|
|
254
|
+
for (const spec of specs) {
|
|
255
|
+
const result = await installOne({ spec, pod, token, nostrPrivkey: privkeyBytes });
|
|
256
|
+
switch (result.status) {
|
|
257
|
+
case 'installed':
|
|
258
|
+
console.log(green(`✓ ${result.name}`) + dim(` → ${result.dest}`));
|
|
259
|
+
okCount++;
|
|
260
|
+
break;
|
|
261
|
+
case 'skipped':
|
|
262
|
+
console.log(yellow(`⊘ ${result.name}`) + dim(`: skipped (${result.reason})`));
|
|
263
|
+
break;
|
|
264
|
+
case 'failed':
|
|
265
|
+
console.error(red(`✗ ${result.name}: ${result.reason.split(':')[0]}`));
|
|
266
|
+
if (result.reason.includes(':')) {
|
|
267
|
+
console.error(dim(` ${result.reason.slice(result.reason.indexOf(':') + 1).trim()}`));
|
|
268
|
+
}
|
|
269
|
+
failCount++;
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
console.log('');
|
|
275
|
+
console.log(bold(`${okCount}/${specs.length} installed.`));
|
|
276
|
+
if (okCount > 0) {
|
|
277
|
+
console.log(dim('Open in browser: ') + `${pod}/public/apps/`);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
if (failCount > 0) {
|
|
281
|
+
throw new Error(`${failCount} of ${specs.length} install(s) failed`);
|
|
282
|
+
}
|
|
283
|
+
}
|
package/src/handlers/git.js
CHANGED
|
@@ -140,7 +140,13 @@ function tryAutoInitRepo(repoAbs, log) {
|
|
|
140
140
|
} else {
|
|
141
141
|
mkdirSync(repoAbs, { recursive: true });
|
|
142
142
|
}
|
|
143
|
-
|
|
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], {
|
|
144
150
|
stdio: ['ignore', 'pipe', 'pipe']
|
|
145
151
|
});
|
|
146
152
|
if (result.status !== 0) {
|
package/src/mashlib/index.js
CHANGED
|
@@ -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(
|
|
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
|
|
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
|
-
|
|
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';
|
|
@@ -77,6 +77,21 @@ describe('Git auto-init on first push', () => {
|
|
|
77
77
|
assert.ok(existsSync(path.join(dotGit, 'refs')), '.git/refs must exist');
|
|
78
78
|
});
|
|
79
79
|
|
|
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
|
+
|
|
80
95
|
it('auto-inits a regular repo when the target directory exists but is empty', async () => {
|
|
81
96
|
const repoPath = 'public/empty-dir';
|
|
82
97
|
await fs.ensureDir(path.resolve(DATA_DIR, repoPath));
|