Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Hub: one Edit beside Fork, Unpublish inside the edit; CDN module imports are not 'self-contained' (#1306)

Jacob Phamb84a75a2a563
diff --git a/desktop/lib/community/output_check.dart b/desktop/lib/community/output_check.dart
index c5688747b..976a94f80 100644
--- a/desktop/lib/community/output_check.dart
+++ b/desktop/lib/community/output_check.dart
@@ -27,6 +27,21 @@ final _cssImport = RegExp(
caseSensitive: false,
);
+/// What a page's own scripts load: modules (`import … from "…"`, `import "…"`, `export … from "…"`,
+/// `import("…")`) and `fetch("…")`. A module from a CDN is the usual way a one-file page still needs
+/// the network (three.js from jsdelivr), and the sandbox blocks it.
+final _scriptBody = RegExp(
+ r'<script\b[^>]*>([\s\S]*?)</script>',
+ caseSensitive: false,
+);
+final _scriptLoads = [
+ RegExp(
+ r'''\b(?:import|export)\s*(?:[\w$*{}\s,]+?\s*from\s*)?["']([^"'\n]+)["']''',
+ ),
+ RegExp(r'''\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)'''),
+ RegExp(r'''\bfetch\s*\(\s*["'`]([^"'`\n]+)["'`]'''),
+];
+
String? _attribute(String tag, String name) {
final match = RegExp(
'\\s$name\\s*=\\s*(?:"([^"]*)"|\'([^\']*)\'|([^\\s>]+))',
@@ -57,5 +72,12 @@ List<String> outsideResources(String html) {
for (final match in _cssImport.allMatches(html)) {
add(match[1]);
}
+ for (final script in _scriptBody.allMatches(html)) {
+ for (final pattern in _scriptLoads) {
+ for (final match in pattern.allMatches(script[1]!)) {
+ add(match[1]!.trim());
+ }
+ }
+ }
return found.toList();
}
diff --git a/desktop/test/community_output_check_test.dart b/desktop/test/community_output_check_test.dart
index afc4f1f9a..2f9363699 100644
--- a/desktop/test/community_output_check_test.dart
+++ b/desktop/test/community_output_check_test.dart
@@ -15,6 +15,20 @@ void main() {
'fonts.css',
]);
});
+ test('names the modules and data a page\'s own scripts load', () {
+ const html = '''<script type="module">import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+ import { OrbitControls } from "./controls.js"; import 'side-effect.js'; export { x } from "./x.js";
+ const lazy = await import("./lazy.js"); fetch('data.json').then(r => r.json());
+ const label = "import nothing from here";</script><p>import "prose" is not a script</p>''';
+ expect(outsideResources(html), [
+ 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js',
+ './controls.js',
+ 'side-effect.js',
+ './x.js',
+ './lazy.js',
+ 'data.json',
+ ]);
+ });
test('a page that carries everything inside it loads nothing', () {
expect(
outsideResources(
diff --git a/desktop/test/community_publish_test.dart b/desktop/test/community_publish_test.dart
index 40ef82a35..f93bd7a06 100644
--- a/desktop/test/community_publish_test.dart
+++ b/desktop/test/community_publish_test.dart
@@ -147,6 +147,31 @@ void main() {
await file('notes.html', game);
expect((await build())['viewerPath'], 'notes.html');
});
+ test(
+ 'a one-file page that imports a module from a CDN is never assumed',
+ () async {
+ await file(
+ 'twisted-ribbon-lamp.html',
+ '<canvas></canvas><script type="module">import * as THREE from "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js";</script>',
+ );
+ await expectLater(
+ buildPublicationDraft(
+ folder: root.path,
+ title: 'Lamp',
+ engine: 'codex',
+ ),
+ throwsA(
+ isA<NeedsOutput>().having(
+ (e) => e.message,
+ 'message',
+ contains(
+ 'twisted-ribbon-lamp.html loads https://cdn.jsdelivr.net/',
+ ),
+ ),
+ ),
+ );
+ },
+ );
test(
'a folder\'s index.html that needs other files is never assumed',
() async {
@@ -399,10 +424,7 @@ void main() {
// The draft goes as a gzipped file, never as text the edge could read.
expect(html, contains('<input type="file" name="draft" hidden>'));
final packed = RegExp(r'atob\("([A-Za-z0-9+/=]+)"\)').firstMatch(html)![1]!;
- expect(
- jsonDecode(utf8.decode(gzip.decode(base64Decode(packed)))),
- draft,
- );
+ expect(jsonDecode(utf8.decode(gzip.decode(base64Decode(packed)))), draft);
await handoff.close();
});
test('login return accepts only local Hub pages', () {
diff --git a/website/README.md b/website/README.md
index 05a25be3a..860bd0d4e 100644
--- a/website/README.md
+++ b/website/README.md
@@ -137,9 +137,11 @@ the proxy forwards those bytes unchanged, and the backend unpacks them (bounded)
(`backend/src/lib/gzipJson.ts`). Plain JSON bodies and an older Desktop's text field still work.
Backend reads are public; likes, comments, following, publication, editing, and unpublication require SSO.
-An author edits a publication in place (`PUT /api/community/harnesses/:id`): **Edit this harness** on
-its page opens `/hub/publish?edit=<id>`, and a draft arriving from Desktop can choose **Publish as →
-Update "…"**. The address, likes, comments and forks stay; forks keep the version they copied; where it
+An author edits a publication in place (`PUT /api/community/harnesses/:id`): **Edit**, beside Fork on
+its page and shown only to its author, opens `/hub/publish?edit=<id>`, where **Unpublish this harness**
+also lives; a draft arriving from Desktop can choose **Publish as → Update "…"**. A harness page whose
+likes and actions fail to load says so with Retry, and one read anonymously because the browser's sign-in
+expired asks to sign in again, instead of silently hiding Edit. The address, likes, comments and forks stay; forks keep the version they copied; where it
came from (`forkedFrom`, credits) and its cover (unless a new one is chosen) stay as published.
Counts are persisted, like/follow writes are idempotent, comment retries have per-user request IDs,
replies retain their parent and display a Creator badge,
diff --git a/website/src/app/hub/components/Detail.tsx b/website/src/app/hub/components/Detail.tsx
index 390a0046d..d6da025f5 100644
--- a/website/src/app/hub/components/Detail.tsx
+++ b/website/src/app/hub/components/Detail.tsx
@@ -4,6 +4,7 @@ import Link from 'next/link';
import { ArrowLeft } from 'lucide-react';
import type { OpenHarness } from '@/lib/community/types';
import { DetailHead, type Panel } from './DetailHead';
+import { DetailNotice } from './DetailNotice';
import { Forks } from './Forks';
import { Header } from './Header';
import { SidePanel } from './SidePanel';
@@ -17,17 +18,16 @@ export default function Detail({ id, initial, initialComments = false }: { id: s
const { harness, social, ready, busy } = page;
if (page.unavailable) return <><Header /><main className={`${styles.wrap} ${styles.empty}`}><h1>This harness is unavailable.</h1><Link className={styles.textLink} href="/hub">Back to Explore</Link></main></>;
if (!harness) return <><Header /><main className={`${styles.wrap} ${styles.loading}`}>{page.error || 'Loading harness…'}{page.error && <button onClick={() => void page.load()}>Retry</button>}</main></>;
- const unpublish = () => { if (window.confirm('Remove this harness from the public feed? Existing downloaded forks remain with their owners.')) void page.unpublish(); };
// A panel's button opens it; pressed again, it returns to the chat log.
const toggle = (next: Panel) => setPanel(current => current === next ? 'log' : next);
return <><Header /><main className={`${styles.wrap} ${styles.detail}`}>
<Link className={styles.back} href="/hub"><ArrowLeft /> All harnesses</Link>
<DetailHead harness={harness} social={social} ready={ready} busy={busy} panel={panel} onFollow={() => void page.follow()} onLike={() => void page.like()} onPanel={toggle} />
+ <DetailNotice social={social} ready={ready} failed={page.failed} onRetry={() => void page.load()} />
<div className={styles.split}><Viewer harness={harness} />
<SidePanel harness={harness} social={social} ready={ready} busy={busy} panel={panel} error={page.error}
onClose={() => setPanel('log')} onRetry={() => void page.load()} onRemove={comment => void page.removeComment(comment)} onPost={page.postComment} />
</div>
{!!social.forks && <Forks id={id} count={social.forks} />}
- {social.mine && <div className={styles.manage}><Link href={`/hub/publish?edit=${id}`}>Edit this harness</Link><button disabled={busy} onClick={unpublish}>Unpublish this harness</button></div>}
</main></>;
}
diff --git a/website/src/app/hub/components/DetailHead.tsx b/website/src/app/hub/components/DetailHead.tsx
index fb2ee85df..a1dddb1ba 100644
--- a/website/src/app/hub/components/DetailHead.tsx
+++ b/website/src/app/hub/components/DetailHead.tsx
@@ -1,6 +1,6 @@
'use client';
import Link from 'next/link';
-import { FileCode2, GitFork, Heart, MessageCircle } from 'lucide-react';
+import { FileCode2, GitFork, Heart, MessageCircle, Pencil } from 'lucide-react';
import { commentTotal } from '@/lib/community/comments';
import type { OpenHarness, SocialState } from '@/lib/community/types';
import { ForkButton } from './ForkButton';
@@ -15,7 +15,7 @@ type Props = {
onFollow: () => void; onLike: () => void; onPanel: (panel: Panel) => void;
};
-/** The harness's title and creator, and what a reader can do with it. */
+/** The harness's title and creator, and what a reader can do with it; its author can also edit (and unpublish) it there. */
export function DetailHead({ harness, social, ready, busy, panel, onFollow, onLike, onPanel }: Props) {
return <header className={styles.detailHead}>
<div className={styles.identity}><h1>{harness.title}</h1><div className={styles.byline}>
@@ -29,6 +29,7 @@ export function DetailHead({ harness, social, ready, busy, panel, onFollow, onLi
<button aria-label="Comments" aria-pressed={panel === 'comments'} onClick={() => onPanel('comments')}><MessageCircle /><span>{ready ? commentTotal(social) : 'Comments'}</span></button>
<button aria-label="Source files" aria-pressed={panel === 'files'} onClick={() => onPanel('files')}><FileCode2 /><span className={styles.actionLabel}>Files</span></button>
<ShareButton id={harness.id} />
+ {social.mine && <Link href={`/hub/publish?edit=${harness.id}`}><Pencil /><span>Edit</span></Link>}
<ForkButton id={harness.id}><GitFork /> Fork</ForkButton>
</div>
</header>;
diff --git a/website/src/app/hub/components/DetailNotice.tsx b/website/src/app/hub/components/DetailNotice.tsx
new file mode 100644
index 000000000..0e1739ce8
--- /dev/null
+++ b/website/src/app/hub/components/DetailNotice.tsx
@@ -0,0 +1,19 @@
+'use client';
+import { rememberHubReturn } from '@/lib/community/session';
+import type { SocialState } from '@/lib/community/types';
+import { webAppPath } from '@/lib/webApp';
+import { useSignedIn } from './useSignedIn';
+import styles from '../community.module.css';
+
+type Props = { social: SocialState; ready: boolean; failed: boolean; onRetry: () => void };
+
+/**
+ * Why a harness page may read as a visitor's: its likes, comments and the author's Edit could not be
+ * loaded, or this browser still holds a sign-in the Hub no longer accepts (it then reads anonymously).
+ */
+export function DetailNotice({ social, ready, failed, onRetry }: Props) {
+ const signedInHere = useSignedIn();
+ if (failed) return <p className={styles.notice} role="status">Likes, comments and your own actions could not be loaded.<button type="button" onClick={onRetry}>Retry</button></p>;
+ if (ready && signedInHere && !social.signedIn) return <p className={styles.notice} role="status">Your sign-in has expired, so this page reads as a visitor&apos;s.<a href={webAppPath} onClick={rememberHubReturn}>Sign in again</a></p>;
+ return null;
+}
diff --git a/website/src/app/hub/components/community.spec.tsx b/website/src/app/hub/components/community.spec.tsx
index 69a6930a4..f6f6700a5 100644
--- a/website/src/app/hub/components/community.spec.tsx
+++ b/website/src/app/hub/components/community.spec.tsx
@@ -108,17 +108,36 @@ describe('community navigation', () => {
fireEvent.click(screen.getByRole('button', { name: 'Back to chat log' }));
expect(screen.getByText('Make an orbit.')).toBeInTheDocument();
});
- it('offers its author Edit beside Unpublish, and a reader neither', async () => {
+ it('offers its author one Edit beside Fork, and a reader none', async () => {
const id = '0f8fad5b-d9cb-469f-a165-70867728950e';
request.mockResolvedValueOnce({ harness: { ...sample, id }, social: { ...emptySocial, signedIn: true, mine: true } });
const { unmount } = render(<Detail id={id} initial={null} />);
- expect(await screen.findByRole('link', { name: 'Edit this harness' })).toHaveAttribute('href', `/hub/publish?edit=${id}`);
- expect(screen.getByRole('button', { name: 'Unpublish this harness' })).toBeInTheDocument();
+ expect(await screen.findByRole('link', { name: 'Edit' })).toHaveAttribute('href', `/hub/publish?edit=${id}`);
+ // Unpublish lives in the edit, not beside the output.
+ expect(screen.queryByRole('button', { name: 'Unpublish this harness' })).not.toBeInTheDocument();
unmount();
request.mockResolvedValueOnce({ harness: { ...sample, id }, social: { ...emptySocial, signedIn: true } });
render(<Detail id={id} initial={null} />);
await screen.findByTitle('Orbit output');
- expect(screen.queryByRole('link', { name: 'Edit this harness' })).not.toBeInTheDocument();
+ expect(screen.queryByRole('link', { name: 'Edit' })).not.toBeInTheDocument();
+ });
+ it('says so when a drawn page cannot load its likes and actions, and retries', async () => {
+ const id = '0f8fad5b-d9cb-469f-a165-70867728950e';
+ request.mockRejectedValueOnce(new CommunityError('Service unavailable', 503));
+ render(<Detail id={id} initial={{ ...sample, id }} />);
+ expect(await screen.findByText(/could not be loaded/)).toBeInTheDocument();
+ request.mockResolvedValueOnce({ social: { ...emptySocial, signedIn: true, mine: true } });
+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));
+ expect(await screen.findByRole('link', { name: 'Edit' })).toBeInTheDocument();
+ expect(screen.queryByText(/could not be loaded/)).not.toBeInTheDocument();
+ });
+ it('tells a browser whose sign-in the Hub no longer accepts to sign in again', async () => {
+ localStorage.setItem('harness.web.v1.auth_access_token', 'expired-fixture');
+ request.mockResolvedValueOnce({ harness: { ...sample, id: sample.id }, social: { ...emptySocial, signedIn: false } });
+ render(<Detail id={sample.id} initial={null} />);
+ expect(await screen.findByText(/Your sign-in has expired/)).toBeInTheDocument();
+ expect(screen.getByRole('link', { name: 'Sign in again' })).toHaveAttribute('href', '/web');
+ localStorage.clear();
});
it('reads a publication once, then refreshes only its social state', async () => {
const id = '0f8fad5b-d9cb-469f-a165-70867728950e';
diff --git a/website/src/app/hub/components/useHarnessDetail.ts b/website/src/app/hub/components/useHarnessDetail.ts
index b3480d1a5..ce3c4b1c2 100644
--- a/website/src/app/hub/components/useHarnessDetail.ts
+++ b/website/src/app/hub/components/useHarnessDetail.ts
@@ -12,6 +12,8 @@ import { useRefreshOnReturn } from './useRefreshOnReturn';
export function useHarnessDetail(id: string, initial: OpenHarness | null, onSignIn: () => void) {
const [harness, setHarness] = useState(initial), [social, setSocial] = useState(emptySocial);
const [error, setError] = useState(''), [busy, setBusy] = useState(false), [ready, setReady] = useState(false), [unavailable, setUnavailable] = useState(false);
+ // A failed read of a page already drawn: said aloud, since without it the author's Edit silently vanishes.
+ const [failed, setFailed] = useState(false);
const revision = useRef(0), writing = useRef(false), loaded = useRef(!!initial);
/**
@@ -35,12 +37,13 @@ export function useHarnessDetail(id: string, initial: OpenHarness | null, onSign
const data = await read();
if (current !== revision.current) return;
if (data.harness) { loaded.current = true; setHarness(data.harness); }
- setSocial(data.social); setReady(true); setError('');
+ setSocial(data.social); setReady(true); setError(''); setFailed(false);
} catch (e) {
if (current !== revision.current) return;
setReady(false);
if (e instanceof CommunityError && e.status === 404) setUnavailable(true);
else if (!initial) setError('This harness could not be loaded. Please try again.');
+ else setFailed(true);
}
}, [read, initial]);
useEffect(() => {
@@ -87,10 +90,5 @@ export function useHarnessDetail(id: string, initial: OpenHarness | null, onSign
return { ...value, comments: [...value.comments.filter(item => item.id !== data.comment.id), data.comment], commentCount: commentTotal(value) + (known ? 0 : 1) };
});
});
- const unpublish = () => mutate(async () => {
- await communityRequest(`harnesses/${id}`, { method: 'DELETE' });
- setUnavailable(true);
- });
-
- return { harness, social, ready, error, busy, unavailable, load, follow, like, removeComment, postComment, unpublish };
+ return { harness, social, ready, failed, error, busy, unavailable, load, follow, like, removeComment, postComment };
}
diff --git a/website/src/app/hub/publish/components/UnpublishAction.tsx b/website/src/app/hub/publish/components/UnpublishAction.tsx
new file mode 100644
index 000000000..0dd3e8058
--- /dev/null
+++ b/website/src/app/hub/publish/components/UnpublishAction.tsx
@@ -0,0 +1,9 @@
+import styles from '../../community.module.css';
+
+/** Below an edit, the one way to take the harness off the Hub, asked twice. */
+export function UnpublishAction({ busy, onUnpublish }: { busy: boolean; onUnpublish: () => void }) {
+ const confirmThen = () => {
+ if (window.confirm('Remove this harness from the public feed? Forks people already made keep their copy.')) onUnpublish();
+ };
+ return <div className={styles.manage}><button type="button" disabled={busy} onClick={confirmThen}>Unpublish this harness</button></div>;
+}
diff --git a/website/src/app/hub/publish/page.spec.tsx b/website/src/app/hub/publish/page.spec.tsx
index a93b7d436..7384f01dc 100644
--- a/website/src/app/hub/publish/page.spec.tsx
+++ b/website/src/app/hub/publish/page.spec.tsx
@@ -1,4 +1,4 @@
-import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import PublishPage from './page';
import { readDraft } from '@/lib/community/drafts';
@@ -115,6 +115,25 @@ describe('explicit publication', () => {
expect(translations()).toHaveLength(0);
window.history.replaceState(null, '', '/');
});
+ it('unpublishes from the edit, after asking, and only there', async () => {
+ render(<PublishPage />); await act(async () => {});
+ expect(screen.queryByRole('button', { name: 'Unpublish this harness' })).not.toBeInTheDocument();
+ cleanup();
+ window.history.replaceState(null, '', `/hub/publish?edit=${tankId}`);
+ const answer = hub(undefined, [{ id: tankId, title: tank.title }]);
+ mocks.request.mockImplementation(async (path: string, options?: { method?: string; body?: unknown }) =>
+ path === `harnesses/${tankId}` && !options ? { harness: tank, social: {} } : path === `harnesses/${tankId}` && options?.method === 'DELETE' ? { removed: true } : answer(path, options));
+ const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true);
+ render(<PublishPage />);
+ await screen.findByDisplayValue('TANK 1987');
+ fireEvent.click(screen.getByRole('button', { name: 'Unpublish this harness' }));
+ expect(mocks.request.mock.calls.some(([, options]) => options?.method === 'DELETE')).toBe(false);
+ fireEvent.click(screen.getByRole('button', { name: 'Unpublish this harness' }));
+ await waitFor(() => expect(mocks.push).toHaveBeenCalledWith('/hub/yours'));
+ expect(mocks.request).toHaveBeenCalledWith(`harnesses/${tankId}`, { method: 'DELETE' });
+ confirm.mockRestore();
+ window.history.replaceState(null, '', '/');
+ });
it('saves an arriving draft over one of your publications when you choose it', async () => {
mocks.request.mockImplementation(hub(undefined, [{ id: tankId, title: tank.title }]));
render(<PublishPage />);
diff --git a/website/src/app/hub/publish/page.tsx b/website/src/app/hub/publish/page.tsx
index f85c4d0e9..7b18d0639 100644
--- a/website/src/app/hub/publish/page.tsx
+++ b/website/src/app/hub/publish/page.tsx
@@ -15,8 +15,9 @@ import { FilesReview } from './components/FilesReview';
import { OutputInputs, SourceInputs } from './components/ProjectInputs';
import { PublishChecks } from './components/PublishChecks';
import { PublishTarget } from './components/PublishTarget';
+import { UnpublishAction } from './components/UnpublishAction';
import { originalOutput, readCover, readProjectFolder } from './projectFiles';
-import { submitPublication } from './publication';
+import { submitPublication, unpublishPublication } from './publication';
import { usePublishDraft, type PublishDraft } from './usePublishDraft';
import { useEnglishDraft } from './useEnglishDraft';
import styles from '../community.module.css';
@@ -66,6 +67,13 @@ export default function PublishPage() {
void publishOnce(async clientId => { router.push(`/hub/${await submitPublication(draft, clientId)}`); })
.catch(e => setError(e instanceof Error ? e.message : 'Publication failed. Your draft is still here.')).finally(() => setBusy(false));
}
+ function unpublish() {
+ if (!draft.updateId || busy) return;
+ const id = draft.updateId;
+ setBusy(true); setError('');
+ void publishOnce(async () => { await unpublishPublication(id); router.push('/hub/yours'); })
+ .catch(e => setError(e instanceof Error ? e.message : 'The harness could not be unpublished. Try again.')).finally(() => setBusy(false));
+ }
const updating = !!draft.updateId;
return <><Header /><main className={`${styles.wrap} ${styles.publish}`}>
@@ -92,5 +100,6 @@ export default function PublishPage() {
{(error || loadError || saveError) && <p className={styles.error} role="alert">{error || loadError || saveError}</p>}
<button className={styles.primary} disabled={busy || !ready}>{updating ? (busy ? 'Saving…' : 'Save changes') : (busy ? 'Publishing…' : 'Publish harness')}</button>
</form>
+ {updating && <UnpublishAction busy={busy} onUnpublish={unpublish} />}
</main></>;
}
diff --git a/website/src/app/hub/publish/publication.ts b/website/src/app/hub/publish/publication.ts
index d92dd4d7a..79a87df4e 100644
--- a/website/src/app/hub/publish/publication.ts
+++ b/website/src/app/hub/publish/publication.ts
@@ -31,6 +31,11 @@ export async function submitPublication(draft: PublishDraft, clientId: string |
return draft.updateId;
}
+/** Takes your publication off the Hub. Forks people already made keep their copy. */
+export async function unpublishPublication(id: string): Promise<void> {
+ await communityRequest(`harnesses/${id}`, { method: 'DELETE' });
+}
+
/** Your own publications, to choose one a draft updates. */
export async function myPublications(): Promise<{ id: string; title: string }[]> {
const { harnesses } = await communityRequest<{ harnesses: { id: string; title: string }[] }>('harnesses?mine=true');
diff --git a/website/src/lib/community/outputCheck.spec.ts b/website/src/lib/community/outputCheck.spec.ts
index 5fa27ab42..91e665a12 100644
--- a/website/src/lib/community/outputCheck.spec.ts
+++ b/website/src/lib/community/outputCheck.spec.ts
@@ -8,6 +8,13 @@ describe('output check', () => {
<style>@import "fonts.css"; body { background: url(bg.png) }</style><a href="other.html">More</a>`;
expect(outsideResources(html)).toEqual(['./app.js', 'https://cdn.example/logo.png', 'style.css', 'bg.png', 'fonts.css']);
});
+ it('names the modules and data a page\'s own scripts load', () => {
+ const html = `<script type="module">import * as THREE from 'https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js';
+ import { OrbitControls } from "./controls.js"; import 'side-effect.js'; export { x } from "./x.js";
+ const lazy = await import("./lazy.js"); fetch('data.json').then(r => r.json());
+ const label = "import nothing from here";</script><p>import "prose" is not a script</p>`;
+ expect(outsideResources(html)).toEqual(['https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js', './controls.js', 'side-effect.js', './x.js', './lazy.js', 'data.json']);
+ });
it('accepts a page that carries everything itself', () => {
expect(outsideResources('<style>i{background:url("data:image/png;base64,AA==")}</style><img src="data:image/png;base64,AA=="><script>go()</script><a href="#top">Top</a>')).toEqual([]);
});
diff --git a/website/src/lib/community/outputCheck.ts b/website/src/lib/community/outputCheck.ts
index 5c4de320a..c00c5ff18 100644
--- a/website/src/lib/community/outputCheck.ts
+++ b/website/src/lib/community/outputCheck.ts
@@ -3,6 +3,18 @@ const inline = /^(?:data:|blob:|#|about:|javascript:)/i;
const attribute = (tag: string, name: string) => tag.match(new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'i'))?.slice(1).find(value => value !== undefined)?.trim();
+/**
+ * What a page's own scripts load: modules (`import … from "…"`, `import "…"`, `export … from "…"`,
+ * `import("…")`) and `fetch("…")`. A module from a CDN is the usual way a one-file page still needs
+ * the network (three.js from jsdelivr), and the sandbox blocks it.
+ */
+const scriptBody = /<script\b[^>]*>([\s\S]*?)<\/script>/gi;
+const scriptLoads = [
+ /\b(?:import|export)\s*(?:[\w$*{}\s,]+?\s*from\s*)?["']([^"'\n]+)["']/g,
+ /\bimport\s*\(\s*["']([^"'\n]+)["']\s*\)/g,
+ /\bfetch\s*\(\s*["'`]([^"'`\n]+)["'`]/g,
+];
+
/**
* Files and addresses an output page loads that the published preview cannot reach: the sandbox
* serves no other file and blocks the network, so each one is missing for readers.
@@ -16,5 +28,8 @@ export function outsideResources(html: string): string[] {
}
for (const [, value] of html.matchAll(/url\(\s*["']?([^"')]+)["']?\s*\)/gi)) add(value.trim());
for (const [, value] of html.matchAll(/@import\s+["']([^"']+)["']/gi)) add(value);
+ for (const [, body] of html.matchAll(scriptBody)) {
+ for (const pattern of scriptLoads) for (const [, value] of body.matchAll(pattern)) add(value.trim());
+ }
return [...found];
}