Compare commits

..
111 Commits
Author SHA1 Message Date
Alex Gleason 2036903918 release: v9.16.4 2026-09-16 00:34:10 -05:00
Alex Gleason 1ca1a4e4ea Stop writing a relay tag NIP-5A never defined
The nsite manifest tag table has `path`, `x`, `d`, `a`, `A`, `server`,
`title`, `description`, and `source`, and nothing for saying which relays
the event went to. Ours went out with one per configured relay anyway,
apparently by symmetry with `server` — but a `server` tag answers a
question the host server actually asks when fetching a blob, and nothing
in the spec or in this codebase ever read the relay hints back.

So they are gone from the deploy path, and gone from the two places the
npanel migration re-signs somebody else's manifest: republishing no
longer strips the archive's relay tags only to write its own in their
place, and retitling no longer passes through whatever an older deploy
of ours left behind. Re-signing an event is the moment to stop carrying
a tag that does not exist.

Where to find the manifest stays the reader's problem and the author's
kind 10002, which is where NIP-5A leaves it.
2026-09-15 22:40:20 -05:00
Alex Gleason 710cf8b6ef release: v9.16.3 2026-09-14 14:02:35 -05:00
Alex Gleason 502fa612e0 Let somebody keep three sites and throw the other thirty-seven away
The migration dialog had one button and it did one thing to everything: Migrate
all. That reads as convenience until you look at what people are actually
holding. Two thousand one hundred and thirty-three names are still outstanding on
the gateway, a great many of them to the same few pubkeys, because the service
this replaced was where people deployed an afternoon's work to see it on a
domain. Somebody with forty names on file does not want forty sites back. They
want three, and they want the rest to stop existing under their old addresses —
and the only thing the dialog would do was hand them all forty.

So every row has its own controls now. Publish or Claim takes one name back,
worded as the work it does rather than as a category — a name whose site is
already published under this key publishes nothing, and calling that Publish was
a small lie the badge beside it was already contradicting. The badge is gone,
since the button now says what it said.

Delete calls the new DELETE /api/claims/:hostname: the gateway stops serving the
name, stops holding it, and it goes back to being anybody's. The confirmation
says only what is true, and says a different true thing depending on the row —
a site published under your own key survives the name going away, an archived one
stays on Nostr under the key that published it. Neither sentence claims the site
is gone, because nothing here can make that happen and a dialog should not offer
to.

Show is the one that makes the rest usable. None of these decisions can be made
from a hostname and a line of explanation, and the site has to be looked at —
which is why the link goes to nsite.lol rather than to the name in question. An
address outlives both the things wrong with a hostname here: it still resolves
after the name is deleted, and it works for a name too deep for a wildcard
certificate, which has answered a TLS error since the day it arrived. About a
quarter of these identifiers are longer than a DNS label leaves room for, so
those fall back to the hostname, and a name that is neither servable nor
addressable gets no button rather than a link to an error.

Two smaller things follow from having per-row actions. The stray retraction now
takes the gateway record down along with the manifest — there was never a useful
middle state where a name that can never load keeps its row — and single-row
actions do not refetch the list, which for someone clearing out twenty sites
would have been twenty signatures and twenty relay round trips to learn what the
row already said. The lists are marked stale on close instead, and the query is
disabled while the dialog is shut, so nothing is asked until it is opened again.
2026-09-14 10:01:19 -05:00
Alex Gleason 90d6bc50b9 chore: sync package-lock version to 9.16.2 2026-09-14 10:00:23 -05:00
Alex Gleason 9c48425c01 release: v9.16.2 2026-09-13 23:59:56 -05:00
Alex Gleason 344a73c6c3 Bring up the migration where somebody runs into it
Taking back a site had one way in: a button in Settings under Deploy, which said
the same thing to everybody and could not say whether anything was actually
waiting. On the gateway this was built for, two people out of eight hundred and
seven have used it.

The moment it is needed is the one somebody types a name they used to own, and
until now that moment did the opposite — the name came back taken and the button
went dead, because a name being held for its previous owner looks exactly like a
stranger's to anyone who does not ask. The gateway can now be asked, so the field
says the name is being held for them and offers the step that gets it back, in
place of a refusal with nowhere to go. The deploy dialog owns that list rather
than the field, because one recognised name is rarely all somebody has waiting.

npanel also refuses to add a name it is holding, saying to take it back instead —
a sentence that was being shown as a flat red alert with no way to act on it.
That refusal now carries the same offer.

And the settings card asks how many are waiting instead of guessing. It costs a
signature on a page nobody asked to sign on, which is the thing this deliberately
did not do before; the difference is that it is now two counted rows rather than
a read of every claimed deploy, and that the card says nothing at all unless
there is something to say. A card that cannot tell whether it applies to you is
one most people learn to ignore before it ever does.
2026-09-13 22:27:18 -05:00
Alex Gleason 4928819a0e ci: remove the ssh deploy job
deploy-nsite covers deployment now, and the rsync-over-ssh job was broken.
2026-09-13 21:33:48 -05:00
Alex Gleason 9d91542ec6 chore: sync package-lock version to 9.16.1 2026-09-13 21:25:45 -05:00
Alex Gleason 28d53e0100 release: v9.16.1 2026-09-13 21:24:10 -05:00
Alex Gleason dbb90df240 Let somebody deploy to a name they already own
The deploy form asked the gateway whether a name was free, which is not the
question it needed answered. A name somebody recovered in the migration is
theirs, is already serving their site, and came back "taken" — so the button
went dead with "That name is taken on shakespeare.wtf. Try another." about their
own site. Every name anyone took back was in this state: a hundred and four of
them for one person.

The form had an escape hatch for exactly this, and it was too narrow. It knew a
name was the user's own only if this project had deployed to it before, read out
of the project's own deploy record. A name recovered through the migration dialog
has no such record — the site was published, the hostname repointed, and nothing
about it ever went through this form.

So the question is asked properly instead. The anonymous ask happens first and is
usually the end of it, because a name somebody is picking is usually free. Only a
name that comes back taken is asked about again with a signature, which is the
one branch where the distinction exists and the one place worth spending a remote
signer on. A gateway too old to answer the second question leaves the first
answer standing, which is the behavior as it was.

The deploy itself never needed fixing: bindHostname asks for the host, is given
it, finds it already points where it is about to point, and returns. The form was
the only thing in the way.

Also compares the saved name trimmed, since that is what gets deployed — a
trailing space is not a different name, and typing one told people their own site
was somebody else's.
2026-09-13 19:25:30 -05:00
Alex Gleason 29b3ca178a release: v9.16.0 2026-09-13 17:13:52 -05:00
Alex Gleason d06b9235a8 Give a name back under the title its site chose, and say which relays took it
Three things the migration got wrong, all of them the same shape: something was
known and not said.

The archive titled every site it carried after the site's hostname, because an
address was all it knew about a site it had only ever seen at one. Handing that
back hands back an address where a name should be — a site called "Arguable"
comes home titled "arguable.shakespeare.wtf". The gateway can now read the name
the site was carrying all along, out of its webmanifest or the metadata it
publishes for link previews, and that is what gets signed. A site that never
said what it is called gets no title, which is what a manifest without one has
always meant. Its `alt` goes too: it says the site is archived so that it keeps
working, which is a true sentence about the archive and stops being true here.

Names already taken back are listed and fixed the same way, rebuilt from the
event as relays hold it rather than from the gateway's copy — a site redeployed
since the migration ran has moved on, and rebuilding it from what the gateway
fetched would quietly restore an older version of it.

Publishing to relays went through a pool that resolves on the first acceptance
and discards every other answer, so a manifest that reached one relay out of
five was reported exactly like one that reached all five, and the reasons the
other four refused were received and thrown away. Of 102 manifests published
this way in one sitting, one relay held every one and another held none, and
nothing anywhere said so. Every relay is now published to on its own and
reported on by name. One acceptance is still a success — the event exists and
whoever reads that relay will find it — so this is a note, not a failure.

The gaps that leaves are closed without signing anything: the events go out
again exactly as they are, ids and signatures unchanged, to the relays whose own
answer says they are missing them. A relay that already has one says duplicate
and nothing happens; a relay that refused before finally says why, which is the
only way to hear a reason that was discarded at the time.

Ordinary nsite deploys published the same blind way, so they use the same
helper and carry the same coverage.

Lastly, names more than one label under the gateway's domain are refused rather
than published for. A wildcard certificate covers one label, so `a.b.example.com`
can be claimed, published for, and will still fail its handshake for everyone
forever. Five are on file, inherited from a host that accepted them; one already
has a manifest published for it, which can now be retracted.
2026-09-13 16:40:33 -05:00
Alex Gleason cb5561ba69 Let people take back the sites they had before the gateway
The domains Shakespeare Deploy published to are now served by a gateway that
took them over, and the sites already under those names had to keep working, so
they were republished under an archive key rather than left to break. That key
is not theirs. This is how it stops speaking for them: the gateway holds a
record of who each name is waiting for, they publish their own copy of the site,
and the name is repointed at it.

All of it at once, because the person with one name to recover is not the person
this is for. Doing it a site at a time through the deploy button would mean
re-deploying a hundred projects, most of which are no longer checked out
anywhere, to recover sites whose files the gateway already has.

The list is only reached by asking, never on page load: finding out what is
waiting costs a signature, and a signing prompt nobody asked for is worse than a
button that sometimes opens an empty list.

A name whose site was always published under its owner's key needs nothing
republished — the record is the whole migration. The rest need the archived
manifest signed again, which reproduces the site exactly, since a manifest is
its tags and the blobs are addressed by hash and already sit where the server
tags say. Publishing happens before claiming, so the name never points at an
event the gateway has not fetched.

What a name must never do is come back at the cost of a live one. Kind 35128 is
addressable, so republishing an archived snapshot at a `d` tag someone already
publishes under would replace the current site with an old copy of itself —
which is not hypothetical: two of the first hundred names looked at were exactly
that. Those are claimed straight to the site that already exists, so both names
end up serving it. Working that out needs relays to answer, so silence from them
is treated as silence and not as "publishes nothing": a user whose own sites the
gateway is already serving must see at least those come back, or nothing is
planned at all.

Also fixes ProviderConfigDialog, which had grown a relay list and a server list
and no height limit, and was pushing its own Save button off the bottom of the
screen with no way to scroll to it.
2026-09-13 15:05:37 -05:00
Alex Gleason fc26a8b27b Deploy to the gateway that actually serves shakespeare.wtf now
Shakespeare Deploy uploaded a zip to a host that kept the files itself. That
host has been replaced: those domains are served out of nsite manifests, so a
deploy through the old API has been succeeding and changing nothing anyone can
see. This replaces it.

NpanelAdapter is NsiteAdapter plus a name. The site is an ordinary nsite under
the user's own key — same event, readable by any nsite client, gateway or no
gateway — and the second half of the deploy asks the gateway to point a hostname
at it. Its predecessor claimed names implicitly, by watching relays and
reserving whichever d tag it saw first; this one keeps an explicit row, which is
what makes a name something its owner holds rather than something they won a
race for. The hostname is asked about before it is claimed, because "nobody
holds this", "I already hold this" and "somebody else holds this" are three
different acts and creating-then-reading-the-409 cannot tell the last two apart.

The name field checks availability as you type, against an endpoint that takes
no credentials: somebody choosing a name has not decided to make an account yet.
A name this project already deployed to is not reported as taken — it is theirs.
An unreachable gateway reports available, because being wrong that way costs a
clear error at deploy time, and being wrong the other way tells someone a free
name is taken and they settle for worse.

Also fixes readDeploySettings, which swallowed a missing file and an unreadable
one alike and answered "no providers" to both. The default provider it was meant
to hand new users had therefore never reached anybody: it was written, saved
back as an empty list on the next render, and gone. The two cases are now
distinct, because inventing defaults for a file that exists but will not parse
would silently replace whatever the user had.

Providers and per-project deploy records saved under the old type are migrated
on load rather than dropped. The project file holds one record per provider a
project ever deployed to, so rejecting one entry would take a Netlify site id
and a Vercel project id with it.

Verified end to end against the live gateway: a fresh key self-enrolled,
uploaded a blob, published a manifest, claimed a name, and the site served
publicly with the SPA fallback working on a deep path.

The package-lock version bump is npm reconciling it with package.json, which
had drifted before this work.
2026-09-13 12:54:30 -05:00
Alex Gleason 4d36e2d3ff Require nsyte 0.28.0 or newer, rather than merely present
The runner image turned out to carry no nsyte at all, so every deploy
took the download fallback and ran 0.27.2, whose nostr-tools refuses to
NIP-44 encrypt a payload over 64 KiB. Signing a site manifest through
the bunker fails outright there. 0.28.0 is the first release with the
fix, and it is now baked into the image.

`command -v nsyte` also left the pin unenforceable: a baked binary of
any vintage won silently, which is how deploys kept running 0.27.2 long
after the pin moved. The check now compares versions and treats the pin
as a floor, so a newer image still wins but an older one is replaced.
2026-08-22 18:40:07 -05:00
Chad Curtis 431b8ec6bb release: v9.15.0 2026-08-19 12:52:59 -05:00
Chad Curtis 77b2be7a3b npm audit fix 2026-08-19 12:36:30 -05:00
Chad Curtis 90d02c42d6 Upgrade @nostrify/react to 0.6.6 to enforce the nostrconnect handshake secret
0.6.6 enforces the nostrconnect handshake secret. Previously a signer
could answer the connect request with result: "ack" and skip proving it
could decrypt the secret, so any relay-connected party who saw the
nostrconnect URI could claim the session and become the user's signer.

The 0.6.6 NostrLoginProvider now resolves stored logins on a microtask
(rendering a null fallback until storage resolves) rather than
synchronously. Component/hook tests render and query immediately, so
they observed an empty tree. Mock @nostrify/react/login in the test
setup with a synchronous provider and matching useNostrLogin hook,
passing every other export (NLogin, NUser, the connect helpers) through
from the real module untouched.
2026-08-19 12:34:08 -05:00
Chad Curtis d3cceb56ee Verify the LNURL invoice amount before paying a zap
Zapping asked the recipient's LNURL-pay server for an invoice and paid
whatever came back, checking only that it was a non-empty string. The
server is chosen by the recipient, so anyone who posts a note and runs
their own endpoint decided how much their victims paid — after the
victim had already approved a figure. The success toast reported the
requested amount rather than the paid one, so an overcharge left no
trace in the UI either.

Add a BOLT11 decoder (bech32 + tagged fields, on @scure/base and
@noble/hashes, both already bundled via nostr-tools) and require the
returned invoice to charge exactly the millisats the user approved.
Amountless invoices are rejected outright. The check runs before the
NWC, WebLN and QR paths alike, and useNWC's sendPayment now takes the
approved amount and re-checks it, so no future caller can hand the
wallet an unvetted invoice.

Resolve LNURL-pay in-repo instead of via nip57.getZapEndpoint, which
returns only the callback URL and discards everything used to validate
the response: HTTPS is now required for both the LNURL and the callback
it names, the advertised minSendable/maxSendable are honoured, and the
invoice's description hash is checked against the zap request (NIP-57)
or the endpoint metadata (LUD-06) when it carries one.

Report the decoded amount in the success toast so it can never
understate a spend.

Adapted from Alex Gleason's ditto commit 6e062450.
2026-08-19 12:16:08 -05:00
Alex Gleason fd23c10f20 Use the nsyte baked into the runner image
Falls back to downloading it, so the workflow still runs on a coordinator
whose image does not carry it.
2026-08-17 10:36:27 -05:00
Alex Gleason 0d73c79d4c Retry the whole nsyte download until the binary runs
From this coordinator the 115 MB release download fails about half the
time, mid-transfer, with an SSL record-mac error; curl's own --retry does
not help because each attempt breaks identically. Loop the fetch, force
HTTP/1.1, and run the binary before accepting it.

The durable fix is baking nsyte into the CI image.
2026-08-17 02:55:03 -05:00
Alex Gleason f951f21535 Retry the nsyte download
It has failed here with "SSL_read: decryption failed or bad record mac",
which curl does not treat as retryable. Also -f, so an HTTP error page is
never saved as the binary, and a version check to catch a truncated one.
2026-08-17 02:22:05 -05:00
Alex Gleason a20fab1ab4 Publish shakespeare.diy as an nsite from ngit-ci
Replaces the GitLab deploy and deploy-nsite jobs. The old nsite job published
under a personal npub; the signing pubkey is the site address, so this one
lives in the Team Soapbox namespace and is served by npanel.
2026-08-17 01:33:45 -05:00
Alex Gleason 97714079d3 Merge branch 'feat/meridian-provider' into 'main'
Feat/meridian provider

See merge request soapbox-pub/shakespeare!119
2026-07-24 01:12:13 +00:00
lemon 01d20c5743 Prefill Meridian placeholder API key, skip ToS checkbox, add purple Globe icon 2026-07-23 17:23:00 -07:00
lemon f2612831c6 Add Meridian local bridge to AI provider presets 2026-07-23 17:14:13 -07:00
Chad Curtis 278b7cd3b2 Add git.nostrhub.io to default GRASP list 2026-06-19 21:25:06 -05:00
Alex Gleason a824677fe2 Merge branch 'pr/git-gc' into 'main'
Add Git garbage collection to rescue bloated repositories

See merge request soapbox-pub/shakespeare!117
2026-06-12 14:51:11 +00:00
DanConwayDev 0eb8693d10 feat: add Optimize Repository button to project dropdown
Single self-contained recovery action: consolidates all git pack files
into one pack of every reachable object (from all branches, tags,
remotes, stash, and HEAD), removes the old packs and redundant loose
objects, and reports the size reduction in a toast. Shows a spinner
while running.

All logic (UI, gc algorithm, run state) lives in one new file; the only
other change is its render line in ProjectTitleMenu, so the feature can
be removed by deleting the file and that line.

Safety guarantees: the repository is left completely untouched if any
object fails to read during the reachability walk (an already-damaged
repo can never lose history), and also if the new undeltified pack
would not actually shrink the repo (isomorphic-git's packObjects does
no delta compression, so repacking a server-deltified clone could
otherwise grow it permanently).
2026-06-12 15:28:37 +01:00
Alex Gleason 9557356ff5 Deploy sw.js in CI 2026-06-06 10:38:58 +00:00
Alex Gleason dbbdcc32eb Revert "Edit .gitlab-ci.yml"
This reverts commit acde1d8a3a
2026-06-06 10:38:09 +00:00
Alex Gleason acde1d8a3a Edit .gitlab-ci.yml 2026-06-06 10:36:31 +00:00
Alex Gleason 5d02627cff release: v9.14.0 2026-06-05 10:38:53 -05:00
Alex Gleason 317c923532 Fix font @font-face runtime error by stripping esm.sh /* from asset URLs
Root cause of the Tailwind v4 'Missing closing } at font-face' runtime
error: font assets imported via a CSS @import (e.g. @fontsource packages)
were emitted as url(https://esm.sh/*@fontsource/...woff2). The /* from
esm.sh's wildcard ('externalize all deps') prefix sits inside an unquoted
url(), and the in-browser Tailwind v4 tokenizer misreads it as the start of
a CSS comment, scanning past the rule's closing } and throwing.

esm.sh's '*' only affects JS module builds; for raw static assets it is
meaningless and the same file is served without it. Strip the '/*' prefix
from externalized asset URLs (and ?url asset imports) so emitted CSS url()
values are parseable by all CSS parsers, not just the ones tolerant of
'/*' inside url(). JS module URLs are untouched.

Adds unit tests for stripAssetUrlWildcard.
2026-06-05 10:34:38 -05:00
Alex Gleason 18815f0649 fix: resolve all npm audit security vulnerabilities
Ran npm audit fix to resolve 19 vulnerabilities and upgraded vitest from
v3 to v4.1.8 (breaking change) to fix the critical UI server advisory
(GHSA-5xrq-8626-4rwp).

Vitest v4 no longer allows vi.fn() mocks to be used as constructors, so
converted constructor mocks (IntersectionObserver, ResizeObserver,
AbortController, NPool/NRelay1) to real classes in the test setup and
affected test files.

npm audit now reports 0 vulnerabilities.
2026-06-05 09:23:29 -05:00
Alex Gleason 98985c29de fix(build): recover from esm.sh 500 on types-only (empty-runtime) packages
esm.sh's build pipeline returns HTTP 500 for packages that ship only
TypeScript types with an effectively-empty runtime JS file (e.g.
@solana/rpc-parsed-types, pulled in transitively by @solana/kit). The
esm plugin treated this as fatal, blocking any project depending on such
a package.

When an esm.sh JS module fetch fails, fall back to jsDelivr's +esm
endpoint to inspect the package's actual runtime. If it is effectively
empty (no exports/imports/code after stripping comments, prologues, and
source-map directives), synthesize an empty ES module so the build can
proceed. Genuine non-empty failures are still re-thrown unchanged, and
the fallback is scoped to JS module requests only (asset/CSS/JSON
failures remain fatal).
2026-06-05 09:12:20 -05:00
Alex Gleason ba422b2d9e Merge branch 'nostr-connect-qr-code' into 'main'
Add nostrconnect:// QR code login for NIP-46 remote signers

See merge request soapbox-pub/shakespeare!114
2026-05-21 16:17:51 +00:00
hzrd149andClaude Opus 4.7 9313d2e0ee Unify login dialog inputs and gate QR code behind a button
Collapses the separate "Secret Key" and "Bunker" tabs into a single
input that auto-detects nsec vs bunker:// from the pasted string. File
upload runs the same detection on file contents.

The nostrconnect QR flow is now opt-in on both platforms — no relay
subscription opens until the user clicks "Login with remote signer"
(desktop) or "Open signer app" (mobile). Mobile skips QR rendering and
deep-links to the signer once the URI is generated.

BunkerLoginPanel is renamed to LoginPanel and owns all string-based
methods plus the QR session lifecycle. LoginDialog drops its
Extension/Key/Bunker Tabs structure; SimpleLoginDialog drops the
nsec/bunker tab switcher. Both now mount LoginPanel directly with
extension login below.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-15 10:43:57 -05:00
hzrd149andClaude Opus 4.7 0013ece013 Add nostrconnect:// QR code login for NIP-46 remote signers
Adds the client-initiated NIP-46 flow alongside the existing bunker:// paste
input. Desktop users scan a generated QR code with their signer app
(Amber, nsec.app, etc.); mobile users get an "Open signer app" deep-link
plus a /remoteloginsuccess callback page. The pasted bunker:// URI moves
into a collapsible fallback below the QR.

A shared BunkerLoginPanel component owns the session lifecycle and is
embedded in both LoginDialog and SimpleLoginDialog. The listener effect
depends only on a sessionToken and reads login/onLoggedIn/config through
refs so parent re-renders don't tear down an in-flight handshake.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
2026-05-12 16:08:38 -05:00
Alex Gleason 0da339c214 Anchor rsync excludes to transfer root
--exclude=index.html matches index.html at every depth, which stripped
prerendered index.html files from subdirectories. Anchoring with a
leading slash limits the exclude to the transfer root so only the root
index.html is skipped.
2026-04-29 15:44:36 -05:00
Alex Gleason 6f3cc62e00 release: v9.13.2 2026-04-29 15:27:31 -05:00
Alex Gleason 5484a57f08 Change default preview domain to iframe.diy 2026-04-29 15:19:27 -05:00
Alex Gleason 09059d87ec Restore original CI timeout 2026-04-29 15:12:44 -05:00
Alex Gleason b9b297d832 Deploy via rsync to venus.vps instead of GitLab Pages
Uses a per-site SSH key jailed on the server via rrsync. Requires CI
variables DEPLOY_SSH_KEY and DEPLOY_TARGET (user@host).
2026-04-29 15:09:27 -05:00
Alex Gleason 4ca7e20011 Remove bundled iframe-fetch-client in favor of iframe.diy
The iframe preview sandboxing service is now maintained as a separate
project at https://gitlab.com/soapbox-pub/iframe.diy and deployed at
https://iframe.diy/. Remove the stale in-tree copy and update the
services README to point to the upstream project.
2026-04-29 14:59:05 -05:00
Alex Gleason e4c4e617c6 Revert "Default to OpenCode Zen with big-pickle model for zero-config first experience"
This reverts commit 0a2cbf4bca.
2026-04-29 13:58:02 -05:00
Alex Gleason 10edacbccb Revert "Fix default settings overriding user's recently used models"
This reverts commit 2736f71687.
2026-04-29 13:58:02 -05:00
Alex Gleason 7e93367b5f release: v9.13.1 2026-04-27 00:55:38 -05:00
Alex Gleason b3fddf6cb3 Audit and overhaul virtual shell's git command
Fix critical bugs, add extensive missing flags, and add 8 new subcommands
to bring the browser-side git command closer to parity with real git.

Critical bug fixes:
- git commit: file-count classification used impossible stageStatus=1
  comparisons, always reporting 0 files changed
- git status --porcelain: untracked files could clobber staged indicators
- git add: directory walker skipped all dotfiles (including .gitignore
  itself), ignoring real git's .gitignore-based filtering
- git pull: untracked files incorrectly blocked pulls
- git reset: target regex rejected valid refs like branch names
- git diff: path filter used substring matching; --cached read working
  directory instead of index; <commit> and <commit>..<commit> forms were
  stubbed/unimplemented; used fake JS hashes instead of git.hashBlob

Implemented git reset --soft (was returning "not implemented").

New flags added across existing subcommands:
- commit: --signoff, --no-verify, -F/--file, --author, -C/--reuse-message,
  multiple -m support
- add: -u/--update, -f/--force, -n/--dry-run, absolute paths inside repo
- log: --stat, -p/--patch, --name-only, --name-status, --author, --grep,
  --since, --until, --no-merges, --reverse, --follow, custom
  --pretty=format:, proper timezone in output
- push: -u/--set-upstream (now wired to config), --tags, --delete,
  --dry-run, refspec (local:remote)
- fetch: --all, --tags, --prune now actually passed through
- branch: -a/--all, -r/--remotes, -m/-M (rename), --show-current, -v
- checkout: -B, -f/--force, commit-hash support (detached HEAD)
- config: --unset, --get-all, --add, --local, proper --list that reads
  the whole config file
- tag: real annotated tags via git.annotatedTag, -m, -f, -n, glob patterns
- clone: -b/--branch, -o/--origin, --bare
- init: -b/--initial-branch
- show: --stat, --name-only, --name-status
- diff: --stat, --name-only, --name-status
- remote: set-url, get-url, rename, show subcommands

New subcommands:
- git rm: remove files from index (and optionally worktree)
- git mv: rename/move files with index updates
- git restore: modern replacement for checkout of files
- git switch: modern replacement for branch checkout
- git merge: wrapper over git.merge (including --abort, --ff-only)
- git revert: create an inverse commit
- git rev-parse: resolve refs, --short, --abbrev-ref, --show-toplevel,
  --git-dir, HEAD~N / HEAD^N
- git ls-files: list tracked/modified/deleted/untracked files

All existing tests updated where behavior intentionally changed; new
subcommands have dedicated test suites. Final suite: 1392 passing.
2026-04-27 00:42:10 -05:00
Alex Gleason 376a982449 Overhaul shell commands for POSIX compliance and AI-agent ergonomics
Each built-in shell command has been audited and rewritten to support the
options AI agents (and humans) typically reach for, close critical behavior
gaps, and align with POSIX/GNU conventions:

- Shared argument parser (utils.ts) handles combined short flags, long
  options with '=VALUE' or space-separated values, the '--' sentinel,
  numeric shortcuts like 'head -5', and '-' for stdin.
- cat, ls, cp, mv, rm, mkdir, touch: added missing common flags; removed
  the legacy 'absolute paths are not supported' and 'reading from stdin
  is not supported' barriers where they made agent use awkward.
- mv now overwrites destinations by default (POSIX) and supports -n.
- touch updates mtime on existing files (by rewriting content) and
  accepts -c/-a/-m/-h/-r/-d/-t options.
- find: new expression engine with -iname, -path, -regex, -type,
  -empty, -size, -maxdepth, -mindepth, -not, -or, -print/-print0,
  -delete, -quit.
- grep: -v, -c, -l, -L, -w, -x, -o, -q, -E, -F, -G, -H, -h, -A/-B/-C
  context, --include/--exclude, multiple -e, -f scriptfile.
- head/tail: -c bytes, -NUM shorthand, negative/positive line counts,
  proper multi-file headers.
- sort: -k keys, -t separator, -o output, -f/-b/-d/-s, -h/-V/-M modes.
- uniq: -i, -f, -s, -w, -D, and the [input [output]] form.
- wc: -m characters and -L longest line; -c now counts bytes (UTF-8).
- cut: open-ended ranges (3-, -5), -s, --complement, --output-delimiter.
- tr: -c/-s/-t, [:class:] character classes, escape sequences.
- sed: real multi-command parser supporting ';', addresses (N, $,
  /re/, N,M), '!' negation, proper -n quiet mode, y///, and -i[SUFFIX].
- echo: -n, -e, -E with standard backslash escapes.
- pwd/cd: -L/-P, plus cd -, cd ~, cd $HOME with OLDPWD tracking.
- diff: proper LCS algorithm producing correct normal and unified
  output; adds -q, -s, -N, -i, -w, -b, -B.
- env: -i, -u, NAME=VAL assignments; reads the live shell environment.
- date: -u, -d, -R, -I, and a full GNU-subset format specifier set.

Tests for each command were updated to reflect the corrected behavior
(e.g. absolute paths and stdin are now accepted, POSIX error messages).
All 1334 tests pass; typecheck and production build succeed.
2026-04-26 23:58:13 -05:00
Alex Gleason 258dce35d2 Replace ShellTool's ad-hoc string parser with a real shell
The old ShellTool used a flat string scanner that couldn't distinguish
quote context from operator context. In practice this produced a long
tail of surprising behaviours that confused AI agents and occasionally
corrupted the virtual filesystem:

  * `echo hi 2>&1` wrote 'hi 2' to a file named literally `&1`
  * `echo hi >&2` wrote to a file named `&2`
  * `cat < in.txt` silently produced no output (input redirection
    was unimplemented but not rejected)
  * `for f in *.tsx; do ... done` was split into three separate
    "command not found" errors
  * `echo $HOME`, `echo $(pwd)`, `echo \`pwd\`` all printed
    the unexpanded source text
  * `# comment`, backslash escapes, brace expansion, tilde, and
    arithmetic all fell through as literal characters

Introduce a proper mini-shell in src/lib/shell/:

  * tokenizer.ts — POSIX-flavoured lexer that understands single and
    double quotes, backslash escapes (including line continuations),
    comments, operators, fd-prefixed redirections (IO_NUMBER), and
    dollar-led expressions ($VAR, ${...}, $(...), $((...)), backticks).
  * parser.ts — recursive-descent parser producing an AST covering
    pipelines, and-or lists, sequences, redirections (including `<<`
    heredocs and fd duplication like `2>&1`), and the full suite of
    compound commands: if/elif/else/fi, for, while, until, case,
    subshells, and brace groups.
  * expand.ts — word expansion following POSIX ordering: brace
    expansion, tilde, parameter, command substitution, arithmetic,
    word splitting, pathname expansion, quote removal. Glob patterns
    match against the virtual filesystem; unmatched patterns pass
    through unchanged.
  * executor.ts — AST interpreter that dispatches simple commands to
    the existing ShellCommand registry, applies redirections safely
    (validateWritePath runs BEFORE any file write so bogus paths can
    no longer materialize), evaluates control flow, and tracks exit
    status in $? with a safe iteration cap on while/until loops.
  * Built-ins: true, false, :, export, unset, exit, test, [.

ShellTool.ts is now a thin integration layer that wires the registry
into a ShellExecutor and formats the final output, keeping its public
API (execute, getCurrentWorkingDirectory, setCurrentWorkingDirectory,
getAvailableCommands) unchanged so existing callers (ChatPane,
Terminal) don't need to change.

Tests:
  * All 35 existing ShellTool tests still pass (adjusted two
    assertions for the improved error messages).
  * Added 29 tokenizer, 19 parser, 24 expander, and 49 end-to-end
    tests covering the bash features listed above and confirming that
    the data-corrupting redirection bugs are gone.
  * Full suite: 1316 passed / 6 skipped, typecheck clean, lint clean,
    build clean.
2026-04-26 23:16:29 -05:00
Alex Gleason b2bd91780b Expand glob patterns in ShellTool arguments
AI agents frequently write bash-style commands like `cp *.tsx src/` or
`ls src/**/*.ts`, but ShellTool previously passed wildcard tokens through
to individual commands literally. Since the command implementations don't
do their own expansion, these invocations failed with confusing errors
like "cannot stat '*.tsx'", leading agents to retry with increasingly
complex workarounds (find -exec, for loops) that also aren't supported.

Move glob expansion into the shell itself, matching how real shells work:
unquoted arguments containing `*`, `?`, or `[...]` are expanded
against the virtual filesystem before being handed to the command. Quoted
patterns and option flags are left untouched, and patterns that match
nothing pass through literally (bash default behaviour).
2026-04-26 22:51:58 -05:00
Alex Gleason 2335395641 release: v9.13.0 2026-04-26 22:19:49 -05:00
Alex Gleason af2436a3b8 Handle bare CSS @import specifiers for Tailwind v4
Tailwind v4 projects typically include `@import "tailwindcss";` in
their CSS entry and often `@import` third-party CSS plugins like
`tw-animate-css`. Both cases were broken:

1. esbuild tried to resolve `tailwindcss` through the ESM CDN as JS,
   producing 'Cannot import <...> into a CSS file'. The existing
   CSS-importer guard used `new URL(args.importer)` to detect CSS
   importers, but esbuild passes fs-namespace importers as plain paths
   (e.g. `/projects/foo/src/index.css`) which don't parse as URLs, so
   the guard never fired.

2. `@tailwindcss/browser@4` only resolves a hardcoded set of `@import`
   specifiers (`tailwindcss`, `tailwindcss/preflight`,
   `tailwindcss/theme`, `tailwindcss/utilities`) and throws
   'The browser build does not support @import for <x>' for everything
   else, so plugin packages couldn't be preserved as external either.

Detect CSS importers with a plain string match and split behavior:
`tailwindcss` and its subpaths stay external so the v4 runtime can
handle them, while other bare CSS imports fall through to the normal
esm.sh resolution path. esm.sh redirects CSS-only packages to their
`.css` entry and `onLoad` picks `loader: "css"` via the content-type
mapping, so the dependency is bundled inline. The combined CSS then
lands in the `<style type="text/tailwindcss">` block where the v4
runtime can process v4 directives (`@custom-variant`, `@theme`, etc.)
from third-party plugins.
2026-04-26 22:17:14 -05:00
Alex Gleason 1fd3d23d4f Support Tailwind CSS v4 in project builds
Detect the Tailwind major version from the project's package.json and
branch the build pipeline accordingly. v3 projects keep loading the Play
CDN runtime and a JS tailwind.config via the existing synthetic entry.
v4 projects instead pull in @tailwindcss/browser@4, which auto-scans the
document and reads theme config from CSS (@theme / @import 'tailwindcss')
so no config shim is required.
2026-04-26 19:56:25 -05:00
Alex Gleason b2c5b1d81e release: v9.12.0 2026-04-25 18:06:46 -05:00
Alex Gleason a7d026e51a Allow ambient-light-sensor permission in preview iframe 2026-04-25 18:04:44 -05:00
Alex Gleason dd078ed17d Grant microphone and other permissions to preview iframe 2026-04-25 17:41:52 -05:00
Alex Gleason 695a697e88 Support new Worker(new URL(..., import.meta.url)) and asset URLs
Shakespeare's esbuild-wasm pipeline now handles the Vite/webpack-compatible
patterns for module workers and static asset URLs, so projects using
  new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })
  new SharedWorker(new URL('./w.ts', import.meta.url), { type: 'module' })
  new URL('./logo.svg', import.meta.url)
build correctly under Shakespeare instead of emitting a 404'ing URL
that pointed at the source-file path inside the main bundle.

Mechanics:
- A new detection pass (src/lib/build/workerPlugin.ts) is invoked from
  the fs plugin's onLoad for .ts/.tsx/.js/.jsx/.mjs files. It cheaply
  regex-prefilters on 'new URL(' so 99% of files pay zero overhead,
  then strips TS/JSX via esbuild.transform and parses with acorn +
  acorn-jsx for the handful of files that actually match. The string
  literal spec inside each matched new URL() call is replaced with a
  unique placeholder token, preserving the enclosing new URL(...,
  import.meta.url) shape so runtime resolution against the main
  bundle URL still works.
- bundle() now runs a per-worker sub-build (esbuild.build) with the
  same plugin stack, producing a hashed ESM chunk alongside the main
  output. The queue drains recursively so nested workers / assets
  discovered during a sub-build are handled in the same bundle call.
- Non-source assets are copied into the output with content-hashed
  filenames (SHA-256 when SubtleCrypto is available, FNV-1a fallback
  for test environments).
- After all sub-builds finish, placeholder tokens are string-replaced
  in every JS output with the corresponding './<emitted-filename>'.
- updateCSPForEsmSh gains an emittedWorkers option; when set it
  additionally ensures worker-src and child-src exist and extends
  them with the ESM CDN so module workers can import from esm.sh.

Errors (with file:line context) are raised for classic (non-module)
workers, dynamic specifiers, and unresolvable worker specs. Plain
new URL() pointing at a source file emits a console warning and is
left untransformed.

Tests: 16 new workerPlugin unit tests cover detection, errors,
dedup, and quote-style handling; 4 new CSP tests cover the
emittedWorkers path.
2026-04-25 17:32:14 -05:00
Alex Gleason 7eab377b7f release: v9.11.4 2026-04-17 18:13:40 -05:00
Alex Gleason 6da4b63a85 Fix preview pane getting stuck during auto-refresh on rapid builds
The refresh mechanism posted a JSON-RPC `refresh` command to the nested
iframe.diy frames. During rapid build cycles, the command could be
silently dropped when the inner iframe was mid-reload, not yet mounted,
or when the outer frame's handshake was still pending \u2014 leaving the
preview stuck on a stale build with no way to recover short of reloading
the whole page.

Switch to remounting the iframe via a React key bump, which always works
regardless of handshake state. Also fix a bug in the injected preview
script where `++rpcId` (a function) silently corrupted the id generator
to NaN, breaking navigation state and uncaught error reporting.
2026-04-17 17:40:34 -05:00
Alex Gleason 565ae93aed Cache the tools array for Anthropic via OpenRouter
The tools JSON is typically 7-12K tokens, stable across every turn in
a session, and was previously re-billed at full input price on every
turn. OpenRouter explicitly supports cache_control on tool definitions
for Anthropic models (announced in their 'tool caching' release), and
the OpenAI SDK serializes the body via JSON.stringify so unknown fields
like cache_control pass through untouched.

This adds a cache_control breakpoint on the last tool, which caches the
entire tools array. Combined with the existing system + last-2-messages
breakpoints, we now use all 4 breakpoints Anthropic allows, matching
the cache hierarchy (tools -> system -> messages).

Expected savings for a 280-turn session (Opus): ~$27 for 16 tools or
~$47 for 31 tools.

Refactors the request-body transform into a named, exported
applyOpenRouterTransforms function with unit tests covering:
- cache_control placement on tools, system, and last two messages
- non-Anthropic models skip the transform
- byte-stability of the tools JSON across calls (the property the
  cache actually relies on)
- no mutation of the caller's tools array
2026-04-16 17:55:34 -05:00
Alex Gleason 429dafce92 release: v9.11.3 2026-04-12 10:52:18 -05:00
Alex Gleason 49889be240 fix: include CHANGELOG.md in ServiceWorker precache manifest for offline support 2026-04-12 10:27:13 -05:00
Alex Gleason c285dbcd05 Merge branch 'fix/app-window-not-showing-on-mobile' into 'main'
fix: render AppDialog on mobile project view

See merge request soapbox-pub/shakespeare!108
2026-04-06 14:43:27 +00:00
Dmitriy E b80205a942 fix: render AppDialog on mobile project view 2026-04-06 15:13:12 +03:00
Alex Gleason 50f85f232d release: v9.11.2 2026-04-06 00:58:48 -05:00
Alex Gleason c5605c9be8 Derive private iframe.diy subdomains with HMAC-SHA256
The project ID used for the preview iframe subdomain is AI-generated
from user input. Using it directly as the iframe.diy subdomain lets
a crafted project name produce a subdomain that collides with another
project's origin, gaining access to its localStorage/IndexedDB.

Introduce a persistent random seed in localStorage (shakespeare:seed)
and derive the subdomain as base36(HMAC-SHA256(seed, prefix|identifier)).
The prefix ("preview") domain-separates different use-cases.
The subdomain is stable per device+project but unpredictable to
third parties.
2026-04-06 00:46:01 -05:00
Alex Gleason 33564842d0 release: v9.11.1 2026-04-05 23:59:06 -05:00
Alex Gleason 0511976688 Switch back to local-shakespeare.dev, which is now an iframe.diy instance 2026-04-05 23:47:55 -05:00
Alex Gleason 819813a000 Replace local-shakespeare.dev with iframe.diy for preview pane 2026-04-05 23:34:15 -05:00
Alex Gleason 2736f71687 Fix default settings overriding user's recently used models
Separate EMPTY_AI_SETTINGS (for initial state and error fallback) from
OPENCODE_DEFAULT_SETTINGS (for genuinely new users only). Previously,
readAISettings returned OPENCODE_DEFAULT_SETTINGS on any error, which
could overwrite an existing user's recentlyUsedModels with
['opencode/big-pickle']. Now the error path returns empty settings, and
OPENCODE defaults are only applied when no providers are configured.
2026-04-04 02:13:35 -05:00
Alex Gleason 0a2cbf4bca Default to OpenCode Zen with big-pickle model for zero-config first experience
Pre-configure OpenCode Zen as the default AI provider so new users can
submit prompts immediately without any setup. Sends x-opencode-* headers
to qualify for the higher daily rate limit tier.
2026-04-04 01:26:07 -05:00
Alex Gleason c359eda1d6 Fix showcase card clone URLs to use NostrURI for proper npub encoding 2026-04-04 00:10:55 -05:00
Alex Gleason 269047d742 Update default blossom servers and relay lists
Add blossom.ditto.pub and blossom.dreamith.to to the top of all blossom
server lists. Add relay.dreamith.to below relay.ditto.pub and remove
relay.damus.io and purplerelay.com from deploy relay lists.
2026-04-03 23:59:20 -05:00
Alex Gleason d2673effd8 Change default nsite gateway to shakespeare.to 2026-04-03 23:38:36 -05:00
Alex Gleason c49564e70d Support vanity subdomain URLs for nsite deployments
After deploying a named site, the adapter probes the gateway for vanity
subdomain support via X-Nsite-* response headers. When the gateway
confirms a vanity name (e.g. ditto.shakespeare.wtf), it is used as the
primary deploy URL. Gracefully degrades to the canonical base36 URL when
the gateway doesn't support vanity subdomains.
2026-04-03 22:49:38 -05:00
Alex Gleason 63671ea85b Fix SW excluding all /_* paths, breaking SvelteKit nsites
The fetch event handler was skipping all paths starting with `/_`,
intended to protect iframe-fetch-client system files. But this also
excluded SvelteKit asset paths like `/_app/immutable/chunks/*.js`,
causing them to bypass JSON-RPC and hit the network directly, which
returns HTML instead of JavaScript.

Narrow the exclusion to only `/_iframe-client/` — the specific
prefix used by the iframe-fetch-client's own assets.
2026-04-03 18:58:24 -05:00
Alex Gleason 46fefd5352 release: v9.11.0 2026-04-03 16:09:05 -05:00
Alex Gleason 13dd307292 Update curator list to use Shakespeare Builders list 2026-04-03 16:04:26 -05:00
Alex Gleason 271013f834 Deduplicate auto-added t-tags to prevent duplicates on re-save 2026-04-03 15:32:43 -05:00
Alex Gleason 31fcb60cd3 Show banner and icon in showcase cards, require both to appear in showcase 2026-04-03 15:20:30 -05:00
Alex Gleason 6bec129e93 Break Advanced section into General, Handlers, and Tags tabs 2026-04-03 14:29:58 -05:00
Alex Gleason 5f56652479 Add ngit repo and nsite deployment naddr fields to App dialog Advanced section 2026-04-03 14:27:34 -05:00
Alex Gleason be458ece7b Add 'All' option to web handler type dropdown so it can be reset 2026-04-03 14:20:44 -05:00
Alex Gleason 1d6ad575f6 Fix type dropdown placeholder to say 'All' 2026-04-03 14:19:24 -05:00
Alex Gleason 68c51fb48f Default web handler type dropdown to 'All' to indicate it's optional 2026-04-03 14:15:35 -05:00
Alex Gleason a81b8420f5 Add t-tag editor under Advanced in App dialog 2026-04-03 14:13:55 -05:00
Alex Gleason ddc1e02431 Add Delete App button under Advanced when editing an existing app 2026-04-03 13:56:16 -05:00
Alex Gleason 8f9ce95a43 Autofill app form from OG tags and web manifest on first publish 2026-04-03 13:50:04 -05:00
Alex Gleason d015887338 Replace per-field Required labels with a consolidated validation summary above the save button 2026-04-03 13:39:49 -05:00
Alex Gleason b7e7f5420a Only show banner pencil badge when a banner image is already set 2026-04-03 13:38:32 -05:00
Alex Gleason 9daccc1947 Show inline validation errors on submit attempt and remove Save icon from button 2026-04-03 13:38:20 -05:00
Alex Gleason c3f1cbc50a Remove website divider and require name, description, website, icon, and banner before saving 2026-04-03 13:35:10 -05:00
Alex Gleason 612759ed64 Move Website field into the app preview card 2026-04-03 13:32:44 -05:00
Alex Gleason b2cfcd7e17 Redesign App dialog banner/icon UI with overlapping avatar card layout 2026-04-03 13:30:39 -05:00
Alex Gleason 08357aa694 Add banner photo upload to App dialog 2026-04-03 13:27:02 -05:00
Alex Gleason c23a79dfb0 Remove nsec and nrelay from Web Handlers type dropdown 2026-04-03 13:21:22 -05:00
Alex Gleason 5102028f6b Replace handler type input with NIP-19 identifier type dropdown in Web Handlers 2026-04-03 13:20:53 -05:00
Alex Gleason 18191e3a27 Remove useless Nostr coordinate element from App dialog 2026-04-03 13:19:07 -05:00
Alex Gleason b1b451072b Fix bunker issue by upgrading Nostrify 2026-04-03 13:17:38 -05:00
Alex Gleason 5d9bc40f51 config: set default showcase curator to soapbox team follow pack 2026-04-03 01:09:14 -05:00
Alex Gleason a644994e93 refactor: replace showcase moderator with curator using NIP-19 event p-tags
Replace the hardcoded 'moderator' npub pattern with a 'curator' field that
accepts any note1/nevent1/naddr1 identifier. The p-tag pubkeys from the
resolved event are used as authors in a kind 31990 (#t:shakespeare) query.
Client-side filter ensures only apps with a 30617 git repo reference are
shown, guaranteeing the 'Edit with Shakespeare' button can be rendered.

All moderation controls (approve/feature/hide/etc.) are removed from
AppShowcaseCard. AppShowcase is simplified to a flat grid.
2026-04-03 01:08:46 -05:00
Alex Gleason ac0e13a09a ci: publish zsp to relay.ditto.pub and use blossom.ditto.pub; remove --publish-server-list from nsite 2026-04-03 00:18:01 -05:00
Alex Gleason 0565eb7aab release: v9.10.4 2026-04-02 21:50:49 -05:00
Alex Gleason e40504ebc6 Fix splash screen: use original colors instead of white silhouette 2026-04-02 21:42:34 -05:00
Alex Gleason 7ccf9ddcc9 release: v9.10.3 2026-04-02 21:27:47 -05:00
Alex Gleason 4976493be3 Replace all default Capacitor images with Shakespeare branding
- Regenerate launcher icon PNGs with colorful logo (not white silhouette)
- Update adaptive icon vector drawable with original logo colors
- Generate splash screen PNGs for all densities and orientations
- Update generate-icons.sh to use colorful SVG and generate splash screens
2026-04-02 21:24:53 -05:00
Alex Gleason 3192ae7f08 release: v9.10.2 2026-04-02 20:45:19 -05:00
Alex Gleason e2d615c2c1 Regenerate launcher icon PNGs with Shakespeare logo 2026-04-02 20:44:11 -05:00
230 changed files with 22652 additions and 8647 deletions

No files matched your search

+2 -15
View File
@@ -28,20 +28,6 @@ test:
- npm run build
- npm run test
pages:
stage: deploy
rules:
- if: $CI_COMMIT_TAG
when: never
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
script:
- npm run build
- rm -rf public
- mv dist public
artifacts:
paths:
- public
deploy-nsite:
stage: deploy
timeout: 10 minutes
@@ -73,7 +59,6 @@ deploy-nsite:
--relays "wss://relay.ditto.pub,wss://relay.nsite.lol,wss://relay.dreamith.to,wss://relay.primal.net"
--servers "https://blossom.primal.net,https://blossom.ditto.pub,https://blossom.dreamith.to"
--fallback "/index.html"
--publish-server-list
--use-fallback-relays
--use-fallback-servers
@@ -222,6 +207,8 @@ publish-zapstore:
- if: $CI_COMMIT_TAG =~ /^v\d+\.\d+\.\d+$/
variables:
SIGN_WITH: $ZAPSTORE_BUNKER_URL
RELAY_URLS: "wss://relay.zapstore.dev,wss://relay.ditto.pub"
BLOSSOM_URL: "https://blossom.ditto.pub"
script:
- go install github.com/zapstore/zsp@latest
+137
View File
@@ -0,0 +1,137 @@
name: Deploy nsite
# Builds dist/ and publishes it as the named nsite "shakespeare" (NIP-5A kind
# 35128) described by .nsite/config.json: the files become Blossom blobs, the
# manifest mapping path -> sha256 goes to relays, and npanel on venus serves
# shakespeare.diy from it. Runs on pushes to the default branch, alongside
# Test.
#
# Replaces the GitLab `deploy-nsite` job, which published the same site under a
# PERSONAL npub with nsyte 0.24.1. The signing pubkey IS the site address, so
# this one lives in the Team Soapbox namespace instead.
#
# Secrets are provisioned by the ngit-ci operator as
# NGIT_CI_SECRET_<ALIAS>__<NAME> (note the double underscore) and injected ONLY
# on maintainer-authored triggers, which a push to a watched repo always is.
# This job needs one:
# NSYTE_BUNKER nbunksec1... -- a pre-established NIP-46 session, the form
# nsyte documents for CI.
# An empty NSYTE_BUNKER fails the job rather than skipping quietly: this is the
# only workflow that publishes the client anywhere, so a skipped run would
# leave the nsite silently pinned to an older build.
#
# NOTE: *.shakespeare.diy is NOT served from here. The wildcard keeps its own
# Caddy vhost and /var/www tree on venus, because the nsite catch-all issues
# certificates on demand over HTTP-01 and cannot get a wildcard.
on:
push:
branches: [main]
jobs:
deploy:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
# Ahead of the build, so a config nsyte will not accept costs seconds
# rather than failing at the end of a green-looking run.
- name: Install nsyte and validate the config
env:
NSYTE_BUNKER: ${{ secrets.NSYTE_BUNKER }}
run: |
set -eu
: "${NSYTE_BUNKER:?NSYTE_BUNKER is not set; ask the ngit-ci operator to provision it for this repo alias.}"
# Pin the binary as a FLOOR, not an exact version. An unversioned
# install has been observed pulling 0.10.1, which emits legacy
# kind-34128 events that every current gateway ignores while still
# reporting a successful deploy. 0.28.0 is the floor because it is the
# first release whose nostr-tools will encrypt a NIP-44 payload larger
# than 64 KiB; under it, signing a large site manifest through the
# bunker fails outright.
#
# nsyte is baked into the coordinator's CI image alongside zsp
# (armada's .ngit/ci-image/Dockerfile). Comparing its VERSION rather
# than just `command -v` is deliberate: a stale baked binary silently
# outranked this pin, which is how deploys kept running 0.27.2 long
# after the pin moved. Accepting anything NEWER than the floor lets
# the image move ahead of these files without sending every job back
# to the download.
#
# That download is the fallback for a coordinator whose image lacks
# nsyte, and is exactly what kept failing here: the ~129 MB release
# asset broke mid-transfer with "SSL_read: decryption failed or bad
# record mac", identically on every attempt within a run, taking
# deploy-nsite down across every repo. Hence the loop, HTTP/1.1, and
# running the binary before trusting it.
NSYTE_MIN_VERSION=0.28.0
# nsyte colours its version output with ANSI escapes even when piped.
baked="$(NO_COLOR=1 nsyte --version 2>/dev/null \
| sed 's/\x1b\[[0-9;]*m//g' | awk 'NR == 1 { print $2 }')"
oldest="$(printf '%s\n%s\n' "$NSYTE_MIN_VERSION" "$baked" | sort -V | head -1)"
if [ -n "$baked" ] && [ "$oldest" = "$NSYTE_MIN_VERSION" ]; then
echo "using the nsyte baked into the runner image ($baked)"
else
test -z "$baked" || echo "baked nsyte $baked is below $NSYTE_MIN_VERSION; downloading"
NSYTE_URL="https://github.com/sandwichfarm/nsyte/releases/download/v${NSYTE_MIN_VERSION}/nsyte-linux-${NSYTE_MIN_VERSION}"
ok=""
for attempt in 1 2 3 4 5; do
if curl -fsSL --http1.1 --retry 2 --retry-delay 5 --retry-all-errors \
--connect-timeout 20 --max-time 900 -o /usr/local/bin/nsyte "$NSYTE_URL" \
&& chmod +x /usr/local/bin/nsyte \
&& nsyte --version >/dev/null; then
ok=yes
break
fi
echo "nsyte download attempt $attempt failed; retrying in 10s"
sleep 10
done
test -n "$ok" || { echo "could not download a working nsyte after 5 attempts"; exit 1; }
fi
nsyte --version
nsyte validate
- run: npm ci
# Builds dist/ and copies index.html -> 404.html, the path NIP-5A host
# servers fall back to.
- run: npm run build
# Sourcemaps are ~290 files and 30 MB of blobs nobody fetches, and they
# near-double the manifest. The GitLab job dropped them too.
- run: find dist -name '*.map' -delete
- name: Publish to Blossom + relays
env:
NSYTE_BUNKER: ${{ secrets.NSYTE_BUNKER }}
run: |
set -eu
# Relays, servers and the site id all come from .nsite/config.json,
# so they are versioned with the client rather than split across this
# file. The secrets scan is skipped because it prompts on false
# positives in our own bundle (pubkeys, bunker:// parsing code), and
# a prompt is unanswerable here -- with -i it defaults to N and
# aborts.
set +e
nsyte deploy dist \
--sec "$NSYTE_BUNKER" \
--concurrency 2 \
--non-interactive \
--skip-secrets-scan 2>&1 | tee /tmp/nsyte-deploy.log
status="${PIPESTATUS[0]}"
set -e
# A deploy that changes no file exits NON-ZERO with "No new files to
# upload". That is success: the manifest already on the relays
# describes exactly this build.
if [ "$status" -ne 0 ] && ! grep -q "No new files to upload" /tmp/nsyte-deploy.log; then
exit "$status"
fi
+31
View File
@@ -0,0 +1,31 @@
name: Test
# Typecheck / lint / unit tests / production build for the Shakespeare client.
# ngit-ci watches .ngit/act/workflows/ and runs each job with `act` (GitHub
# Actions-compatible syntax) in a Linux container. Runs on every push and on
# every Nostr PR.
on:
push:
branches: ["**"]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- run: npm ci
# package.json splits these: "typecheck" is tsc --noEmit and "test" is
# eslint + vitest. The GitLab job ran typecheck, build and test; keep all
# three so a type error still fails CI.
- run: npm run typecheck
- run: npm run build
- run: npm run test
+20
View File
@@ -0,0 +1,20 @@
{
"$schema": "https://nsyte.run/schemas/config.schema.json",
"relays": [
"wss://relay.ditto.pub",
"wss://relay.dreamith.to",
"wss://relay.primal.net"
],
"id": "shakespeare",
"servers": [
"https://blossom.ditto.pub",
"https://blossom.dreamith.to",
"https://blossom.primal.net"
],
"fallback": "/index.html",
"publishRelayList": false,
"publishServerList": false,
"title": "Shakespeare",
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment.",
"source": "https://gitworkshop.dev/soapbox.pub/relay.ngit.dev/shakespeare"
}
+36 -1
View File
@@ -67,7 +67,7 @@ Shakespeare provides a comprehensive set of shell commands that are JavaScript r
- **File Operations**: `cat`, `cp`, `mv`, `rm`, `touch`, `find`, `grep`
- **Directory Operations**: `cd`, `ls`, `mkdir`, `pwd`, `tree`
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, `git diff`, `git branch`, `git checkout`, `git switch`, `git merge`, `git revert`, `git rm`, `git mv`, `git restore`, `git rev-parse`, `git ls-files`, `git tag`, `git stash`, `git fetch`, `git clone`, `git init`, `git reset`, `git show`, `git remote`, `git config`
#### Security
@@ -77,6 +77,41 @@ AI filesystem access through tools (including shell commands via ShellTool) has
- **Write operations**: Restricted to current project directory and `/tmp/` directory (including subdirectories)
- **Copy operations**: Can copy from any absolute path to relative paths or `/tmp/`, but cannot copy from relative to absolute paths outside allowed areas
#### Web Workers and Asset URLs
Shakespeare's esbuild-wasm build pipeline supports the Vite/webpack-compatible patterns for loading Web Workers and static assets:
```ts
// Module Worker (required: { type: 'module' })
const worker = new Worker(
new URL('./worker.ts', import.meta.url),
{ type: 'module' },
);
// SharedWorker, same pattern
const shared = new SharedWorker(
new URL('./shared.ts', import.meta.url),
{ type: 'module' },
);
// Static asset URL (images, wasm, fonts, audio, etc.)
const logoUrl = new URL('./logo.svg', import.meta.url);
```
**Supported:**
- `new Worker(new URL('<spec>', import.meta.url), { type: 'module' })`
- `new SharedWorker(new URL('<spec>', import.meta.url), { type: 'module' })`
- `new URL('<spec>', import.meta.url)` where `<spec>` resolves to a non-source file (images, wasm, audio, fonts, etc.)
- Relative (`./`, `../`), absolute (`/`), and alias (`@/`) specifiers
- String literals with any quote style, including backticks without interpolation
**Not supported (will emit a build error):**
- Classic (non-module) workers — `{ type: 'module' }` is required
- Dynamic specifiers — the first argument to `new URL()` must be a string literal
- `new URL(..., import.meta.url)` pointing at source files (`.ts/.tsx/.js/.jsx/.mjs/.cjs/.css`); use a regular import or the Worker pattern instead (emits a console warning, then leaves the expression untouched)
Workers are bundled as separate ESM chunks and can import from npm packages normally — the same ESM-CDN rewrites applied to the main bundle apply to workers. When any workers are emitted, the build also extends the output CSP's `worker-src` and `child-src` directives to permit loading the ESM CDN from within workers.
### Git Integration with isomorphic-git
Shakespeare provides full Git functionality in the browser using `isomorphic-git` and `@isomorphic-git/lightning-fs`, with all data persisted in IndexedDB.
+155 -1
View File
@@ -1,9 +1,163 @@
# Changelog
## [9.16.4] - 2026-09-16
### Changed
- Published sites carry only the tags the nsite spec defines — the relay hints Shakespeare used to attach were read by nothing, and taking a site back no longer rewrites them
## [9.16.3] - 2026-09-14
### Added
- Take back your sites one at a time — every name waiting for you now has its own Publish, Show, and Delete buttons, so you can keep the few you want and clear out the rest
- Show opens a site by its Nostr address before you decide about it, so you can look at names that never loaded in a browser
### Changed
- Deleting a name only gives it up on shakespeare.wtf — anything published to Nostr stays yours
- Names that couldn't be taken back safely can now be cleared out, instead of only explaining why they were stuck
## [9.16.2] - 2026-09-13
### Changed
- Deploy settings now says how many of your names are waiting to be taken back, and stays quiet when there are none
### Fixed
- Names you published before shakespeare.wtf changed hands are recognized as yours as you type them — the Deploy screen offers to hand them back instead of reporting them taken by somebody else
## [9.16.1] - 2026-09-13
### Fixed
- Deploying to a name you already own works again — names you took back in the migration were reported as taken by somebody else, and the Deploy button refused to publish to your own site
## [9.16.0] - 2026-09-13
### Added
- Take back the sites you published before shakespeare.wtf changed hands — Deploy settings now lists every name that's waiting for you and hands them all back at once, republished under your own key
- Deploys report which relays accepted your site, and can fill in any that missed it without republishing
### Changed
- Deploying to Shakespeare now publishes your site to Nostr under your own key, so it stays readable by any Nostr site viewer with or without shakespeare.wtf
- Recovered sites are titled whatever they call themselves rather than after their web address
### Fixed
- Deploying to Shakespeare works again — it had been reporting success while changing nothing, because the host it uploaded to no longer serves those addresses
- New accounts start with Shakespeare set up as a deployment target instead of an empty screen
- Deployment provider settings now scroll, so Save is always reachable
## [9.15.0] - 2026-08-19
### Added
- Connect to Meridian as an AI provider — available as a one-click preset with streamlined setup
- Optimize Repository action in the project menu that consolidates git history to reclaim space and repair bloated repositories
### Fixed
- Zaps now verify the invoice amount before paying, so you're never charged more than you approved
## [9.14.0] - 2026-06-05
### Added
- Log in with a remote signer by scanning a QR code — connect your NIP-46 mobile signer to Shakespeare without copying and pasting bunker strings
### Changed
- Unified the login dialog into a single, streamlined experience across sign-in methods
### Fixed
- Custom fonts now load correctly in previews instead of triggering a runtime error
- Builds no longer fail when a project depends on types-only packages
- Resolved all known security vulnerabilities in dependencies
## [9.13.2] - 2026-04-29
### Changed
- Preview pane now uses the new iframe.diy sandboxing service for a faster, more reliable preview experience
## [9.13.1] - 2026-04-27
### Changed
- AI agents now run commands through a real POSIX-style shell with proper quoting, pipes, redirects, and glob expansion, making multi-step project edits more reliable
- Overhauled the built-in `git` commands used by AI agents, adding `ls-files`, `merge`, `mv`, `restore`, `rev-parse`, `revert`, `rm`, and `switch` alongside improvements across existing git operations
- Overhauled core shell commands (`cat`, `cp`, `find`, `grep`, `ls`, `sed`, `sort`, and more) for closer POSIX behavior and better ergonomics when AI agents work on your project
## [9.13.0] - 2026-04-26
### Added
- Build projects with Tailwind CSS v4, including `@import "tailwindcss"` entry files and third-party v4 plugins like `tw-animate-css`
## [9.12.0] - 2026-04-25
### Added
- Build support for module workers and static asset URLs — projects using `new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })`, `SharedWorker`, and `new URL('./logo.svg', import.meta.url)` now build and run correctly in the preview
- Preview pane grants microphone, ambient-light-sensor, and other device permissions so richer apps can run inside the preview
## [9.11.4] - 2026-04-17
### Fixed
- Preview pane no longer gets stuck on stale builds during rapid edits
### Changed
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
## [9.11.3] - 2026-04-12
### Fixed
- App publish dialog now appears on mobile devices
- Changelog available offline via ServiceWorker precache
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
- Switch preview pane to iframe.diy for improved reliability and compatibility
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
- Update default Blossom servers and relay lists across deployments and uploads
### Fixed
- Default settings no longer override existing users' recently used models
- Showcase card clone URLs now use proper Nostr URI encoding
- Service worker no longer blocks SvelteKit nsite routes
## [9.11.0] - 2026-04-03
### Added
- Upload a banner image for your app directly from the App dialog
- T-tag editor in the App dialog Advanced section for tagging your app by category
- Delete App button in the App dialog Advanced section when editing an existing app
- Ngit repo and nsite deployment address fields in the App dialog Advanced section
- Auto-fill app name, description, and images from your project's OG tags and web manifest on first publish
### Changed
- Redesigned App dialog with an overlapping banner and avatar card layout
- Reorganized App dialog Advanced section into General, Handlers, and Tags tabs
- Showcase cards now show banner and icon images, and require both to appear in the showcase
- Validation summary above the Save button replaces per-field "Required" labels
- Updated showcase curator to the Shakespeare Builders community list
### Fixed
- Upgrade Nostrify to fix bunker connection issues
## [9.10.4] - 2026-04-02
### Fixed
- Fix Android splash screen showing logo masked to white silhouette instead of full color
## [9.10.3] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor splash screen and icon colors
## [9.10.2] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor icon instead of Shakespeare logo in app drawer
## [9.10.1] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor icon instead of Shakespeare logo in app drawer
- Replace default Capacitor vector drawable icons with Shakespeare logo
## [9.10.0] - 2026-04-02
Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.5 KiB

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

After

Width:  |  Height:  |  Size: 41 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.7 KiB

After

Width:  |  Height:  |  Size: 26 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.0 KiB

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

After

Width:  |  Height:  |  Size: 42 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 57 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 17 KiB

After

Width:  |  Height:  |  Size: 79 KiB

@@ -5,11 +5,10 @@
android:viewportHeight="108">
<!--
Shakespeare parrot logo from public/shakespeare.svg.
SVG viewBox is "0 0 128 128".
We scale to ~55% and center within the 108x108 viewport to fit
Shakespeare theater masks logo from public/shakespeare.svg.
SVG viewBox is "0 0 128 128", with original colors preserved.
Scaled to ~55% and centered within the 108x108 viewport to fit
Android's adaptive icon safe zone (66% of 108dp).
Scale factor: 108 * 0.55 / 128 ≈ 0.464. Translate to center.
-->
<group
@@ -18,36 +17,66 @@
android:scaleX="0.464"
android:scaleY="0.464">
<!-- Beak right -->
<!-- Red beak right -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M110.28,61.32l2.63,8.84c0,0,7.24,-1.6,7.62,3.2c0.38,4.8,-6.77,8,-6.77,8l2.26,10.63 c0,0,7.9,-6.4,8,-15.61c0,0,0.66,-11.29,-6.11,-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
<!-- Tail feathers -->
<!-- Red tail feathers -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M68.71,94.99c0,0,-11.1,-4.7,-16.46,1.98c-0.75,0.94,-1.41,1.88,-2.16,2.82 c-0.56,0.75,-1.13,1.5,-1.69,2.16c-0.47,0.56,-1.03,1.13,-1.69,1.5c-0.66,0.38,-1.32,0.66,-2.07,0.85c-0.94,0.19,-1.88,0.19,-2.82,0.09 c-1.32,-0.09,-2.63,-0.38,-3.95,-0.66c-0.47,-0.09,-0.85,-0.19,-1.22,-0.28c-0.09,0,-0.19,-0.09,-0.28,-0.09 s-0.19,-0.09,-0.28,-0.09c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98 c1.32,0.66,2.73,1.03,4.14,1.13c0.09,0,0.38,0,0.47,0.09c0.19,0.19,-0.28,0.47,-0.47,0.56c-0.28,0.19,-0.47,0.28,-0.75,0.38 c-0.85,0.38,-1.79,0.56,-2.63,0.75c-0.85,0.19,-1.69,0.28,-2.45,0.28c-0.47,0,-0.85,0.09,-1.22,0.09c-0.28,0,-0.56,-0.09,-0.85,0 s0.09,0.47,0.28,0.56c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38 c1.32,-0.19,2.63,-0.56,3.86,-1.03c6.77,-3.1,6.21,-9.59,12.42,-10.16c4.61,-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
<!-- Beak left -->
<!-- Red beak left -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M19.79,38.28c0,0,-12.13,1.98,-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22,-9.41 c0,0,-13.07,-1.32,-12.32,-6.3c0.94,-6.21,11.85,-5.64,11.85,-5.64L19.79,38.28z"/>
<!-- Wing detail -->
<!-- Red wing detail -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M20.73,70.92c0,0,-1.88,0.56,-4.61,2.54c-1.88,1.32,-4.42,3.01,-6.87,5.93 c-1.22,1.41,-2.16,3.1,-2.82,4.89c-0.47,1.22,-0.66,2.45,-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66 c0.09,-0.09,0.19,-0.38,0.28,-0.47c0.19,-0.47,0.47,-0.85,0.75,-1.22c0.85,-1.13,1.88,-2.16,3.01,-3.01c0.38,-0.28,0.75,-0.47,1.13,-0.66 c0.28,-0.28,0.75,-0.66,0.94,-0.28c0.09,0.19,-0.09,0.47,-0.19,0.66c-0.09,0.28,-0.19,0.66,-0.19,0.94c-0.38,1.5,-0.56,3.01,-0.75,4.51 c-0.09,0.85,-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19 c0.09,-0.09,0.09,-0.19,0.19,-0.38c0.19,-0.28,0.28,-0.66,0.47,-0.94c0.47,-0.85,0.94,-1.69,1.5,-2.63c0.66,-1.13,1.41,-2.16,2.16,-3.1 c0.85,-1.13,1.88,-2.26,2.92,-3.2c1.13,-1.03,2.35,-2.07,3.67,-2.92c0.75,-0.47,1.6,-0.94,2.45,-1.32L20.73,70.92z"/>
<!-- Body -->
<!-- Yellow body -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#FCC21B"
android:pathData="M116.4,79.29c-1.13,-5.55,-2.73,-11.01,-4.51,-16.46c-1.5,-4.61,-3.1,-9.31,-5.83,-13.36 c-1.22,-1.79,-3.01,-3.01,-5.27,-3.86c-4.33,-1.69,-9.97,-1.98,-13.73,-1.98c-5.64,0,-11.48,1.22,-16.74,3.67 c-1.88,5.64,-7.05,19.94,-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23 c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66 c2.54,-1.13,4.61,-2.92,6.3,-5.08c1.79,-2.26,3.2,-4.8,4.42,-7.43c1.88,-3.95,3.86,-8.37,4.14,-12.89 C117.99,87.38,117.24,83.24,116.4,79.29z"/>
<!-- Head -->
<!-- Blue head -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#429ADF"
android:pathData="M77.64,33.57c-0.28,-1.03,-1.03,-2.07,-1.6,-3.01c-6.3,-11.01,-20.04,-16.27,-32.26,-15.52 c-3.76,0.28,-9.31,0.85,-13.54,2.73c-2.07,0.94,-3.86,2.35,-4.99,4.14c-2.54,4.23,-3.76,8.94,-5.08,13.64 C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89,-1.41,10.25,-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32 c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94,-0.19,1.98,-0.28,2.92,-0.56 c1.88,-0.47,3.67,-1.13,5.46,-1.79c7.52,-3.01,13.64,-7.43,17.68,-14.58c1.69,-3.1,3.1,-6.4,4.42,-9.69c0.09,-0.19,0.19,-0.38,0.19,-0.56 c1.98,-5.46,3.29,-11.19,4.61,-16.84c0.66,-2.73,1.41,-5.55,1.79,-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
<!-- Dark eye band -->
<path
android:fillColor="#193D51"
android:pathData="M23.09,40.53c1.69,-3.1,5.74,-5.55,9.31,-5.08c0.56,0.09,1.22,0.19,1.79,0.47 c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75,-0.66,0.85,-1.22,0.38c-1.98,-1.69,-3.57,-3.01,-6.21,-3.67c-2.16,-0.56,-4.61,-0.28,-6.68,0.28 c-0.47,0.09,-1.22,0.56,-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
<!-- Dark mouth/chin -->
<path
android:fillColor="#193D51"
android:pathData="M62.21,64.9c-1.03,1.6,-2.45,3.01,-3.86,4.33c-0.38,0.28,-0.66,0.66,-1.03,0.94 c-5.64,4.7,-13.26,7.05,-20.51,5.27c-1.98,-0.47,-4.14,-1.5,-5.74,-2.73c-1.22,-0.94,-2.45,-2.16,-3.48,-3.39c-1.88,-2.26,-3.29,-4.89,-4.23,-7.62 c-0.47,-1.41,-0.75,-2.73,-0.94,-4.23c0,-0.47,-0.66,-5.46,0.85,-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03 c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09 c5.08,-0.28,10.25,-1.79,14.86,-3.76c0.38,-0.19,0.85,-0.47,1.32,-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
<!-- Dark eye detail -->
<path
android:fillColor="#193D51"
android:pathData="M67.58,51.16c0,0.47,-0.19,1.13,-0.75,1.03c-0.47,-0.09,-0.85,-0.94,-1.13,-1.22 c-1.32,-1.69,-3.86,-3.57,-6.4,-4.14c-3.01,-0.75,-5.27,0.56,-8.28,0.85c-0.85,0.09,-1.32,-0.28,-0.94,-1.03c1.6,-3.48,5.83,-6.21,10.25,-5.46 c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
<!-- Gold eye detail -->
<path
android:fillColor="#9B7515"
android:pathData="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41,-0.09,2.26,0.09,1.88,1.69 c-0.75,3.29,-3.86,5.17,-6.87,5.83c-0.75,0.19,-1.5,0.19,-2.26,0.19c-1.41,-0.09,-2.82,-0.66,-4.04,-1.5c-2.63,-1.79,-4.61,-4.89,-5.17,-8 C89.68,63.67,90.25,62.83,91.84,63.86z"/>
<!-- Gold mouth detail -->
<path
android:fillColor="#9B7515"
android:pathData="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51,-2.35,9.03,-5.93,11.38,-10.63 c0.85,-1.79,1.79,-1.41,2.45,0.28c1.13,3.1,1.03,6.87,-0.38,9.88c-0.66,1.41,-1.6,2.63,-2.82,3.57c-0.66,0.47,-1.32,0.75,-2.07,1.03 C71.43,83.33,67.58,83.24,65.22,80.79z"/>
<!-- Gold chin/jaw detail -->
<path
android:fillColor="#9B7515"
android:pathData="M110,96.41c-0.38,0,-0.94,-0.38,-1.41,-0.66c-0.47,-0.28,-0.94,-0.66,-1.22,-0.85 c-1.13,-0.56,-2.45,-1.13,-3.67,-1.5c-3.76,-1.22,-7.9,-1.22,-11.57,0c-2.63,0.85,-5.17,2.45,-7.24,4.33c-2.26,2.16,-3.95,4.8,-6.11,7.05 c-0.28,0.28,-0.56,0.56,-0.85,0.75c-0.56,0.28,-1.13,-0.09,-1.32,-0.66c-0.94,-3.95,1.69,-9.5,3.67,-12.89c2.26,-3.76,5.55,-6.77,9.78,-8 c2.07,-0.66,4.33,-0.66,6.49,-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
</group>
</vector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 15 KiB

@@ -20,34 +20,64 @@
<!-- Red beak right -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M110.28,61.32l2.63,8.84c0,0,7.24,-1.6,7.62,3.2c0.38,4.8,-6.77,8,-6.77,8l2.26,10.63 c0,0,7.9,-6.4,8,-15.61c0,0,0.66,-11.29,-6.11,-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
<!-- Red tail feathers -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M68.71,94.99c0,0,-11.1,-4.7,-16.46,1.98c-0.75,0.94,-1.41,1.88,-2.16,2.82 c-0.56,0.75,-1.13,1.5,-1.69,2.16c-0.47,0.56,-1.03,1.13,-1.69,1.5c-0.66,0.38,-1.32,0.66,-2.07,0.85c-0.94,0.19,-1.88,0.19,-2.82,0.09 c-1.32,-0.09,-2.63,-0.38,-3.95,-0.66c-0.47,-0.09,-0.85,-0.19,-1.22,-0.28c-0.09,0,-0.19,-0.09,-0.28,-0.09 s-0.19,-0.09,-0.28,-0.09c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98 c1.32,0.66,2.73,1.03,4.14,1.13c0.09,0,0.38,0,0.47,0.09c0.19,0.19,-0.28,0.47,-0.47,0.56c-0.28,0.19,-0.47,0.28,-0.75,0.38 c-0.85,0.38,-1.79,0.56,-2.63,0.75c-0.85,0.19,-1.69,0.28,-2.45,0.28c-0.47,0,-0.85,0.09,-1.22,0.09c-0.28,0,-0.56,-0.09,-0.85,0 s0.09,0.47,0.28,0.56c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38 c1.32,-0.19,2.63,-0.56,3.86,-1.03c6.77,-3.1,6.21,-9.59,12.42,-10.16c4.61,-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
<!-- Red beak left -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M19.79,38.28c0,0,-12.13,1.98,-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22,-9.41 c0,0,-13.07,-1.32,-12.32,-6.3c0.94,-6.21,11.85,-5.64,11.85,-5.64L19.79,38.28z"/>
<!-- Red wing detail -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#F45125"
android:pathData="M20.73,70.92c0,0,-1.88,0.56,-4.61,2.54c-1.88,1.32,-4.42,3.01,-6.87,5.93 c-1.22,1.41,-2.16,3.1,-2.82,4.89c-0.47,1.22,-0.66,2.45,-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66 c0.09,-0.09,0.19,-0.38,0.28,-0.47c0.19,-0.47,0.47,-0.85,0.75,-1.22c0.85,-1.13,1.88,-2.16,3.01,-3.01c0.38,-0.28,0.75,-0.47,1.13,-0.66 c0.28,-0.28,0.75,-0.66,0.94,-0.28c0.09,0.19,-0.09,0.47,-0.19,0.66c-0.09,0.28,-0.19,0.66,-0.19,0.94c-0.38,1.5,-0.56,3.01,-0.75,4.51 c-0.09,0.85,-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19 c0.09,-0.09,0.09,-0.19,0.19,-0.38c0.19,-0.28,0.28,-0.66,0.47,-0.94c0.47,-0.85,0.94,-1.69,1.5,-2.63c0.66,-1.13,1.41,-2.16,2.16,-3.1 c0.85,-1.13,1.88,-2.26,2.92,-3.2c1.13,-1.03,2.35,-2.07,3.67,-2.92c0.75,-0.47,1.6,-0.94,2.45,-1.32L20.73,70.92z"/>
<!-- Yellow body -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#FCC21B"
android:pathData="M116.4,79.29c-1.13,-5.55,-2.73,-11.01,-4.51,-16.46c-1.5,-4.61,-3.1,-9.31,-5.83,-13.36 c-1.22,-1.79,-3.01,-3.01,-5.27,-3.86c-4.33,-1.69,-9.97,-1.98,-13.73,-1.98c-5.64,0,-11.48,1.22,-16.74,3.67 c-1.88,5.64,-7.05,19.94,-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23 c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66 c2.54,-1.13,4.61,-2.92,6.3,-5.08c1.79,-2.26,3.2,-4.8,4.42,-7.43c1.88,-3.95,3.86,-8.37,4.14,-12.89 C117.99,87.38,117.24,83.24,116.4,79.29z"/>
<!-- Blue head -->
<path
android:fillColor="#FFFFFF"
android:fillColor="#429ADF"
android:pathData="M77.64,33.57c-0.28,-1.03,-1.03,-2.07,-1.6,-3.01c-6.3,-11.01,-20.04,-16.27,-32.26,-15.52 c-3.76,0.28,-9.31,0.85,-13.54,2.73c-2.07,0.94,-3.86,2.35,-4.99,4.14c-2.54,4.23,-3.76,8.94,-5.08,13.64 C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89,-1.41,10.25,-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32 c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94,-0.19,1.98,-0.28,2.92,-0.56 c1.88,-0.47,3.67,-1.13,5.46,-1.79c7.52,-3.01,13.64,-7.43,17.68,-14.58c1.69,-3.1,3.1,-6.4,4.42,-9.69c0.09,-0.19,0.19,-0.38,0.19,-0.56 c1.98,-5.46,3.29,-11.19,4.61,-16.84c0.66,-2.73,1.41,-5.55,1.79,-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
<!-- Dark eye band -->
<path
android:fillColor="#193D51"
android:pathData="M23.09,40.53c1.69,-3.1,5.74,-5.55,9.31,-5.08c0.56,0.09,1.22,0.19,1.79,0.47 c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75,-0.66,0.85,-1.22,0.38c-1.98,-1.69,-3.57,-3.01,-6.21,-3.67c-2.16,-0.56,-4.61,-0.28,-6.68,0.28 c-0.47,0.09,-1.22,0.56,-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
<!-- Dark mouth/chin -->
<path
android:fillColor="#193D51"
android:pathData="M62.21,64.9c-1.03,1.6,-2.45,3.01,-3.86,4.33c-0.38,0.28,-0.66,0.66,-1.03,0.94 c-5.64,4.7,-13.26,7.05,-20.51,5.27c-1.98,-0.47,-4.14,-1.5,-5.74,-2.73c-1.22,-0.94,-2.45,-2.16,-3.48,-3.39c-1.88,-2.26,-3.29,-4.89,-4.23,-7.62 c-0.47,-1.41,-0.75,-2.73,-0.94,-4.23c0,-0.47,-0.66,-5.46,0.85,-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03 c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09 c5.08,-0.28,10.25,-1.79,14.86,-3.76c0.38,-0.19,0.85,-0.47,1.32,-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
<!-- Dark eye detail -->
<path
android:fillColor="#193D51"
android:pathData="M67.58,51.16c0,0.47,-0.19,1.13,-0.75,1.03c-0.47,-0.09,-0.85,-0.94,-1.13,-1.22 c-1.32,-1.69,-3.86,-3.57,-6.4,-4.14c-3.01,-0.75,-5.27,0.56,-8.28,0.85c-0.85,0.09,-1.32,-0.28,-0.94,-1.03c1.6,-3.48,5.83,-6.21,10.25,-5.46 c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
<!-- Gold eye detail -->
<path
android:fillColor="#9B7515"
android:pathData="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41,-0.09,2.26,0.09,1.88,1.69 c-0.75,3.29,-3.86,5.17,-6.87,5.83c-0.75,0.19,-1.5,0.19,-2.26,0.19c-1.41,-0.09,-2.82,-0.66,-4.04,-1.5c-2.63,-1.79,-4.61,-4.89,-5.17,-8 C89.68,63.67,90.25,62.83,91.84,63.86z"/>
<!-- Gold mouth detail -->
<path
android:fillColor="#9B7515"
android:pathData="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51,-2.35,9.03,-5.93,11.38,-10.63 c0.85,-1.79,1.79,-1.41,2.45,0.28c1.13,3.1,1.03,6.87,-0.38,9.88c-0.66,1.41,-1.6,2.63,-2.82,3.57c-0.66,0.47,-1.32,0.75,-2.07,1.03 C71.43,83.33,67.58,83.24,65.22,80.79z"/>
<!-- Gold chin/jaw detail -->
<path
android:fillColor="#9B7515"
android:pathData="M110,96.41c-0.38,0,-0.94,-0.38,-1.41,-0.66c-0.47,-0.28,-0.94,-0.66,-1.22,-0.85 c-1.13,-0.56,-2.45,-1.13,-3.67,-1.5c-3.76,-1.22,-7.9,-1.22,-11.57,0c-2.63,0.85,-5.17,2.45,-7.24,4.33c-2.26,2.16,-3.95,4.8,-6.11,7.05 c-0.28,0.28,-0.56,0.56,-0.85,0.75c-0.56,0.28,-1.13,-0.09,-1.32,-0.66c-0.94,-3.95,1.69,-9.5,3.67,-12.89c2.26,-3.76,5.55,-6.77,9.78,-8 c2.07,-0.66,4.33,-0.66,6.49,-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
</group>
</vector>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 5.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.2 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

After

Width:  |  Height:  |  Size: 3.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.1 KiB

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.9 KiB

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.5 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 20 KiB

@@ -1,4 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="ic_launcher_background">#2b0037</color>
</resources>
</resources>
+1 -1
View File
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist"] },
{ ignores: ["dist", "android"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
+702 -735
View File
File diff suppressed because it is too large. Load diff
+6 -4
View File
@@ -3,7 +3,7 @@
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"homepage": "https://shakespeare.diy",
"license": "AGPL-3.0-or-later",
"version": "9.10.1",
"version": "9.16.4",
"type": "module",
"author": {
"name": "shakespeare.diy",
@@ -34,8 +34,8 @@
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.49.2",
"@nostrify/react": "^0.2.24",
"@nostrify/nostrify": "^0.54.1",
"@nostrify/react": "^0.6.6",
"@opensecret/react": "^1.5.4",
"@plausible-analytics/tracker": "^0.4.4",
"@radix-ui/react-accordion": "^1.2.0",
@@ -70,6 +70,8 @@
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"acorn": "^8.16.0",
"acorn-jsx": "^5.3.2",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
@@ -149,6 +151,6 @@
"typescript-eslint": "^8.0.1",
"vite": "^6.3.5",
"vite-plugin-pwa": "^1.1.0",
"vitest": "^3.1.4"
"vitest": "^4.1.8"
}
}
+155 -1
View File
@@ -1,9 +1,163 @@
# Changelog
## [9.16.4] - 2026-09-16
### Changed
- Published sites carry only the tags the nsite spec defines — the relay hints Shakespeare used to attach were read by nothing, and taking a site back no longer rewrites them
## [9.16.3] - 2026-09-14
### Added
- Take back your sites one at a time — every name waiting for you now has its own Publish, Show, and Delete buttons, so you can keep the few you want and clear out the rest
- Show opens a site by its Nostr address before you decide about it, so you can look at names that never loaded in a browser
### Changed
- Deleting a name only gives it up on shakespeare.wtf — anything published to Nostr stays yours
- Names that couldn't be taken back safely can now be cleared out, instead of only explaining why they were stuck
## [9.16.2] - 2026-09-13
### Changed
- Deploy settings now says how many of your names are waiting to be taken back, and stays quiet when there are none
### Fixed
- Names you published before shakespeare.wtf changed hands are recognized as yours as you type them — the Deploy screen offers to hand them back instead of reporting them taken by somebody else
## [9.16.1] - 2026-09-13
### Fixed
- Deploying to a name you already own works again — names you took back in the migration were reported as taken by somebody else, and the Deploy button refused to publish to your own site
## [9.16.0] - 2026-09-13
### Added
- Take back the sites you published before shakespeare.wtf changed hands — Deploy settings now lists every name that's waiting for you and hands them all back at once, republished under your own key
- Deploys report which relays accepted your site, and can fill in any that missed it without republishing
### Changed
- Deploying to Shakespeare now publishes your site to Nostr under your own key, so it stays readable by any Nostr site viewer with or without shakespeare.wtf
- Recovered sites are titled whatever they call themselves rather than after their web address
### Fixed
- Deploying to Shakespeare works again — it had been reporting success while changing nothing, because the host it uploaded to no longer serves those addresses
- New accounts start with Shakespeare set up as a deployment target instead of an empty screen
- Deployment provider settings now scroll, so Save is always reachable
## [9.15.0] - 2026-08-19
### Added
- Connect to Meridian as an AI provider — available as a one-click preset with streamlined setup
- Optimize Repository action in the project menu that consolidates git history to reclaim space and repair bloated repositories
### Fixed
- Zaps now verify the invoice amount before paying, so you're never charged more than you approved
## [9.14.0] - 2026-06-05
### Added
- Log in with a remote signer by scanning a QR code — connect your NIP-46 mobile signer to Shakespeare without copying and pasting bunker strings
### Changed
- Unified the login dialog into a single, streamlined experience across sign-in methods
### Fixed
- Custom fonts now load correctly in previews instead of triggering a runtime error
- Builds no longer fail when a project depends on types-only packages
- Resolved all known security vulnerabilities in dependencies
## [9.13.2] - 2026-04-29
### Changed
- Preview pane now uses the new iframe.diy sandboxing service for a faster, more reliable preview experience
## [9.13.1] - 2026-04-27
### Changed
- AI agents now run commands through a real POSIX-style shell with proper quoting, pipes, redirects, and glob expansion, making multi-step project edits more reliable
- Overhauled the built-in `git` commands used by AI agents, adding `ls-files`, `merge`, `mv`, `restore`, `rev-parse`, `revert`, `rm`, and `switch` alongside improvements across existing git operations
- Overhauled core shell commands (`cat`, `cp`, `find`, `grep`, `ls`, `sed`, `sort`, and more) for closer POSIX behavior and better ergonomics when AI agents work on your project
## [9.13.0] - 2026-04-26
### Added
- Build projects with Tailwind CSS v4, including `@import "tailwindcss"` entry files and third-party v4 plugins like `tw-animate-css`
## [9.12.0] - 2026-04-25
### Added
- Build support for module workers and static asset URLs — projects using `new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })`, `SharedWorker`, and `new URL('./logo.svg', import.meta.url)` now build and run correctly in the preview
- Preview pane grants microphone, ambient-light-sensor, and other device permissions so richer apps can run inside the preview
## [9.11.4] - 2026-04-17
### Fixed
- Preview pane no longer gets stuck on stale builds during rapid edits
### Changed
- Reduce AI costs for Anthropic models via OpenRouter by caching tool definitions across turns
## [9.11.3] - 2026-04-12
### Fixed
- App publish dialog now appears on mobile devices
- Changelog available offline via ServiceWorker precache
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
- Switch preview pane to iframe.diy for improved reliability and compatibility
- New users start with OpenCode Zen pre-configured for a zero-setup first experience
- Default nsite gateway changed to shakespeare.to with vanity subdomain support
- Update default Blossom servers and relay lists across deployments and uploads
### Fixed
- Default settings no longer override existing users' recently used models
- Showcase card clone URLs now use proper Nostr URI encoding
- Service worker no longer blocks SvelteKit nsite routes
## [9.11.0] - 2026-04-03
### Added
- Upload a banner image for your app directly from the App dialog
- T-tag editor in the App dialog Advanced section for tagging your app by category
- Delete App button in the App dialog Advanced section when editing an existing app
- Ngit repo and nsite deployment address fields in the App dialog Advanced section
- Auto-fill app name, description, and images from your project's OG tags and web manifest on first publish
### Changed
- Redesigned App dialog with an overlapping banner and avatar card layout
- Reorganized App dialog Advanced section into General, Handlers, and Tags tabs
- Showcase cards now show banner and icon images, and require both to appear in the showcase
- Validation summary above the Save button replaces per-field "Required" labels
- Updated showcase curator to the Shakespeare Builders community list
### Fixed
- Upgrade Nostrify to fix bunker connection issues
## [9.10.4] - 2026-04-02
### Fixed
- Fix Android splash screen showing logo masked to white silhouette instead of full color
## [9.10.3] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor splash screen and icon colors
## [9.10.2] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor icon instead of Shakespeare logo in app drawer
## [9.10.1] - 2026-04-02
### Fixed
- Fix Android app showing default Capacitor icon instead of Shakespeare logo in app drawer
- Replace default Capacitor vector drawable icons with Shakespeare logo
## [9.10.0] - 2026-04-02
+45 -18
View File
@@ -45,21 +45,18 @@ fi
BG_COLOR="#2b0037" # Shakespeare purple
TMPDIR=$(mktemp -d)
LOGO_WHITE_SVG="$TMPDIR/logo_white.svg"
LOGO_WHITE="$TMPDIR/logo_white.png"
LOGO_COLOR="$TMPDIR/logo_color.png"
# Recolor the SVG fills to white before rasterizing.
sed -E 's/fill:#[0-9A-Fa-f]{6}/fill:#ffffff/g' "$SOURCE_SVG" > "$LOGO_WHITE_SVG"
echo "Rendering white SVG at 512x512..."
# Render the original colorful SVG at high resolution for downscaling.
echo "Rendering colorful SVG at 512x512..."
if [ "$SVG_RENDERER" = "inkscape" ]; then
inkscape --export-type=png --export-filename="$LOGO_WHITE" -w 512 -h 512 "$LOGO_WHITE_SVG" 2>/dev/null
inkscape --export-type=png --export-filename="$LOGO_COLOR" -w 512 -h 512 "$SOURCE_SVG" 2>/dev/null
else
rsvg-convert -w 512 -h 512 "$LOGO_WHITE_SVG" -o "$LOGO_WHITE"
rsvg-convert -w 512 -h 512 "$SOURCE_SVG" -o "$LOGO_COLOR"
fi
# ── Adaptive icon foreground PNGs (transparent bg, white logo, safe-zone padding) ──
# ── Adaptive icon foreground PNGs (transparent bg, colorful logo, safe-zone padding) ──
# Content at 47% of canvas to fit within Android's adaptive icon safe zone.
echo "Generating adaptive foreground PNGs..."
@@ -69,7 +66,7 @@ make_foreground() {
local content_size=$(echo "$size * 47 / 100" | bc)
local dest=$2
$MAGICK -size "${size}x${size}" "xc:none" \
\( "$LOGO_WHITE" -resize "${content_size}x${content_size}" \) \
\( "$LOGO_COLOR" -resize "${content_size}x${content_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
@@ -82,8 +79,7 @@ make_foreground 192 android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_foregrou
# ── Legacy launcher icons (ic_launcher.png and ic_launcher_round.png) ──
# These are used on pre-API-26 devices and as fallback on some launchers.
# They must have the logo composited onto the purple background — NOT just
# a solid color fill.
# They must have the logo composited onto the purple background.
echo "Generating legacy launcher icons (ic_launcher.png and ic_launcher_round.png)..."
@@ -93,7 +89,7 @@ make_legacy_square() {
local content_size=$(echo "$size * 60 / 100" | bc)
local dest=$2
$MAGICK -size "${size}x${size}" "xc:${BG_COLOR}" \
\( "$LOGO_WHITE" -resize "${content_size}x${content_size}" \) \
\( "$LOGO_COLOR" -resize "${content_size}x${content_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
@@ -111,7 +107,7 @@ make_legacy_round() {
# Fill purple, apply circle mask, composite logo
$MAGICK -size "${size}x${size}" "xc:${BG_COLOR}" \
"$mask" -compose dst-in -composite \
\( "$LOGO_WHITE" -resize "${content_size}x${content_size}" \) \
\( "$LOGO_COLOR" -resize "${content_size}x${content_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
@@ -138,7 +134,37 @@ cat > "$BACKGROUND_COLOR_FILE" << 'EOF'
</resources>
EOF
# ── iOS App Icon (1024x1024, white logo on purple background) ──
# ── Splash screen PNGs (logo centered on purple background) ──
# These are the legacy splash screens used by the Capacitor splash screen plugin.
# Logo is sized to ~25% of the shorter dimension, centered on solid purple.
echo "Generating splash screen PNGs..."
make_splash() {
local w=$1
local h=$2
local dest=$3
local shorter=$(( w < h ? w : h ))
local logo_size=$(echo "$shorter * 25 / 100" | bc)
$MAGICK -size "${w}x${h}" "xc:${BG_COLOR}" \
\( "$LOGO_COLOR" -resize "${logo_size}x${logo_size}" \) \
-gravity center -compose over -composite \
"$dest"
}
make_splash 480 320 android/app/src/main/res/drawable/splash.png
make_splash 320 480 android/app/src/main/res/drawable-port-mdpi/splash.png
make_splash 480 800 android/app/src/main/res/drawable-port-hdpi/splash.png
make_splash 720 1280 android/app/src/main/res/drawable-port-xhdpi/splash.png
make_splash 960 1600 android/app/src/main/res/drawable-port-xxhdpi/splash.png
make_splash 1280 1920 android/app/src/main/res/drawable-port-xxxhdpi/splash.png
make_splash 480 320 android/app/src/main/res/drawable-land-mdpi/splash.png
make_splash 800 480 android/app/src/main/res/drawable-land-hdpi/splash.png
make_splash 1280 720 android/app/src/main/res/drawable-land-xhdpi/splash.png
make_splash 1600 960 android/app/src/main/res/drawable-land-xxhdpi/splash.png
make_splash 1920 1280 android/app/src/main/res/drawable-land-xxxhdpi/splash.png
# ── iOS App Icon (1024x1024, colorful logo on purple background) ──
echo "Generating iOS app icon..."
@@ -146,9 +172,9 @@ IOS_ICON_DIR="ios/App/App/Assets.xcassets/AppIcon.appiconset"
if [ -d "$IOS_ICON_DIR" ]; then
IOS_ICON="$IOS_ICON_DIR/[email protected]"
# Logo at ~60% of canvas, centered on purple background (matches legacy Android style)
# Logo at ~60% of canvas, centered on purple background
$MAGICK -size "1024x1024" "xc:${BG_COLOR}" \
\( "$LOGO_WHITE" -resize "614x614" \) \
\( "$LOGO_COLOR" -resize "614x614" \) \
-gravity center -compose over -composite \
"$IOS_ICON"
echo -e " ${GREEN}✓${NC} $IOS_ICON"
@@ -160,11 +186,12 @@ fi
rm -rf "$TMPDIR"
echo -e "\n${GREEN}App icons generated successfully!${NC}"
echo -e "Icon: white Shakespeare logo on ${GREEN}${BG_COLOR}${NC} (Shakespeare purple)"
echo -e "Icon: colorful Shakespeare logo on ${GREEN}${BG_COLOR}${NC} (Shakespeare purple)"
echo -e "Generated:"
echo -e " Android:"
echo -e " - ic_launcher_foreground.png (adaptive, all densities)"
echo -e " - ic_launcher.png (legacy square, all densities)"
echo -e " - ic_launcher_round.png (legacy round, all densities)"
echo -e " - splash.png (portrait + landscape, all densities)"
echo -e " iOS:"
echo -e " - [email protected] (1024x1024)"
+7 -1
View File
@@ -1,3 +1,9 @@
# Shakespeare Services
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
## Preview Iframe Service
Shakespeare uses [iframe.diy](https://iframe.diy/) to sandbox project previews on an isolated origin, protecting the main app's `localStorage` and `IndexedDB` from untrusted preview code. The default `previewDomain` in the app config is `iframe.diy`.
To self-host the iframe preview service, deploy [soapbox-pub/iframe.diy](https://gitlab.com/soapbox-pub/iframe.diy) on your own domain and set `previewDomain` accordingly.
@@ -1,394 +0,0 @@
# iframe Fetch Client Messaging Protocol (JSON-RPC)
This document describes the simplified JSON-RPC based communication protocol
between the parent page and the iframe fetch client.
## Overview
The iframe fetch client uses JSON-RPC 2.0 over `postMessage` for communication.
The ServiceWorker makes JSON-RPC calls directly, with the main thread acting as
a relay between the ServiceWorker and parent page. The only required method is
`fetch` for handling HTTP requests.
## Architecture
```
┌─────────────────┐ JSON-RPC over ┌──────────────────────┐
│ Parent Page │ postMessage │ Main Thread │
│ │ ←─────────────────→ │ (relay only) │
│ - Request │ │ │
│ handling │ │ ↕ │
└─────────────────┘ │ JSON-RPC over │
│ postMessage │
│ │
│ ┌──────────────────┐ │
│ │ ServiceWorker │ │
│ │ │ │
│ │ - Makes JSON-RPC │ │
│ │ calls directly │ │
│ │ - Handles │ │
│ │ requests │ │
│ └──────────────────┘ │
└──────────────────────┘
```
## JSON-RPC Structure
All messages follow JSON-RPC 2.0 specification:
```javascript
// GET Request
{
"jsonrpc": "2.0",
"method": "fetch",
"params": {
"request": {
"url": "https://app123.example.com/assets/main.js",
"method": "GET",
"headers": {
"Accept": "application/javascript"
},
"body": null
}
},
"id": 123
}
// POST Request with JSON body
{
"jsonrpc": "2.0",
"method": "fetch",
"params": {
"request": {
"url": "https://app123.example.com/api/data",
"method": "POST",
"headers": {
"Content-Type": "application/json"
},
"body": "eyJuYW1lIjoiSm9obiIsImFnZSI6MzB9" // base64 encoded: {"name":"John","age":30}
}
},
"id": 124
}
// Success Response
{
"jsonrpc": "2.0",
"result": {
"status": 200,
"statusText": "OK",
"headers": {
"Content-Type": "application/javascript",
"Cache-Control": "no-cache"
},
"body": "Y29uc29sZS5sb2coJ2hlbGxvJyk7" // base64 encoded: console.log('hello');
},
"id": 123
}
// Error Response (still uses JSON-RPC error format for protocol errors)
{
"jsonrpc": "2.0",
"error": {
"code": -32001,
"message": "Invalid request format",
"data": { "url": "/assets/main.js" }
},
"id": 123
}
```
## Methods
### `fetch`
**Purpose:** Handle HTTP requests, including GET, POST, PUT, DELETE, etc. with
full request body support
**Parameters:**
- `request` (object): Serialized fetch request
- `url` (string): Full URL of the request
- `method` (string): HTTP method (GET, POST, etc.)
- `headers` (object): Request headers as key-value pairs
- `body` (string|null): Request body as base64 encoded string, or null if no body
**Result:**
- `status` (number): HTTP status code (200, 404, etc.)
- `statusText` (string): HTTP status text ("OK", "Not Found", etc.)
- `headers` (object): Response headers as key-value pairs
- `body` (string|null): Response body content as base64 encoded string (null if status is 204)
**Error Codes:**
- `-32001`: Invalid request format
- `-32002`: Request processing error
- `-32003`: Invalid URL
**Request Body Support:** The system fully supports request bodies, enabling:
- POST/PUT requests with JSON data
- Form submissions
- API calls with payloads
- File uploads (as base64 strings)
- Any HTTP method with body content
Request bodies must be base64-encoded strings when not null. This ensures
consistent handling of both text and binary data across the messaging protocol.
### `console`
**Purpose:** Forward console messages from iframe to parent for display
**Parameters:**
- `level` (string): Log level - "log", "warn", "error", "info", "debug"
- `message` (string): The log message
**Result:** None (notification only, no response expected)
### Navigation Methods
#### `navigate`
**Purpose:** Navigate iframe to a new URL within the same origin
**Parameters:** `url` (string) - Target URL (must be same origin)
**Result:** None (notification only)
#### `refresh`
**Purpose:** Refresh/reload the current page in the iframe
**Parameters:** None
**Result:** None (notification only)
#### `updateNavigationState`
**Purpose:** Update parent about iframe's current navigation state
**Parameters:**
- `currentUrl` (string) - Current URL of the iframe
- `canGoBack` (boolean) - Whether iframe can go back in history
- `canGoForward` (boolean) - Whether iframe can go forward in history
**Result:** None (notification only)
## Implementation
### Parent Page
The parent page acts as a static file server and console log collector:
```javascript
class FetchClientParent {
constructor(files) {
this.files = files; // Map of path -> {content, contentType}
this.consoleLogs = []; // Store console messages
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
// Verify origin for security
if (event.origin !== "https://app123.example.com") return;
const message = event.data;
// Handle fetch requests
if (message.jsonrpc === "2.0" && message.method === "fetch") {
this.handleFetch(message);
}
// Handle console messages
if (message.jsonrpc === "2.0" && message.method === "console") {
this.handleConsoleMessage(message);
}
});
}
handleConsoleMessage(message) {
const { params } = message;
const { level, message: logMessage } = params;
// Store the log message
this.consoleLogs.push({
level,
message: logMessage,
timestamp: Date.now(),
id: Date.now()
});
// Update UI to show new logs
this.updateConsoleUI();
// Also log to parent's console for debugging
console[level](`[IFRAME] ${logMessage}`);
}
updateConsoleUI() {
// Implementation depends on your UI framework
console.log(`Total console logs: ${this.consoleLogs.length}`);
}
handleFetch(request) {
const { params, id } = request;
const { request: fetchRequest } = params;
// Extract path from URL
const url = new URL(fetchRequest.url);
const path = url.pathname;
const file = this.files.get(path);
if (file) {
this.sendResponse({
id,
jsonrpc: "2.0",
result: {
status: 200,
statusText: "OK",
headers: {
"Content-Type": file.contentType,
"Cache-Control": "no-cache",
},
body: btoa(file.content),
},
});
} else {
this.sendResponse({
id,
jsonrpc: "2.0",
result: {
status: 404,
statusText: "Not Found",
headers: {
"Content-Type": "text/plain",
},
body: btoa(`File not found: ${path}`),
},
});
}
}
sendResponse(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
}
```
### iframe Client Communication
The iframe client uses a simplified JSON-RPC client for communication. In the actual implementation, the ServiceWorker makes requests and the main thread acts as a relay:
```javascript
// Simplified JSON-RPC client (actual implementation in _iframe-client/main.js)
class JSONRPCClient {
constructor() {
this.requestId = 0;
this.pendingRequests = new Map();
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
const message = event.data;
if (message.jsonrpc === "2.0" && message.id !== undefined) {
this.handleResponse(message);
}
});
}
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request },
id,
}, "*");
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, 10000);
});
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
if (!pending) return;
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
pending.resolve(result);
}
}
}
```
## Base64 Encoding
All request and response bodies are base64 encoded when not null to ensure proper transmission through JSON-RPC:
- **Consistent Data Handling:** Both text and binary data are handled uniformly
- **JSON Compatibility:** Avoids issues with special characters in JSON messages
- **Binary Data Support:** Enables transmission of images, files, and other binary content
**Encoding/Decoding:**
```javascript
// Encoding text content (parent side)
const encodedBody = btoa(textContent);
// Encoding binary content (ServiceWorker side)
const bytes = new Uint8Array(arrayBuffer);
const encodedBody = btoa(String.fromCharCode(...bytes));
// Decoding (receiver side)
const decodedText = atob(encodedBody);
const decodedBytes = new Uint8Array(atob(encodedBody).split('').map(c => c.charCodeAt(0)));
```
## Security
- **Origin Validation:** Always verify message origin
- **Path Validation:** Validate file paths to prevent directory traversal
- **Timeout:** Requests timeout after 10 seconds
- **Error Handling:** Proper JSON-RPC error responses
## Example Usage
```html
<iframe
id="preview-iframe"
src="https://app123.example.com"
sandbox="allow-scripts allow-same-origin"
>
</iframe>
<script>
const files = new Map([
["/", {
content: "<!DOCTYPE html><html><body>Hello world!</body></html>",
contentType: "text/html",
}],
["/app.js", {
content: "console.log('App loaded');",
contentType: "application/javascript",
}],
]);
// Initialize the fetch client parent
new FetchClientParent(files);
</script>
```
## Console Logging Implementation
The iframe client automatically intercepts console messages and forwards them to the parent. The implementation (in `_iframe-client/main.js`) overrides console methods.
-365
View File
@@ -1,365 +0,0 @@
# iframe Fetch Client
An iframe preview system for **Single Page Applications (SPAs)**.
## Why?
We want to display a preview of a project built with Vite, Webpack, etc in an
iframe, but the SPA uses root-relative paths (like `/assets/main.js`). This
means we can't just load it directly from a file system or a local server
without deploying it to a web server.
To work around this, we can instead deploy this "iframe Fetch Client" to a
subdomain, embed it in an iframe, and then respond to its `postMessage` requests
from the parent to serve it the files it needs.
This "iframe Fetch Client" is entirely static files, and only needs to be
deployed once. As long as the parent page implements its JSON-RPC protocol, it
can serve any web application.
## Architecture
```
┌─────────────────┐ JSON-RPC over ┌──────────────────────┐
│ Parent Page │ postMessage │ iframe Client │
│ (example.com) │ ←─────────────────→ │ (*.example.com) │
│ │ fetch() │ │
│ - Request │ │ ┌──────────────────┐ │
│ handling │ │ │ Main Thread │ │
└─────────────────┘ │ │ (relay only) │ │
│ │ ↕ │ │
│ │ JSON-RPC over │ │
│ │ postMessage │ │
│ │ ↕ │ │
│ │ ┌──────────────┐ │ │
│ │ │ServiceWorker │ │ │
│ │ │ │ │ │
│ │ │- Makes │ │ │
│ │ │ JSON-RPC │ │ │
│ │ │ calls │ │ │
│ │ │- Handles │ │ │
│ │ │ requests │ │ │
│ │ └──────────────┘ │ │
│ └──────────────────┘ │
└──────────────────────┘
```
## Limitations
This system uses a ServiceWorker to serve requests, which means the preview site
cannot itself register a ServiceWorker. If it tries, the attempt will be
blocked.
## Files Structure
```
/
├── index.html # Main iframe client page
├── _iframe-client/
│ ├── main.js # Main coordination script
│ └── client.css # Styles for the iframe client
├── sw.js # ServiceWorker
├── MESSAGING_PROTOCOL.md # Communication protocol docs
└── README.md # This file
```
## Simplified JSON-RPC Protocol
The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
- **`fetch(request)`** - Handle HTTP requests with serialized fetch
request/response
- **`console(level, message)`** - Forward console messages from
iframe to parent for display
**Request:**
```javascript
{
"jsonrpc": "2.0",
"method": "fetch",
"params": {
"request": {
"url": "https://app123.example.com/assets/main.js",
"method": "GET",
"headers": {},
"body": null
}
},
"id": 123
}
```
**Response:**
```javascript
{
"jsonrpc": "2.0",
"result": {
"status": 200,
"statusText": "OK",
"headers": {
"Content-Type": "application/javascript"
},
"body": "console.log('hello');"
},
"id": 123
}
```
**Console Message:**
```javascript
{
"jsonrpc": "2.0",
"method": "console",
"params": {
"level": "error",
"message": "Failed to load module"
}
}
```
## How It Works
1. **Initialization:**
- iframe client loads at `app123.example.com`
- Registers ServiceWorker at `/sw.js` with scope `/`
- Blocks future ServiceWorker registrations
- Main thread sets up relay between ServiceWorker and parent
2. **Request Handling:**
- ServiceWorker intercepts all requests (except iframe client system files)
- ServiceWorker makes JSON-RPC `fetch()` calls directly with serialized
requests
- Main thread relays JSON-RPC messages between ServiceWorker and parent
- Parent responds with serialized HTTP responses
- ServiceWorker creates Response objects and returns them to the client app
3. **SPA Routing Support:**
- ServiceWorker detects navigation requests (HTML page requests with `mode: "navigate"`)
- For SPA routes like `/about`, `/contact`, etc., the ServiceWorker serves the site's `index.html`
- This allows the SPA's client-side router to handle the route properly
- All other requests (assets, API calls, etc.) are handled normally via JSON-RPC
4. **Semantic Path Navigation:**
- **Key Concept**: iframe stays on base URL (`/`) while communicating semantic paths to parent
- When user navigates to `/about` in address bar, iframe doesn't actually change URL
- Instead, NavigationHandler tracks semantic path (`/about`) and communicates it to parent
- Parent displays semantic path while iframe remains on base URL
- SPA's client-side router handles navigation internally without page reloads
- This prevents 404 errors from literal path navigation
5. **SPA Navigation Tracking:**
- NavigationHandler overrides `history.pushState()` and `history.replaceState()` to detect SPA navigation
- When SPAs change URLs via history methods, NavigationHandler detects the change and sends navigation state to parent
- Navigation state includes semantic path, back/forward capability, and history tracking
- Parent can display current semantic path and enable proper back/forward navigation controls
6. **Content Replacement:**
- Main thread requests `/` from parent via JSON-RPC fetch
- Replaces its own content with the site index
- Site runs normally, with all requests handled by SW via JSON-RPC
## Deployment
### iframe Client Domain (`*.example.com`)
Deploy these files to your iframe client subdomain:
```
https://*.example.com/
├── index.html
├── _iframe-client/
│ ├── main.js
│ └── client.css
└── sw.js
```
**Security Note:** It is recommended to serve the client on a wildcard subdomain
(like `*.example.com`) if you wish to support multiple projects. That way
projects won't share the same localStorage and IndexedDB.
### Parent Page Integration
Include the iframe client in your parent page:
```html
<iframe
id="preview-iframe"
src="https://app123.example.com/"
sandbox="allow-scripts allow-same-origin"
>
</iframe>
```
Implement the JSON-RPC protocol:
```javascript
class FetchClientParent {
constructor(files) {
this.files = files; // Map of path -> {content, contentType}
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
if (event.origin !== "https://example.com") return;
const message = event.data;
if (message.jsonrpc === "2.0" && message.method === "fetch") {
this.handleFetch(message);
}
});
}
handleFetch(request) {
const { params, id } = request;
const { request: fetchRequest } = params;
// Extract path from URL
const url = new URL(fetchRequest.url);
const path = url.pathname;
const file = this.files.get(path);
if (file) {
this.sendResponse({
id,
jsonrpc: "2.0",
result: {
status: 200,
statusText: "OK",
headers: {
"Content-Type": file.contentType,
"Cache-Control": "no-cache",
},
body: file.content,
},
});
} else {
// Return 404 response
this.sendResponse({
id,
jsonrpc: "2.0",
result: {
status: 404,
statusText: "Not Found",
headers: {
"Content-Type": "text/plain",
},
body: `File not found: ${path}`,
},
});
}
}
sendResponse(message) {
const iframe = document.getElementById("preview-iframe");
iframe.contentWindow.postMessage(message, "https://app123.example.com");
}
}
```
## Request Handling
Handle requests by providing responses as a Map or object for static files, or
implement custom logic for dynamic requests:
```javascript
const staticFiles = new Map([
["/", {
content: "<!DOCTYPE html>...",
contentType: "text/html",
}],
["/assets/main.js", {
content: 'console.log("app");',
contentType: "application/javascript",
}],
["/assets/style.css", {
content: "body { margin: 0; }",
contentType: "text/css",
}],
]);
// Or handle dynamic requests like APIs
function handleRequest(fetchRequest) {
const url = new URL(fetchRequest.url);
if (url.pathname.startsWith("/api/")) {
// Handle API requests
return handleAPIRequest(fetchRequest);
} else {
// Serve static files
return serveStaticFile(url.pathname);
}
}
```
## Security Features
- **Origin Validation:** Messages are validated by origin
- **Sandboxed Iframe:** Client runs in a sandboxed environment
- **Isolated ServiceWorker:** SW only affects the iframe client domain
- **No Direct Access:** Parent controls all request handling
## Testing
1. Create a parent page implementing the JSON-RPC protocol (see example in MESSAGING_PROTOCOL.md)
2. Load the iframe client in an iframe pointing to your deployed client domain
3. The iframe client should load and display the served content
4. Test navigation and functionality within the iframe client
## Browser Support
- **ServiceWorker:** Required (supported in all modern browsers)
- **postMessage:** Required (universal support)
- **iframe sandbox:** Recommended (modern browsers)
## Limitations
- Request/response bodies must be JSON-serializable strings (no binary support)
- All requests go through the parent page (potential performance impact)
- Requires HTTPS for ServiceWorker (except localhost)
- Limited to same-origin communication patterns within the iframe
## Troubleshooting
### iframe client doesn't load
- Check browser console for ServiceWorker errors
- Verify HTTPS is used (required for ServiceWorker)
- Ensure parent page implements the messaging protocol
### Requests fail
- Check that request paths match your handling logic (case-sensitive)
- Verify parent page is responding to JSON-RPC `fetch` requests
- Check browser network tab for failed requests
### Communication issues
- Verify iframe src points to correct preview domain
- Check that JSON-RPC messages are properly formatted
- Ensure iframe has appropriate sandbox permissions
### SPA routes don't work
- Ensure the parent page serves the correct `index.html` for the root path `/`
- Check that the SPA's client-side router is properly configured
- Verify that navigation requests are being detected correctly by the ServiceWorker
- Make sure the parent page returns the same `index.html` content for SPA routes as it does for the root path
- **Important**: iframe should stay on base URL (`/`) while semantic paths are communicated to parent. If you see literal path navigation (iframe URL changing to `/about`), this indicates a configuration issue.
## Development
To modify the system:
1. **iframe Client:** Edit `index.html`, `_iframe-client/main.js`,
`_iframe-client/client.css`, `sw.js`
2. **Protocol:** Update `MESSAGING_PROTOCOL.md` for any changes
3. **Testing:** Create a parent page implementing the JSON-RPC protocol for testing changes
## License
This system is designed for development and testing purposes. Ensure appropriate
security measures for production use.
@@ -1,39 +0,0 @@
body {
margin: 0;
padding: 20px;
font-family: system-ui, -apple-system, sans-serif;
background: #f5f5f5;
}
.loading {
text-align: center;
padding: 50px;
}
.spinner {
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
width: 40px;
height: 40px;
animation: spin 2s linear infinite;
margin: 0 auto 20px;
}
@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}
.error {
color: #e74c3c;
background: #fdf2f2;
border: 1px solid #fecaca;
border-radius: 4px;
padding: 15px;
margin: 20px 0;
}
@@ -1,562 +0,0 @@
/**
* iframe Fetch Client - Simplified Implementation
* Implements JSON-RPC 2.0 messaging protocol per MESSAGING_PROTOCOL.md
*/
// JSON-RPC Client for communication with parent
class JSONRPCClient {
constructor() {
this.requestId = 0;
this.pendingRequests = new Map();
this.setupMessageListener();
}
setupMessageListener() {
window.addEventListener("message", (event) => {
// Only accept messages from parent window for security
if (event.source !== window.parent) {
return;
}
const message = event.data;
// Check if this is a response to our own request or a ServiceWorker request
if (message.jsonrpc === "2.0" && message.id !== undefined) {
if (this.pendingRequests.has(message.id)) {
this.handleResponse(message);
} else {
// This is a response to a ServiceWorker request, relay it back
this.relayToServiceWorker(message);
}
}
});
}
relayToServiceWorker(response) {
// Forward the JSON-RPC response to ServiceWorker
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage(response);
}
}
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
this.pendingRequests.set(id, { resolve, reject });
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request },
id,
}, "*");
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, 10000);
});
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
if (!pending) return;
this.pendingRequests.delete(id);
if (error) {
pending.reject(new Error(`${error.message} (code: ${error.code})`));
} else {
pending.resolve(result);
}
}
}
// Console Interceptor - forwards console messages to parent
class ConsoleInterceptor {
constructor() {
this.originalConsole = {};
this.methods = ['log', 'warn', 'error', 'info', 'debug'];
this.init();
}
init() {
// Store original methods and override in single pass
this.methods.forEach((method) => {
if (typeof console[method] === 'function') {
this.originalConsole[method] = console[method];
console[method] = (...args) => {
// Call original method
try {
this.originalConsole[method](...args);
} catch (e) {
// Continue if original fails
}
// Send to parent
this.sendConsoleMessage(method, ...args);
};
}
});
}
sendConsoleMessage(level, ...args) {
const message = args.map((arg) => {
if (arg === undefined) return 'undefined';
if (arg === null) return 'null';
if (typeof arg === 'object') {
try {
return JSON.stringify(arg, (key, value) => {
if (value instanceof Error) {
return {
name: value.name,
message: value.message,
stack: value.stack
};
}
return value;
});
} catch {
return String(arg);
}
}
return String(arg);
}).join(' ');
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level, message }
}, "*");
} catch (error) {
// Retry once after delay if postMessage fails
setTimeout(() => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: { level: "error", message: `[DELAYED] ${message}` }
}, "*");
} catch {
// Give up if retry fails
}
}, 100);
}
}
}
// Navigation Handler - manages iframe navigation and history
class NavigationHandler {
constructor() {
// Get initial path from window property or default to root
this.currentSemanticPath = window.__IFRAME_INITIAL_PATH__ || '/';
this.setupMessageListener();
this.setupHistoryListeners();
this.overrideHistoryMethods();
this.updateNavigationState();
}
// Extract semantic path from URL or string
extractSemanticPath(urlOrString) {
try {
const url = typeof urlOrString === 'string'
? new URL(urlOrString, window.location.origin)
: urlOrString;
return url.pathname + url.search + url.hash;
} catch {
return window.location.pathname + window.location.search + window.location.hash;
}
}
setupMessageListener() {
window.addEventListener("message", (event) => {
// Only accept messages from parent window for security
if (event.source !== window.parent) {
return;
}
const message = event.data;
if (message.jsonrpc === "2.0") {
switch (message.method) {
case "navigate":
this.handleNavigate(message.params.url);
break;
case "refresh":
this.handleRefresh();
break;
}
}
});
}
setupHistoryListeners() {
// Listen for popstate events (back/forward navigation)
window.addEventListener('popstate', () => {
this.currentSemanticPath = this.extractSemanticPath(window.location);
this.updateNavigationState();
});
// Listen for hash changes
window.addEventListener('hashchange', () => {
this.currentSemanticPath = this.extractSemanticPath(window.location);
this.updateNavigationState();
});
}
overrideHistoryMethods() {
// Override history.pushState and history.replaceState to detect SPA navigation
this.originalPushState = window.history.pushState;
this.originalReplaceState = window.history.replaceState;
window.history.pushState = (...args) => {
const result = this.originalPushState.apply(window.history, args);
// Extract semantic path from URL argument or use current location
const semanticPath = args[2]
? this.extractSemanticPath(args[2])
: this.extractSemanticPath(window.location);
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
return result;
};
window.history.replaceState = (...args) => {
const result = this.originalReplaceState.apply(window.history, args);
const semanticPath = args[2]
? this.extractSemanticPath(args[2])
: this.extractSemanticPath(window.location);
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
return result;
};
}
handleNavigate(url) {
try {
// Validate URL - must be same origin
const targetUrl = new URL(url, window.location.origin);
if (targetUrl.origin !== window.location.origin) {
console.error('Navigation to different origin not allowed:', url);
return;
}
const semanticPath = this.extractSemanticPath(targetUrl);
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
// Trigger SPA navigation
window.history.pushState({}, '', semanticPath);
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
} catch (error) {
console.error('Invalid navigation URL:', url, error);
}
}
handleRefresh() {
// Store current semantic path for reload
const currentPath = this.currentSemanticPath || '/';
// Save the current path to sessionStorage so it persists across reload
try {
sessionStorage.setItem('iframe_initial_path', currentPath);
} catch (error) {
console.warn('Failed to store initial path in sessionStorage:', error);
}
// Actually reload the iframe to get a fresh SPA instance
window.location.reload();
}
updateNavigationState() {
// Use tracked semantic path, fallback to current location if needed
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
const state = {
currentUrl: semanticPath,
canGoBack: false, // Let parent handle history tracking
canGoForward: false // Let parent handle history tracking
};
// Send navigation state to parent
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "updateNavigationState",
params: state
}, "*");
} catch (error) {
console.error('Failed to send navigation state:', error);
}
}
}
// Main Fetch Client
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.consoleInterceptor = new ConsoleInterceptor();
this.navigationHandler = new NavigationHandler();
this.init();
}
// Ensure SPA navigates to initial path after document is loaded
ensureInitialNavigation() {
// Wait for the SPA to initialize, then navigate to the initial path
setTimeout(() => {
const initialPath = window.__IFRAME_INITIAL_PATH__;
if (initialPath && initialPath !== '/') {
const currentPath = window.location.pathname + window.location.search + window.location.hash;
// If we're not already at the initial path, navigate there
if (currentPath !== initialPath) {
this.navigationHandler.handleNavigate(initialPath);
}
}
}, 150); // Give SPA more time to initialize
}
async init() {
try {
await this.setupServiceWorker();
await this.loadSiteIndex();
} catch (error) {
console.error("FetchClient: Initialization failed:", error);
this.showError("Failed to initialize fetch client", error);
}
}
async setupServiceWorker() {
if (!("serviceWorker" in navigator)) {
throw new Error("ServiceWorker not supported");
}
// Check if already registered
const existing = await navigator.serviceWorker.getRegistration();
if (existing) {
console.log("ServiceWorker already registered");
this.setupServiceWorkerCommunication();
return;
}
// Register new ServiceWorker
const registration = await navigator.serviceWorker.register("/sw.js", { scope: "/" });
console.log("ServiceWorker registered:", registration);
await navigator.serviceWorker.ready;
this.setupServiceWorkerCommunication();
this.blockFutureRegistrations(); // Block future registrations to prevent site from registering its own SW
}
setupServiceWorkerCommunication() {
// Relay JSON-RPC requests from ServiceWorker to parent
navigator.serviceWorker.addEventListener("message", (event) => {
const { data } = event;
if (data.jsonrpc === "2.0" && data.method && data.id !== undefined) {
window.parent.postMessage(data, "*");
}
});
}
blockFutureRegistrations() {
navigator.serviceWorker.register = () => {
console.log("Blocked ServiceWorker registration attempt");
return Promise.resolve({
scope: "/",
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => {},
removeEventListener: () => {},
});
};
}
async loadSiteIndex() {
// Check if we have a stored initial path from a refresh
let initialPath = '/';
try {
const storedPath = sessionStorage.getItem('iframe_initial_path');
if (storedPath) {
initialPath = storedPath;
// Clear the stored path after using it
sessionStorage.removeItem('iframe_initial_path');
}
} catch (error) {
console.warn('loadSiteIndex: Failed to read initial path from sessionStorage:', error);
}
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
body: null,
headers: {},
};
const response = await this.rpcClient.fetch(serializedRequest);
if (response?.status !== 200) {
throw new Error(`Failed to fetch site index: ${response?.status || 'Invalid response from site: ' + response} ${response?.statusText || ''}`);
}
if (response.headers["Content-Type"] !== "text/html") {
throw new Error(`Unexpected Content-Type: ${response.headers["Content-Type"]}`);
}
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
const text = new TextDecoder().decode(bytes);
// Set the initial path on window before replacing the document
// This will be available to the NavigationHandler when it initializes
if (initialPath && initialPath !== '/') {
window.__IFRAME_INITIAL_PATH__ = initialPath;
}
this.replaceDocument(text);
}
replaceDocument(htmlContent) {
console.log("replaceDocument: Starting...");
// Restore the initial path from sessionStorage before replacing document
let initialPath = '/';
try {
const storedPath = sessionStorage.getItem('spa_initial_path');
if (storedPath) {
initialPath = storedPath;
sessionStorage.removeItem('spa_initial_path');
console.log('replaceDocument: Restored initial path:', initialPath);
// Set it on window for the new document
window.__IFRAME_INITIAL_PATH__ = initialPath;
}
} catch (error) {
console.warn('replaceDocument: Failed to restore initial path:', error);
}
// Create a new document from the HTML content
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlContent, "text/html");
// Extract scripts for re-execution
const scripts = [];
newDoc.querySelectorAll("script").forEach((script) => {
scripts.push({
src: script.src,
type: script.type,
async: script.hasAttribute("async"),
defer: script.hasAttribute("defer"),
});
script.remove();
});
// Replace document content
document.head.innerHTML = newDoc.head.innerHTML;
document.body.innerHTML = newDoc.body.innerHTML;
// Re-add scripts to execute them
scripts.forEach((script) => {
const newScript = document.createElement("script");
newScript.src = script.src;
newScript.type = script.type;
if (script.async) newScript.async = true;
if (script.defer) newScript.defer = true;
document.body.appendChild(newScript);
});
// Ensure initial navigation after document is loaded
this.ensureInitialNavigation();
}
showError(message, error) {
console.error(message, error);
document.body.innerHTML = `
<div style="
font-family: system-ui, -apple-system, sans-serif;
max-width: 600px;
margin: 50px auto;
padding: 20px;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid #dc3545;
">
<h2 style="color: #dc3545; margin-top: 0;">Fetch Client Error</h2>
<p><strong>${message}</strong></p>
<p style="color: #6c757d;">${error.message || error}</p>
<details style="margin-top: 20px;">
<summary style="cursor: pointer; color: #007bff;">Technical Details</summary>
<pre style="
background: #f1f3f4;
padding: 10px;
border-radius: 4px;
overflow-x: auto;
font-size: 12px;
margin-top: 10px;
">${error.stack || JSON.stringify(error, null, 2)}</pre>
</details>
</div>
`;
}
}
// Global error handlers
const setupGlobalErrorHandlers = () => {
window.addEventListener('error', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: `Uncaught Error: ${event.message}`,
source: event.filename,
lineno: event.lineno,
colno: event.colno,
stack: event.error?.stack
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
window.addEventListener('unhandledrejection', (event) => {
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "console",
params: {
level: "error",
message: "Unhandled Promise Rejection",
reason: event.reason,
promise: event.promise ? 'Promise object' : 'No promise object'
}
}, "*");
} catch {
// Ignore postMessage errors
}
});
};
// Initialize
setupGlobalErrorHandlers();
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
new FetchClient();
}
-17
View File
@@ -1,17 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Site Preview</title>
<link rel="stylesheet" href="/_iframe-client/client.css">
</head>
<body>
<div class="loading">
<div class="spinner"></div>
<p>Loading preview...</p>
<p><small>Waiting for ServiceWorker and parent communication</small></p>
</div>
<script type="module" src="/_iframe-client/main.js"></script>
</body>
</html>
-205
View File
@@ -1,205 +0,0 @@
/**
* iframe Fetch Client ServiceWorker
* Intercepts requests and handles them via JSON-RPC communication
*/
let pendingRequests = new Map();
let requestIdCounter = 0;
// Install event
self.addEventListener("install", (event) => {
console.log("ServiceWorker installing");
self.skipWaiting();
});
// Activate event
self.addEventListener("activate", (event) => {
console.log("ServiceWorker activating");
event.waitUntil(self.clients.claim());
});
// Message handling from main thread (JSON-RPC responses)
self.addEventListener("message", (event) => {
handleMainThreadMessage(event.data);
});
function handleMainThreadMessage(data) {
// Handle JSON-RPC responses relayed from main thread
if (data.jsonrpc === "2.0" && data.id !== undefined) {
handleJSONRPCResponse(data);
}
}
function handleJSONRPCResponse(message) {
const { id, result, error } = message;
const pendingRequest = pendingRequests.get(id);
if (!pendingRequest) {
console.warn("No pending request found for ID:", id);
return;
}
pendingRequests.delete(id);
if (error) {
pendingRequest.reject(new Error(`${error.message} (code: ${error.code})`));
return;
}
// Create response from serialized response
const { status, statusText, headers, body } = result;
// Decode base64 body if present
let decoded = null;
if (typeof body === "string") {
decoded = new Uint8Array(atob(body).split('').map(c => c.charCodeAt(0)));
}
const response = new Response(decoded, {
status: status || 200,
statusText: statusText || "OK",
headers: headers || {},
});
pendingRequest.resolve(response);
}
async function requestViaJSONRPC(request) {
return new Promise(async (resolve, reject) => {
const id = ++requestIdCounter;
// Check if request is a plain object or Request object
let url, method, headers, body;
if (request instanceof Request) {
// Handle Request object
url = request.url;
method = request.method;
headers = Object.fromEntries(request.headers.entries());
if (request.body) {
try {
// Convert body to Uint8Array then base64 encode
const bytes = await request.bytes();
body = btoa(String.fromCharCode(...bytes));
} catch (error) {
reject(new Error(`Failed to serialize request body: ${error.message}`));
return;
}
}
} else {
// Handle plain request object
url = request.url;
method = request.method || 'GET';
headers = request.headers || {};
body = request.body || null;
}
const serializedRequest = {
url: url,
method: method,
headers: headers,
body: body,
};
pendingRequests.set(id, { resolve, reject, originalRequest: request });
// Send JSON-RPC request to main thread for relay to parent
self.clients.matchAll().then((clients) => {
if (clients.length > 0) {
clients[0].postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request: serializedRequest },
id,
});
} else {
pendingRequests.delete(id);
reject(new Error("No clients available"));
}
});
// Timeout after 10 seconds
setTimeout(() => {
if (pendingRequests.has(id)) {
pendingRequests.delete(id);
reject(new Error(`Timeout requesting: ${url}`));
}
}, 10000);
});
}
// Fetch event - intercept all requests
self.addEventListener("fetch", (event) => {
const url = new URL(event.request.url);
// Ignore requests to other origins
if (url.origin !== location.origin) {
return;
}
// Let iframe client system files be handled normally
if (url.pathname.startsWith("/_") || url.pathname === "/sw.js") {
return;
}
// Let root path be handled normally (loads the iframe client page)
if (url.pathname === "/") {
return;
}
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
if (url.pathname.startsWith("/_iframe-client/") ||
url.pathname === "/favicon.ico" ||
url.pathname === "/manifest.webmanifest") {
return;
}
// For SPA routes, check if this is a navigation request (HTML page request)
// But first check if we need to load the iframe client (this happens during refresh)
if (event.request.mode === "navigate" &&
(event.request.headers.get("accept") || "").includes("text/html")) {
// Check if this is a request for the iframe client itself
// We need to serve the iframe client HTML first, which will then load the SPA
if (url.pathname !== "/") {
// Redirect to root to load the iframe client, which will then navigate to the target path
const response = Response.redirect(new URL("/", event.request.url).href, 302);
event.respondWith(response);
return;
}
// This is a request for the root path, serve the site's index.html via JSON-RPC
const rootRequest = {
url: new URL("/", event.request.url).href,
method: event.request.method,
headers: Object.fromEntries(event.request.headers.entries()),
body: event.request.body
};
event.respondWith(handleRequest(rootRequest));
return;
}
// Handle all other requests through JSON-RPC communication
event.respondWith(handleRequest(event.request));
});
async function handleRequest(request) {
try {
console.log("ServiceWorker handling request for:", request.url);
return await requestViaJSONRPC(request);
} catch (error) {
console.error("Failed to handle request:", request.url, error);
// Return 404 for failed requests
return new Response(`Request failed: ${request.url}`, {
status: 404,
statusText: "Not Found",
headers: {
"Content-Type": "text/plain",
},
});
}
}
console.log("ServiceWorker script loaded");
+3 -2
View File
@@ -63,6 +63,7 @@ const defaultConfig: AppConfig = {
relays: [
{ url: 'wss://git.shakespeare.diy/' },
{ url: 'wss://relay.ngit.dev/' },
{ url: 'wss://git.nostrhub.io/' },
],
updatedAt: 0,
},
@@ -78,9 +79,9 @@ const defaultConfig: AppConfig = {
gitProxyOrigins: ["https://github.com", "https://gitlab.com"],
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
ngitWebUrl: "https://nostrhub.io/{naddr}",
previewDomain: "local-shakespeare.dev",
previewDomain: "iframe.diy",
showcaseEnabled: true,
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
showcaseCurator: "naddr1qvzqqqr4xqpzq7q6z5ns2hm5c8msyv83qwzxpxe52j8c4d4q5m92wsp9sflelkh9qqjrvdrxxajnqvny95mkyc33956xvwfk94sn2vek94sn2et9ve3kycfexfnryvty32j",
fsPathProjects: "/projects",
fsPathConfig: "/config",
fsPathTmp: "/tmp",
+2
View File
@@ -21,6 +21,7 @@ import GitHubOAuth from "./pages/GitHubOAuth";
import NetlifyOAuth from "./pages/NetlifyOAuth";
import VercelOAuth from "./pages/VercelOAuth";
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
import RemoteLoginSuccess from "./pages/RemoteLoginSuccess";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
@@ -43,6 +44,7 @@ export function AppRouter() {
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
<Route path="/remoteloginsuccess" element={<RemoteLoginSuccess />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
+19 -21
View File
@@ -156,7 +156,7 @@ export function AddAIProviderDialog({
value={apiKey}
onChange={(e) => setApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && apiKey.trim() && termsAgreed) {
if (e.key === 'Enter' && apiKey.trim() && (termsAgreed || !preset.tosURL)) {
handleAdd();
}
}}
@@ -165,20 +165,20 @@ export function AddAIProviderDialog({
/>
)}
{/* Terms of Service Agreement */}
<div className="flex items-center gap-1.5">
<Checkbox
id="agree-terms"
checked={termsAgreed}
onCheckedChange={(checked) => setTermsAgreed(checked === true)}
className="size-3 [&_svg]:size-3"
/>
<label
htmlFor="agree-terms"
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
{preset.tosURL ? (
{/* Terms of Service Agreement (skipped for providers without terms, e.g. local services) */}
{preset.tosURL && (
<div className="flex items-center gap-1.5">
<Checkbox
id="agree-terms"
checked={termsAgreed}
onCheckedChange={(checked) => setTermsAgreed(checked === true)}
className="size-3 [&_svg]:size-3"
/>
<label
htmlFor="agree-terms"
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
<a
href={preset.tosURL}
target="_blank"
@@ -188,11 +188,9 @@ export function AddAIProviderDialog({
>
{t('termsOfService')}
</a>
) : (
t('termsOfService')
)}
</label>
</div>
</label>
</div>
)}
</div>
)}
</div>
@@ -205,7 +203,7 @@ export function AddAIProviderDialog({
<Button
onClick={handleAdd}
disabled={
!termsAgreed ||
(!!preset.tosURL && !termsAgreed) ||
(!!preset.apiKeysURL && !apiKey.trim())
}
>
+73 -27
View File
@@ -23,7 +23,7 @@ import {
SelectValue,
} from '@/components/ui/select';
import type {
ShakespeareDeployProvider,
NpanelProvider,
NetlifyProvider,
VercelProvider,
NsiteProvider,
@@ -34,7 +34,7 @@ import type {
// Type for provider without the 'id' field (will be generated)
type DeployProviderInput =
| Omit<ShakespeareDeployProvider, 'id'>
| Omit<NpanelProvider, 'id'>
| Omit<NetlifyProvider, 'id'>
| Omit<VercelProvider, 'id'>
| Omit<NsiteProvider, 'id'>
@@ -54,14 +54,14 @@ export function AddCustomProviderDialog({
onAdd,
}: AddCustomProviderDialogProps) {
const { t } = useTranslation();
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
const [customProviderType, setCustomProviderType] = useState<'npanel' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
const [customName, setCustomName] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAccountId, setCustomAccountId] = useState('');
const [customOrganizationId, setCustomOrganizationId] = useState('');
const [customBaseURL, setCustomBaseURL] = useState('');
const [customBaseDomain, setCustomBaseDomain] = useState('');
const [customHost, setCustomHost] = useState('');
const [customDashboardHost, setCustomDashboardHost] = useState('');
const [customProxy, setCustomProxy] = useState(false);
const [customGateway, setCustomGateway] = useState('');
const [customRelayUrls, setCustomRelayUrls] = useState<string[]>([]);
@@ -73,20 +73,23 @@ export function AddCustomProviderDialog({
// Build provider object based on type
let provider: DeployProviderInput;
if (customProviderType === 'shakespeare') {
if (customProviderType === 'npanel') {
if (!customDashboardHost.trim() || !customGateway.trim()) return;
provider = {
type: 'shakespeare',
type: 'npanel',
name: customName.trim(),
...(customHost?.trim() && { host: customHost.trim() }),
...(customProxy && { proxy: true }),
dashboardHost: customDashboardHost.trim(),
domain: customGateway.trim(),
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/'],
};
} else if (customProviderType === 'nsite') {
provider = {
type: 'nsite',
name: customName.trim(),
gateway: customGateway.trim() || 'nsite.lol',
gateway: customGateway.trim() || 'shakespeare.to',
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/'],
};
} else if (customProviderType === 'netlify') {
if (!customApiKey.trim()) return;
@@ -151,7 +154,7 @@ export function AddCustomProviderDialog({
setCustomOrganizationId('');
setCustomBaseURL('');
setCustomBaseDomain('');
setCustomHost('');
setCustomDashboardHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls([]);
@@ -160,12 +163,22 @@ export function AddCustomProviderDialog({
onOpenChange(false);
};
const isValid = customProviderType && customName.trim() &&
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
(customApiKey.trim() &&
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
(customProviderType !== 'railway' || true)));
const hasRequiredFields = () => {
// A gateway is named by two hosts and reached with a Nostr key, so there is
// no API key to ask for — but it cannot be guessed at either.
if (customProviderType === 'npanel') {
return Boolean(customDashboardHost.trim() && customGateway.trim());
}
// Plain nsite needs nothing beyond a name: it has defaults for the rest.
if (customProviderType === 'nsite') return true;
if (!customApiKey.trim()) return false;
if (customProviderType === 'cloudflare') return Boolean(customAccountId.trim());
if (customProviderType === 'deno') return Boolean(customOrganizationId.trim());
return true;
};
const isValid = Boolean(customProviderType && customName.trim() && hasRequiredFields());
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -184,7 +197,7 @@ export function AddCustomProviderDialog({
</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
onValueChange={(value: 'npanel' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
setCustomProviderType(value);
// Reset form when provider type changes
setCustomApiKey('');
@@ -192,7 +205,7 @@ export function AddCustomProviderDialog({
setCustomOrganizationId('');
setCustomBaseURL('');
setCustomBaseDomain('');
setCustomHost('');
setCustomDashboardHost('');
setCustomProxy(false);
setCustomGateway('');
setCustomRelayUrls([]);
@@ -203,7 +216,7 @@ export function AddCustomProviderDialog({
<SelectValue placeholder={t('selectProviderType')} />
</SelectTrigger>
<SelectContent>
<SelectItem value="shakespeare">Shakespeare Deploy</SelectItem>
<SelectItem value="npanel">nsite gateway</SelectItem>
<SelectItem value="nsite">nsite</SelectItem>
<SelectItem value="netlify">Netlify</SelectItem>
<SelectItem value="vercel">Vercel</SelectItem>
@@ -228,20 +241,53 @@ export function AddCustomProviderDialog({
/>
</div>
{customProviderType === 'shakespeare' ? (
{customProviderType === 'npanel' ? (
<>
<p className="text-sm text-muted-foreground">
{t('shakespeareDeployNostrAuth')}
</p>
<div className="grid gap-2">
<Label htmlFor="custom-host">Host (Optional)</Label>
<Label htmlFor="custom-domain">
Domain <span className="text-destructive">*</span>
</Label>
<Input
id="custom-host"
id="custom-domain"
placeholder="shakespeare.wtf"
value={customHost}
onChange={(e) => setCustomHost(e.target.value)}
value={customGateway}
onChange={(e) => setCustomGateway(e.target.value)}
/>
<p className="text-xs text-muted-foreground">
Sites get a name under this domain.
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-dashboard-host">
Gateway API <span className="text-destructive">*</span>
</Label>
<Input
id="custom-dashboard-host"
placeholder="npanel.shakespeare.to"
value={customDashboardHost}
onChange={(e) => setCustomDashboardHost(e.target.value)}
/>
<p className="text-xs text-muted-foreground">
Where names are claimed. Usually a different host from the one above.
</p>
</div>
<UrlListEditor
label="Relay URLs"
items={customRelayUrls}
onChange={setCustomRelayUrls}
protocol="wss"
placeholder="relay.ditto.pub"
/>
<UrlListEditor
label="Blossom Servers"
items={customBlossomServers}
onChange={setCustomBlossomServers}
protocol="https"
placeholder="blossom.ditto.pub"
/>
</>
) : customProviderType === 'nsite' ? (
<>
@@ -252,7 +298,7 @@ export function AddCustomProviderDialog({
<Label htmlFor="custom-gateway">Gateway</Label>
<Input
id="custom-gateway"
placeholder="nsite.lol"
placeholder="shakespeare.to"
value={customGateway}
onChange={(e) => setCustomGateway(e.target.value)}
/>
@@ -269,7 +315,7 @@ export function AddCustomProviderDialog({
items={customBlossomServers}
onChange={setCustomBlossomServers}
protocol="https"
placeholder="blossom.primal.net"
placeholder="blossom.ditto.pub"
/>
</>
) : (
+532 -203
View File
@@ -13,6 +13,8 @@ import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
@@ -27,16 +29,15 @@ import { DotAI } from '@/lib/DotAI';
import { buildAppEvent } from '@/lib/appEvent';
import {
Loader2,
Save,
Plus,
X,
ExternalLink,
Pencil,
Upload,
ChevronDown,
CircleHelp,
} from 'lucide-react';
import type { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
interface AppDialogProps {
projectId: string;
@@ -48,10 +49,14 @@ interface AppFormData {
name: string;
about: string;
picture: string;
banner: string;
website: string;
dTag: string;
tTags: string[];
supportedKinds: string[];
webHandlers: Array<{ url: string; type: string }>;
ngitRepo: string;
nsiteDeployment: string;
}
/** Parse a kind 31990 event into form data */
@@ -75,14 +80,26 @@ function eventToFormData(event: NostrEvent): AppFormData {
.filter(([t]) => t === 'web')
.map(([, url, type]) => ({ url: url ?? '', type: type ?? '' }));
const tTags = event.tags
.filter(([t]) => t === 't')
.map(([, v]) => v)
.filter(Boolean);
const ngitATag = event.tags.find(([t, v]) => t === 'a' && v?.startsWith('30617:'))?.[1] ?? '';
const nsiteATag = event.tags.find(([t, v]) => t === 'a' && v?.startsWith('35128:'))?.[1] ?? '';
return {
name: metadata.name ?? '',
about: metadata.about ?? '',
picture: metadata.picture ?? '',
banner: metadata.banner ?? '',
website: metadata.website ?? '',
dTag,
tTags,
supportedKinds,
webHandlers,
ngitRepo: aTagToNaddr(ngitATag),
nsiteDeployment: aTagToNaddr(nsiteATag),
};
}
@@ -100,13 +117,120 @@ function emptyFormData(projectId: string): AppFormData {
name: toTitleCase(projectId),
about: '',
picture: '',
banner: '',
website: '',
dTag: projectId,
tTags: [],
supportedKinds: [],
webHandlers: [],
ngitRepo: '',
nsiteDeployment: '',
};
}
/** Convert a "kind:pubkey:identifier" a-tag value to an naddr string, or return '' on failure. */
function aTagToNaddr(aTag: string): string {
try {
const [kindStr, pubkey, ...rest] = aTag.split(':');
const kind = parseInt(kindStr);
const identifier = rest.join(':');
if (!kind || !pubkey || !identifier) return '';
return nip19.naddrEncode({ kind, pubkey, identifier });
} catch {
return '';
}
}
/** Convert an naddr string to a "kind:pubkey:identifier" a-tag value, or return '' on failure. */
function naddrToATag(naddr: string): string {
try {
const decoded = nip19.decode(naddr.trim());
if (decoded.type !== 'naddr') return '';
const { kind, pubkey, identifier } = decoded.data;
return `${kind}:${pubkey}:${identifier}`;
} catch {
return '';
}
}
/** Read a file from VFS as a UTF-8 string, returning null if it doesn't exist. */
async function readVfsText(fs: { readFile(path: string, options: { encoding: string }): Promise<string> }, path: string): Promise<string | null> {
try {
return await fs.readFile(path, { encoding: 'utf8' });
} catch {
return null;
}
}
/** Extract OG/meta tag content from HTML text. */
function parseMetaContent(html: string, property: string): string | null {
const re = new RegExp(`<meta[^>]+(?:property|name)=["']${property}["'][^>]+content=["']([^"']+)["']`, 'i');
const alt = new RegExp(`<meta[^>]+content=["']([^"']+)["'][^>]+(?:property|name)=["']${property}["']`, 'i');
return (re.exec(html) ?? alt.exec(html))?.[1] ?? null;
}
/** Scrape autofill candidates from the project's built output and source files. */
async function scrapeProjectMeta(
fs: { readFile(path: string, options: { encoding: string }): Promise<string> },
cwd: string,
): Promise<Partial<{ name: string; about: string; picture: string; banner: string }>> {
const result: Partial<{ name: string; about: string; picture: string; banner: string }> = {};
// 1. Try dist/index.html for OG tags
const html = await readVfsText(fs, `${cwd}/dist/index.html`);
if (html) {
const ogTitle = parseMetaContent(html, 'og:title');
const ogDesc = parseMetaContent(html, 'og:description') ?? parseMetaContent(html, 'description');
const ogImage = parseMetaContent(html, 'og:image');
const ogBanner = parseMetaContent(html, 'og:image:banner') ?? parseMetaContent(html, 'twitter:image');
if (ogTitle) result.name = ogTitle;
if (ogDesc) result.about = ogDesc;
if (ogImage) result.picture = ogImage;
if (ogBanner) result.banner = ogBanner;
}
// 2. Try web manifest for name, description, and icons
const manifestPaths = [
`${cwd}/public/manifest.webmanifest`,
`${cwd}/public/manifest.json`,
`${cwd}/dist/manifest.webmanifest`,
`${cwd}/dist/manifest.json`,
];
for (const path of manifestPaths) {
const text = await readVfsText(fs, path);
if (!text) continue;
try {
const manifest = JSON.parse(text);
if (!result.name && (manifest.name || manifest.short_name)) {
result.name = manifest.name ?? manifest.short_name;
}
if (!result.about && manifest.description) {
result.about = manifest.description;
}
if (!result.picture && Array.isArray(manifest.icons) && manifest.icons.length > 0) {
// Prefer the largest icon
const sorted = [...manifest.icons].sort((a, b) => {
const sizeA = parseInt(a.sizes?.split('x')[0] ?? '0');
const sizeB = parseInt(b.sizes?.split('x')[0] ?? '0');
return sizeB - sizeA;
});
const iconSrc = sorted[0]?.src;
if (iconSrc) {
// If it's an absolute URL use it directly, otherwise it's a relative VFS path
result.picture = iconSrc.startsWith('http') ? iconSrc : iconSrc;
}
}
break;
} catch {
// Invalid JSON, try next
}
}
return result;
}
export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
const { fs } = useFS();
const { projectsPath } = useFSPaths();
@@ -117,17 +241,21 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const cwd = `${projectsPath}/${projectId}`;
const { event, isLoading, aTag, hasApp, refetch } = useAppEvent({ cwd });
const { event, isLoading, hasApp, refetch } = useAppEvent({ cwd });
const { settings: deploySettings, isLoading: isDeployLoading } = useProjectDeploySettings(projectId);
const [formData, setFormData] = useState<AppFormData>(emptyFormData(projectId));
const [isSaving, setIsSaving] = useState(false);
const [submitted, setSubmitted] = useState(false);
const [confirmDelete, setConfirmDelete] = useState(false);
const [newTag, setNewTag] = useState('');
const [newKind, setNewKind] = useState('');
const [newHandlerUrl, setNewHandlerUrl] = useState('');
const [newHandlerType, setNewHandlerType] = useState('');
const [advancedOpen, setAdvancedOpen] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const bannerFileInputRef = useRef<HTMLInputElement>(null);
// Get the deployed URL from project deploy settings
const deployedUrl = (() => {
@@ -152,10 +280,36 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
}
}, [hasApp, isDeployLoading, deployedUrl, formData.website]);
// Auto-fill form from OG tags / web manifest when opening for the first time
useEffect(() => {
if (!open || hasApp || isLoading) return;
scrapeProjectMeta(fs, cwd).then(meta => {
setFormData(prev => ({
...prev,
name: prev.name && prev.name !== toTitleCase(projectId) ? prev.name : (meta.name ?? prev.name),
about: prev.about || meta.about || '',
picture: prev.picture || meta.picture || '',
banner: prev.banner || meta.banner || '',
}));
}).catch(() => {/* silently ignore */});
}, [open, hasApp, isLoading, fs, cwd, projectId]);
const updateField = useCallback(<K extends keyof AppFormData>(key: K, value: AppFormData[K]) => {
setFormData(prev => ({ ...prev, [key]: value }));
}, []);
const addTag = useCallback(() => {
const tag = newTag.trim().toLowerCase();
if (tag && !formData.tTags.includes(tag)) {
updateField('tTags', [...formData.tTags, tag]);
setNewTag('');
}
}, [newTag, formData.tTags, updateField]);
const removeTag = useCallback((tag: string) => {
updateField('tTags', formData.tTags.filter(t => t !== tag));
}, [formData.tTags, updateField]);
const addKind = useCallback(() => {
const kind = newKind.trim();
if (kind && !formData.supportedKinds.includes(kind)) {
@@ -181,6 +335,30 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
updateField('webHandlers', formData.webHandlers.filter((_, i) => i !== index));
}, [formData.webHandlers, updateField]);
const handleBannerUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try {
const tags = await uploadFile(file);
const url = tags[0]?.[1];
if (url) {
updateField('banner', url);
toast({ title: 'Banner uploaded', description: 'Your app banner has been uploaded.' });
}
} catch (error) {
toast({
title: 'Upload failed',
description: error instanceof Error ? error.message : 'Failed to upload banner.',
variant: 'destructive',
});
} finally {
if (bannerFileInputRef.current) {
bannerFileInputRef.current.value = '';
}
}
}, [uploadFile, updateField, toast]);
const handleIconUpload = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
@@ -216,12 +394,9 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
return;
}
if (!formData.name.trim()) {
toast({
title: 'Name required',
description: 'Please enter a name for your app.',
variant: 'destructive',
});
setSubmitted(true);
if (!formData.name.trim() || !formData.about.trim() || !formData.website.trim() || !formData.picture.trim() || !formData.banner.trim()) {
return;
}
@@ -243,10 +418,14 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
name: formData.name,
about: formData.about,
picture: formData.picture,
banner: formData.banner,
website: formData.website,
dTag: formData.dTag,
tTags: formData.tTags,
supportedKinds: formData.supportedKinds,
webHandlers: formData.webHandlers,
ngitRepo: naddrToATag(formData.ngitRepo),
nsiteDeployment: naddrToATag(formData.nsiteDeployment),
},
{ fs, cwd, pubkey: user.pubkey },
);
@@ -285,6 +464,37 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
}
};
const handleDelete = async () => {
if (!event) return;
setIsSaving(true);
try {
// Publish NIP-09 deletion event
await publishEvent({
kind: 5,
content: 'Deleted app',
tags: [['e', event.id], ['a', `31990:${event.pubkey}:${formData.dTag}`]],
});
// Remove the local app config
const dotAI = new DotAI(fs, cwd);
await dotAI.writeAppConfig({ a: '' });
await queryClient.invalidateQueries({ queryKey: ['app-event'] });
toast({ title: 'App deleted', description: `"${formData.name}" has been deleted.` });
onOpenChange(false);
} catch (error) {
toast({
title: 'Failed to delete',
description: error instanceof Error ? error.message : 'An unexpected error occurred',
variant: 'destructive',
});
} finally {
setIsSaving(false);
setConfirmDelete(false);
}
};
if (!user) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
@@ -326,88 +536,105 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
</div>
) : (
<div className="space-y-5">
{/* App Preview Card */}
<div className="flex items-start gap-4">
{/* Icon with upload */}
<div className="relative flex-shrink-0 group">
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleIconUpload}
className="hidden"
disabled={isSaving || isUploading}
/>
<button
type="button"
onClick={() => fileInputRef.current?.click()}
disabled={isSaving || isUploading}
className="relative block rounded-2xl overflow-hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none"
>
{formData.picture ? (
<>
<Avatar className="h-20 w-20 rounded-2xl">
<AvatarImage src={formData.picture} alt={formData.name || 'App icon'} className="object-cover" />
<AvatarFallback className="rounded-2xl bg-muted" />
</Avatar>
<div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-2xl">
{isUploading ? (
<Loader2 className="h-5 w-5 text-white animate-spin" />
) : (
<Pencil className="h-4 w-4 text-white" />
)}
</div>
</>
) : (
<div className="h-20 w-20 rounded-2xl bg-muted flex items-center justify-center transition-colors group-hover:bg-muted-foreground">
{isUploading ? (
<Loader2 className="h-6 w-6 text-muted-foreground animate-spin group-hover:text-background" />
) : (
<Upload className="h-6 w-6 text-muted-foreground transition-colors group-hover:text-background" />
)}
</div>
)}
</button>
</div>
{/* Name & Description inline */}
<div className="flex-1 min-w-0 space-y-2">
<Input
value={formData.name}
onChange={e => updateField('name', e.target.value)}
placeholder="App Name"
disabled={isSaving}
/>
<Textarea
value={formData.about}
onChange={e => updateField('about', e.target.value)}
placeholder="A short description of your app..."
rows={2}
disabled={isSaving}
className="resize-none"
/>
</div>
</div>
{/* Website */}
<div className="space-y-1.5">
<Label htmlFor="app-website" className="text-xs text-muted-foreground">Website</Label>
<Input
id="app-website"
value={formData.website}
onChange={e => updateField('website', e.target.value)}
placeholder={deployedUrl || 'https://myapp.example.com'}
disabled={isSaving}
{/* App Preview Card — banner + overlapping icon */}
<div className="border rounded-xl overflow-hidden bg-card">
{/* Hidden file inputs */}
<input
ref={bannerFileInputRef}
type="file"
accept="image/*"
onChange={handleBannerUpload}
className="hidden"
disabled={isSaving || isUploading}
/>
<input
ref={fileInputRef}
type="file"
accept="image/*"
onChange={handleIconUpload}
className="hidden"
disabled={isSaving || isUploading}
/>
</div>
{/* Existing app coordinate info */}
{aTag && (
<div className="text-xs text-muted-foreground space-y-1">
<p className="font-medium">Nostr Coordinate</p>
<code className="block p-2 bg-muted rounded text-xs break-all select-all">{aTag}</code>
{/* Banner */}
<div
className={`relative h-32 bg-muted cursor-pointer group${submitted && !formData.banner ? ' ring-2 ring-destructive ring-inset' : ''}`}
style={formData.banner ? { backgroundImage: `url(${formData.banner})`, backgroundSize: 'cover', backgroundPosition: 'center' } : undefined}
onClick={() => !isSaving && !isUploading && bannerFileInputRef.current?.click()}
>
{!formData.banner && (
<div className="absolute inset-0 bg-gradient-to-br from-accent/10 via-transparent to-primary/5" />
)}
{!formData.banner && (
<div className="absolute inset-0 flex items-center justify-center">
<Plus className="h-6 w-6 text-muted-foreground" strokeWidth={3} />
</div>
)}
<div className="absolute inset-0 bg-black/0 group-hover:bg-black/30 transition-colors flex items-center justify-center">
<span className="opacity-0 group-hover:opacity-100 transition-opacity flex items-center gap-1.5 text-white text-xs font-medium bg-black/50 rounded-full px-3 py-1.5 backdrop-blur-sm">
{isUploading ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Pencil className="h-3.5 w-3.5" />}
{formData.banner ? 'Change banner' : 'Add banner'}
</span>
</div>
{formData.banner && (
<div className="absolute bottom-2 right-2 h-7 w-7 rounded-full bg-background border border-border shadow-sm flex items-center justify-center">
<Pencil className="h-3.5 w-3.5 text-muted-foreground" />
</div>
)}
</div>
)}
{/* Icon + Name/Description */}
<div className="px-4 pb-4">
{/* Icon overlapping banner */}
<div className="-mt-10 mb-3">
<div className={`relative inline-block group cursor-pointer${submitted && !formData.picture ? ' ring-2 ring-destructive rounded-2xl' : ''}`} onClick={() => !isSaving && !isUploading && fileInputRef.current?.click()}>
<Avatar className="h-20 w-20 rounded-2xl border-4 border-background shadow-sm">
<AvatarImage src={formData.picture} alt={formData.name || 'App icon'} className="object-cover" />
<AvatarFallback className="rounded-2xl bg-muted">
{formData.picture ? null : <Plus className="h-7 w-7 text-muted-foreground" strokeWidth={3} />}
</AvatarFallback>
</Avatar>
<div className="absolute inset-0 rounded-2xl bg-black/0 group-hover:bg-black/40 transition-colors flex items-center justify-center">
<Pencil className="h-5 w-5 text-white opacity-0 group-hover:opacity-100 transition-opacity drop-shadow" />
</div>
<div className="absolute bottom-0 right-0 h-6 w-6 rounded-full bg-background border border-border shadow-sm flex items-center justify-center">
<Pencil className="h-3 w-3 text-muted-foreground" />
</div>
</div>
</div>
{/* Name & Description */}
<div className="space-y-2">
<Input
value={formData.name}
onChange={e => updateField('name', e.target.value)}
placeholder="App Name"
disabled={isSaving}
className={submitted && !formData.name.trim() ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
<Textarea
value={formData.about}
onChange={e => updateField('about', e.target.value)}
placeholder="A short description of your app..."
rows={2}
disabled={isSaving}
className={`resize-none${submitted && !formData.about.trim() ? ' border-destructive focus-visible:ring-destructive' : ''}`}
/>
</div>
{/* Website */}
<div className="mt-3">
<Input
id="app-website"
value={formData.website}
onChange={e => updateField('website', e.target.value)}
placeholder={deployedUrl || 'https://myapp.example.com'}
disabled={isSaving}
className={`text-sm${submitted && !formData.website.trim() ? ' border-destructive focus-visible:ring-destructive' : ''}`}
/>
</div>
</div>
</div>
{/* Advanced Section */}
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
@@ -421,140 +648,242 @@ export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) {
</button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="space-y-4 pt-2">
<div className="space-y-3 pt-2">
{/* Hint to use AI */}
<div className="flex items-start gap-2 text-xs text-muted-foreground bg-muted/50 rounded-lg p-3">
<CircleHelp className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
<span>Not sure? Ask Shakespeare to update your app.</span>
</div>
{/* Identifier (d-tag) */}
<div className="space-y-1.5">
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
<Input
id="app-dtag"
value={formData.dTag}
onChange={e => updateField('dTag', e.target.value)}
placeholder="my-app"
disabled={isSaving || hasApp}
/>
<p className="text-xs text-muted-foreground">
{hasApp ? 'Cannot be changed after publishing.' : 'Unique identifier for this app. Defaults to the project ID.'}
</p>
</div>
<Tabs defaultValue="general">
<TabsList className="w-full">
<TabsTrigger value="general" className="flex-1">General</TabsTrigger>
<TabsTrigger value="handlers" className="flex-1">Handlers</TabsTrigger>
<TabsTrigger value="tags" className="flex-1">Tags</TabsTrigger>
</TabsList>
{/* Supported Kinds */}
<div className="space-y-1.5">
<Label className="text-xs">Supported Event Kinds</Label>
{formData.supportedKinds.length > 0 && (
<div className="flex flex-wrap gap-1">
{formData.supportedKinds.map(kind => (
<Badge key={kind} variant="secondary" className="gap-1">
{kind}
<button
onClick={() => removeKind(kind)}
disabled={isSaving}
className="hover:text-destructive"
>
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newKind}
onChange={e => setNewKind(e.target.value)}
placeholder="Kind number (e.g. 1)"
disabled={isSaving}
onKeyDown={e => {
if (e.key === 'Enter') {
e.preventDefault();
addKind();
}
}}
className="flex-1"
/>
<Button
variant="outline"
size="sm"
onClick={addKind}
disabled={isSaving || !newKind.trim()}
className="h-9"
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
{/* Web Handlers */}
<div className="space-y-1.5">
<Label className="text-xs">Web Handlers</Label>
{formData.webHandlers.length > 0 && (
{/* General tab: Identifier, Git Repo, nsite */}
<TabsContent value="general" className="space-y-4 mt-3">
<div className="space-y-1.5">
{formData.webHandlers.map((handler, index) => (
<div key={index} className="flex items-center gap-2 text-sm bg-muted/50 p-2 rounded-md">
<ExternalLink className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<span className="truncate flex-1">{handler.url}</span>
{handler.type && (
<Badge variant="outline" className="text-xs flex-shrink-0">{handler.type}</Badge>
)}
<button
onClick={() => removeHandler(index)}
disabled={isSaving}
className="hover:text-destructive flex-shrink-0"
>
<X className="h-3 w-3" />
</button>
</div>
))}
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
<Input
id="app-dtag"
value={formData.dTag}
onChange={e => updateField('dTag', e.target.value)}
placeholder="my-app"
disabled={isSaving || hasApp}
/>
<p className="text-xs text-muted-foreground">
{hasApp ? 'Cannot be changed after publishing.' : 'Unique identifier for this app. Defaults to the project ID.'}
</p>
</div>
)}
<div className="flex gap-2">
<Input
value={newHandlerUrl}
onChange={e => setNewHandlerUrl(e.target.value)}
placeholder="https://app.example.com/e/<bech32>"
disabled={isSaving}
className="flex-1"
/>
<Input
value={newHandlerType}
onChange={e => setNewHandlerType(e.target.value)}
placeholder="nevent"
disabled={isSaving}
className="w-24"
/>
<Button
variant="outline"
size="sm"
onClick={addHandler}
disabled={isSaving || !newHandlerUrl.trim()}
className="h-9"
>
<Plus className="h-4 w-4" />
</Button>
<div className="space-y-1.5">
<Label htmlFor="app-ngit" className="text-xs">Git Repository</Label>
<Input
id="app-ngit"
value={formData.ngitRepo}
onChange={e => updateField('ngitRepo', e.target.value)}
placeholder="naddr1..."
disabled={isSaving}
className={formData.ngitRepo && !naddrToATag(formData.ngitRepo) ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
{formData.ngitRepo && !naddrToATag(formData.ngitRepo) && (
<p className="text-xs text-destructive">Invalid naddr</p>
)}
<p className="text-xs text-muted-foreground">naddr of the ngit repository (kind 30617). Auto-detected from git remote if left blank.</p>
</div>
<div className="space-y-1.5">
<Label htmlFor="app-nsite" className="text-xs">nsite Deployment</Label>
<Input
id="app-nsite"
value={formData.nsiteDeployment}
onChange={e => updateField('nsiteDeployment', e.target.value)}
placeholder="naddr1..."
disabled={isSaving}
className={formData.nsiteDeployment && !naddrToATag(formData.nsiteDeployment) ? 'border-destructive focus-visible:ring-destructive' : ''}
/>
{formData.nsiteDeployment && !naddrToATag(formData.nsiteDeployment) && (
<p className="text-xs text-destructive">Invalid naddr</p>
)}
<p className="text-xs text-muted-foreground">naddr of the nsite deployment (kind 35128). Auto-detected from .nsite/config.json if left blank.</p>
</div>
</TabsContent>
{/* Handlers tab: Supported Kinds, Web Handlers */}
<TabsContent value="handlers" className="space-y-4 mt-3">
<div className="space-y-1.5">
<Label className="text-xs">Supported Event Kinds</Label>
{formData.supportedKinds.length > 0 && (
<div className="flex flex-wrap gap-1">
{formData.supportedKinds.map(kind => (
<Badge key={kind} variant="secondary" className="gap-1">
{kind}
<button onClick={() => removeKind(kind)} disabled={isSaving} className="hover:text-destructive">
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newKind}
onChange={e => setNewKind(e.target.value)}
placeholder="Kind number (e.g. 1)"
disabled={isSaving}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addKind(); } }}
className="flex-1"
/>
<Button variant="outline" size="sm" onClick={addKind} disabled={isSaving || !newKind.trim()} className="h-9">
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
<div className="space-y-1.5">
<Label className="text-xs">Web Handlers</Label>
{formData.webHandlers.length > 0 && (
<div className="space-y-1.5">
{formData.webHandlers.map((handler, index) => (
<div key={index} className="flex items-center gap-2 text-sm bg-muted/50 p-2 rounded-md">
<ExternalLink className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<span className="truncate flex-1">{handler.url}</span>
{handler.type && (
<Badge variant="outline" className="text-xs flex-shrink-0">{handler.type}</Badge>
)}
<button onClick={() => removeHandler(index)} disabled={isSaving} className="hover:text-destructive flex-shrink-0">
<X className="h-3 w-3" />
</button>
</div>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newHandlerUrl}
onChange={e => setNewHandlerUrl(e.target.value)}
placeholder="https://app.example.com/e/<bech32>"
disabled={isSaving}
className="flex-1"
/>
<Select value={newHandlerType || '_all_'} onValueChange={v => setNewHandlerType(v === '_all_' ? '' : v)} disabled={isSaving}>
<SelectTrigger className="w-28">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="_all_">All</SelectItem>
<SelectItem value="npub">npub</SelectItem>
<SelectItem value="note">note</SelectItem>
<SelectItem value="nprofile">nprofile</SelectItem>
<SelectItem value="nevent">nevent</SelectItem>
<SelectItem value="naddr">naddr</SelectItem>
</SelectContent>
</Select>
<Button variant="outline" size="sm" onClick={addHandler} disabled={isSaving || !newHandlerUrl.trim()} className="h-9">
<Plus className="h-4 w-4" />
</Button>
</div>
<p className="text-xs text-muted-foreground">
URL patterns where <code className="text-xs">{'<bech32>'}</code> will be replaced with the NIP-19 entity.
</p>
</div>
</TabsContent>
{/* Tags tab */}
<TabsContent value="tags" className="space-y-4 mt-3">
<div className="space-y-1.5">
<Label className="text-xs">Tags</Label>
{formData.tTags.length > 0 && (
<div className="flex flex-wrap gap-1">
{formData.tTags.map(tag => (
<Badge key={tag} variant="secondary" className="gap-1">
{tag}
<button onClick={() => removeTag(tag)} disabled={isSaving} className="hover:text-destructive">
<X className="h-3 w-3" />
</button>
</Badge>
))}
</div>
)}
<div className="flex gap-2">
<Input
value={newTag}
onChange={e => setNewTag(e.target.value)}
placeholder="e.g. productivity"
disabled={isSaving}
onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); addTag(); } }}
className="flex-1"
/>
<Button variant="outline" size="sm" onClick={addTag} disabled={isSaving || !newTag.trim()} className="h-9">
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
</TabsContent>
</Tabs>
{/* Delete App */}
{hasApp && (
<div className="pt-2 border-t">
{confirmDelete ? (
<div className="space-y-2">
<p className="text-xs text-muted-foreground">Are you sure? This will publish a deletion event to Nostr.</p>
<div className="flex gap-2">
<Button variant="destructive" size="sm" className="flex-1" onClick={handleDelete} disabled={isSaving}>
{isSaving && <Loader2 className="h-3.5 w-3.5 mr-1.5 animate-spin" />}
Yes, delete
</Button>
<Button variant="outline" size="sm" className="flex-1" onClick={() => setConfirmDelete(false)} disabled={isSaving}>
Cancel
</Button>
</div>
</div>
) : (
<Button
variant="ghost"
size="sm"
className="w-full text-destructive hover:text-destructive hover:bg-destructive/10"
onClick={() => setConfirmDelete(true)}
disabled={isSaving}
>
Delete App
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
URL patterns where <code className="text-xs">{'<bech32>'}</code> will be replaced with the NIP-19 entity.
</p>
</div>
)}
</div>
</CollapsibleContent>
</Collapsible>
{/* Validation summary */}
{submitted && (() => {
const missing = [
!formData.banner && 'banner',
!formData.picture && 'icon',
!formData.name.trim() && 'name',
!formData.about.trim() && 'description',
!formData.website.trim() && 'website',
].filter(Boolean) as string[];
if (!missing.length) return null;
const list = missing.length === 1
? missing[0]
: missing.slice(0, -1).join(', ') + ' and ' + missing[missing.length - 1];
return (
<p className="text-sm text-destructive">
Please add a {list} before publishing.
</p>
);
})()}
{/* Save Button */}
<Button
onClick={handleSave}
disabled={isSaving || !formData.name.trim()}
disabled={isSaving}
className="w-full gap-2"
>
{isSaving ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<Save className="h-4 w-4" />
)}
{isSaving && <Loader2 className="h-4 w-4 animate-spin" />}
{isSaving
? (hasApp ? 'Updating...' : 'Publishing...')
: (hasApp ? 'Update App' : 'Publish App')}
+1 -1
View File
@@ -51,7 +51,7 @@ const AppConfigSchema = z.object({
previewDomain: z.string().min(1),
language: z.string(),
showcaseEnabled: z.boolean(),
showcaseModerator: z.string(),
showcaseCurator: z.string(),
fsPathProjects: z.string().min(1),
fsPathConfig: z.string().min(1),
fsPathTmp: z.string().min(1),
+7 -164
View File
@@ -1,92 +1,24 @@
import React, { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useCurrentUser";
import React from "react";
import { useAppSubmissions } from "@/hooks/useAppSubmissions";
import { AppShowcaseCard } from "@/components/AppShowcaseCard";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { nip19 } from 'nostr-tools';
import { shuffleArray } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent } from "@/components/ui/card";
import { useAppContext } from "@/hooks/useAppContext";
import { useTranslation } from 'react-i18next';
import { Button } from "@/components/ui/button";
import { Link } from 'react-router-dom';
import { Settings } from 'lucide-react';
export function AppShowcase() {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { config } = useAppContext();
const { data: submissions = [], isLoading } = useAppSubmissions();
const [showAllApps, setShowAllApps] = useState(false);
// Get moderator hex from config
const MODERATOR_HEX = useMemo(() => {
try {
const decoded = nip19.decode(config.showcaseModerator);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
}, [config.showcaseModerator]);
const isModerator = user?.pubkey === MODERATOR_HEX;
// Categorize and organize submissions - single pass for efficiency
const {
displayedFeaturedApps,
displayedTemplateApps,
moreApps
} = useMemo(() => {
const DISPLAY_LIMIT = 6;
// Single pass categorization
const templates: typeof submissions = [];
const featured: typeof submissions = [];
const approved: typeof submissions = [];
for (const app of submissions) {
if (app.isHidden) continue;
const isTemplate = app.appTags.includes('Template');
const isFeatured = app.isFeatured;
const isApproved = app.isApproved;
if (isTemplate) {
templates.push(app);
} else if (isFeatured) {
featured.push(app);
} else if (isApproved) {
approved.push(app);
}
}
// Shuffle each category once
const shuffledTemplates = shuffleArray(templates);
const shuffledFeatured = shuffleArray(featured);
const shuffledApproved = shuffleArray(approved);
// Split into display and more sections
return {
displayedFeaturedApps: shuffledFeatured.slice(0, DISPLAY_LIMIT),
displayedTemplateApps: shuffledTemplates.slice(0, DISPLAY_LIMIT),
moreApps: [
...shuffledFeatured.slice(DISPLAY_LIMIT),
...shuffledTemplates.slice(DISPLAY_LIMIT),
...shuffledApproved,
],
};
}, [submissions]);
// Don't show showcase if disabled in settings
if (!config.showcaseEnabled) {
return null;
}
// Don't show showcase if no apps exist
if (isLoading) {
return (
<div className="mt-16 max-w-7xl mx-auto">
@@ -106,14 +38,9 @@ export function AppShowcase() {
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
<div className="flex gap-1 mb-4">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
</div>
<div className="mt-auto flex gap-2">
<Skeleton className="h-6 flex-1" />
<Skeleton className="h-8 w-8" />
<Skeleton className="h-8 w-8" />
</div>
</CardContent>
</Card>
@@ -147,95 +74,11 @@ export function AppShowcase() {
return (
<div className="mt-16 max-w-7xl mx-auto">
{/* Apps Grid */}
<div className="space-y-12">
{/* Featured Apps */}
{displayedFeaturedApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
<span className="text-sm">⭐</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">{t('featuredApps')}</h3>
<p className="text-sm text-muted-foreground">{t('featuredAppsDescription')}</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{displayedFeaturedApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* Templates Section */}
{displayedTemplateApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
<span className="text-sm">📋</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">{t('templates')}</h3>
<p className="text-sm text-muted-foreground">{t('templatesDescription')}</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{displayedTemplateApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* More Apps (Remaining Featured, Templates, and Approved) - Collapsible */}
{moreApps.length > 0 && (
<div>
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
<CollapsibleTrigger asChild>
<Button variant="ghost" className="p-0 h-auto mb-6 hover:bg-transparent">
<div className="flex items-start gap-3">
<div className="flex-none w-8 h-8 bg-blue-100 dark:bg-blue-900/50 rounded-lg flex items-center justify-center">
<span className="text-sm">📱</span>
</div>
<div className="text-left">
<h3 className="text-xl font-bold text-foreground">
{t('moreAppsCount', { count: moreApps.length })}
</h3>
<p className="text-sm text-muted-foreground">
{showAllApps ? t('clickToCollapse') : t('clickToViewMore')}
</p>
</div>
</div>
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{moreApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</CollapsibleContent>
</Collapsible>
</div>
)}
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{submissions.map((app) => (
<AppShowcaseCard key={app.id} app={app} />
))}
</div>
</div>
);
}
}
+60 -529
View File
@@ -2,541 +2,81 @@ import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
ExternalLink,
Edit,
Star,
StarOff,
Eye,
EyeOff,
MoreVertical,
CheckCircle,
XCircle,
User,
Home,
Contact
} from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { ExternalLink, User } from 'lucide-react';
import type { AppSubmission } from '@/hooks/useAppSubmissions';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useNostr } from '@nostrify/react';
import { useAuthor } from '@/hooks/useAuthor';
import { nip19 } from 'nostr-tools';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
interface AppShowcaseCardProps {
app: AppSubmission;
onEdit?: (app: AppSubmission) => void;
showModerationControls?: boolean;
hideApprovalStatus?: boolean; // Hide pending/approval badges
}
export function AppShowcaseCard({ app, onEdit, showModerationControls, hideApprovalStatus: _hideApprovalStatus }: AppShowcaseCardProps) {
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { mutate: publishEvent, isPending } = useNostrPublish();
const queryClient = useQueryClient();
const [imageError, setImageError] = useState(false);
const { toast } = useToast();
export function AppShowcaseCard({ app }: AppShowcaseCardProps) {
const [bannerError, setBannerError] = useState(false);
const [iconError, setIconError] = useState(false);
// Get author pubkey from authorNpub field
const authorPubkey = React.useMemo(() => {
if (!app.authorNpub) return app.pubkey; // Fallback to event pubkey
try {
// If it's already a hex key, use it directly
if (app.authorNpub.length === 64 && /^[0-9a-f]+$/i.test(app.authorNpub)) {
return app.authorNpub;
}
// Otherwise try to decode as npub
const decoded = nip19.decode(app.authorNpub);
return decoded.type === 'npub' ? decoded.data : app.pubkey;
} catch {
return app.pubkey; // Fallback to event pubkey if decode fails
}
}, [app.authorNpub, app.pubkey]);
const { data: authorData } = useAuthor(authorPubkey);
const isOwner = user?.pubkey === app.pubkey;
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
const MODERATOR_HEX = (() => {
try {
const decoded = nip19.decode(MODERATOR_NPUB);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
})();
const isModerator = user?.pubkey === MODERATOR_HEX;
// Check if this is a Halloween submission by looking for Halloween tags
const isHalloweenSubmission = app.appTags.includes('Halloween Hackathon 2025');
// Get contact info from Halloween submissions (these have lightning/email tags)
const getContactInfo = () => {
if (!isHalloweenSubmission) return null;
// Look for lightning and email tags in the event tags
const lightningTag = app.tags?.find((tag: string[]) => tag[0] === 'lightning')?.[1];
const emailTag = app.tags?.find((tag: string[]) => tag[0] === 'email')?.[1];
return { lightning: lightningTag, email: emailTag };
};
const handleCopyContactInfo = () => {
const contactInfo = getContactInfo();
if (!contactInfo) return;
const info: string[] = [];
if (contactInfo.lightning) info.push(`Lightning: ${contactInfo.lightning}`);
if (contactInfo.email) info.push(`Email: ${contactInfo.email}`);
const textToCopy = info.join('\n');
navigator.clipboard.writeText(textToCopy);
toast({
title: 'Contact Info Copied!',
description: `Copied ${info.length} contact method(s) to clipboard`
});
};
const handleModerationAction = async (action: 'feature' | 'unfeature' | 'approve' | 'unapprove' | 'hide' | 'unhide' | 'homepage' | 'unhomepage') => {
if (!isModerator || !user) return;
const dTag = app.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) {
toast({
title: 'Error',
description: 'Cannot perform moderation action: missing app identifier',
variant: 'destructive'
});
return;
}
const appCoordinate = `${app.kind}:${app.pubkey}:${dTag}`;
try {
if (action === 'homepage' || action === 'unhomepage') {
// Get current homepage apps list
const currentHomepageLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-homepage-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentHomepageList = currentHomepageLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current homepage app coordinates
const currentHomepageApps = new Set<string>();
if (currentHomepageList) {
currentHomepageList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentHomepageApps.add(tag[1]));
}
// Update the homepage set
if (action === 'homepage') {
currentHomepageApps.add(appCoordinate);
} else {
currentHomepageApps.delete(appCoordinate);
}
// Publish updated homepage apps list
publishEvent({
kind: 30267,
content: 'Soapbox homepage apps curated by moderators',
tags: [
['d', 'soapbox-homepage-apps'],
['title', 'Soapbox Homepage Apps'],
['description', 'Apps displayed on the Soapbox homepage'],
...Array.from(currentHomepageApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
// If adding to homepage, also ensure it's approved
if (action === 'homepage') {
// Get current approved apps list
const currentApprovedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Add to approved list if not already there
currentApprovedApps.add(appCoordinate);
// Publish updated approved apps list
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
}
} else if (action === 'feature' || action === 'unfeature') {
// Get current featured apps list
const currentFeaturedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-featured-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentFeaturedList = currentFeaturedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current featured app coordinates
const currentFeaturedApps = new Set<string>();
if (currentFeaturedList) {
currentFeaturedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentFeaturedApps.add(tag[1]));
}
// Update the featured set
if (action === 'feature') {
currentFeaturedApps.add(appCoordinate);
} else {
currentFeaturedApps.delete(appCoordinate);
}
// Publish updated featured apps list
publishEvent({
kind: 30267,
content: 'Soapbox featured apps curated by moderators',
tags: [
['d', 'soapbox-featured-apps'],
['title', 'Soapbox Featured Apps'],
['description', 'Apps featured in the Soapbox showcase'],
...Array.from(currentFeaturedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
// If featuring an app, also ensure it's approved
if (action === 'feature') {
// Get current approved apps list
const currentApprovedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Add to approved list if not already there
currentApprovedApps.add(appCoordinate);
// Publish updated approved apps list
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
}
} else if (action === 'approve' || action === 'unapprove') {
// Get current approved apps list
const currentApprovedLists = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1
}], { signal: AbortSignal.timeout(3000) });
const currentApprovedList = currentApprovedLists.reduce((latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Update the approved set
if (action === 'approve') {
currentApprovedApps.add(appCoordinate);
} else {
currentApprovedApps.delete(appCoordinate);
}
// Publish updated approved apps list
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map(coord => ['a', coord])
],
created_at: Math.floor(Date.now() / 1000)
});
} else if (action === 'hide' || action === 'unhide') {
// Create NIP-56 report event
publishEvent({
kind: 1984,
content: `App ${action}den by moderator: "${app.appName}"`,
tags: [
['a', appCoordinate, action === 'hide' ? 'spam' : 'other'],
['p', app.pubkey],
['L', 'soapbox.moderation'],
['l', action === 'hide' ? 'hidden' : 'unhidden', 'soapbox.moderation']
],
created_at: Math.floor(Date.now() / 1000)
});
}
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
// If this is a Halloween app, also invalidate Halloween queries
if (isHalloweenSubmission) {
queryClient.invalidateQueries({ queryKey: ['halloween-submissions'] });
queryClient.invalidateQueries({ queryKey: ['halloween-submissions-with-contacts'] });
}
toast({
title: 'Success!',
description: `App "${app.appName}" ${action}d successfully`
});
} catch (error) {
console.error('Moderation action failed:', error);
toast({
title: 'Error',
description: `Failed to ${action} app "${app.appName}"`,
variant: 'destructive'
});
}
};
const { data: authorData } = useAuthor(app.pubkey);
const authorNpub = nip19.npubEncode(app.pubkey);
return (
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
<div className="relative">
{/* App Screenshot */}
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
>
{!imageError ? (
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col overflow-hidden">
{/* Banner + overlapping icon */}
<a
href={app.websiteUrl || undefined}
target="_blank"
rel="noopener noreferrer"
className="block relative"
>
{/* Banner */}
<div className="aspect-[3/1] bg-muted overflow-hidden">
{app.bannerUrl && !bannerError ? (
<img
src={app.screenshotUrl}
alt={`${app.appName} screenshot`}
src={app.bannerUrl}
alt=""
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
onError={() => setImageError(true)}
onError={() => setBannerError(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
<div className="text-center">
<div className="w-16 h-16 mx-auto mb-2 bg-muted rounded-lg flex items-center justify-center">
<ExternalLink className="w-8 h-8" />
</div>
<p className="text-sm">Screenshot unavailable</p>
</div>
</div>
<div className="w-full h-full bg-gradient-to-br from-accent/10 via-transparent to-primary/5" />
)}
</a>
</div>
{/* Actions Menu */}
{(isOwner || showModerationControls) && (
<div className="absolute top-3 right-3">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="sm" className="h-8 w-8 p-0">
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{isOwner && (
<DropdownMenuItem onClick={() => onEdit?.(app)}>
<Edit className="w-4 h-4 mr-2" />
Edit App
</DropdownMenuItem>
)}
{showModerationControls && isModerator && (
<>
{isHalloweenSubmission && getContactInfo() && (getContactInfo()?.lightning || getContactInfo()?.email) && (
<DropdownMenuItem
onClick={handleCopyContactInfo}
>
<Contact className="w-4 h-4 mr-2" />
View Contact Info
</DropdownMenuItem>
)}
{!app.isApproved && (
<DropdownMenuItem
onClick={() => handleModerationAction('approve')}
disabled={isPending}
>
<CheckCircle className="w-4 h-4 mr-2" />
Approve
</DropdownMenuItem>
)}
{app.isApproved && !app.isFeatured && (
<DropdownMenuItem
onClick={() => handleModerationAction('unapprove')}
disabled={isPending}
>
<XCircle className="w-4 h-4 mr-2" />
Unapprove
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={() => handleModerationAction(app.isFeatured ? 'unfeature' : 'feature')}
disabled={isPending}
>
{app.isFeatured ? (
<>
<StarOff className="w-4 h-4 mr-2" />
Un-feature
</>
) : (
<>
<Star className="w-4 h-4 mr-2" />
Feature
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleModerationAction(app.isHomepage ? 'unhomepage' : 'homepage')}
disabled={isPending}
>
{app.isHomepage ? (
<>
<Home className="w-4 h-4 mr-2" />
Remove from Homepage
</>
) : (
<>
<Home className="w-4 h-4 mr-2" />
Add to Homepage
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleModerationAction(app.isHidden ? 'unhide' : 'hide')}
disabled={isPending}
>
{app.isHidden ? (
<>
<Eye className="w-4 h-4 mr-2" />
Unhide
</>
) : (
<>
<EyeOff className="w-4 h-4 mr-2" />
Hide
</>
)}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div>
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-3">
{/* App Icon */}
<div className="w-12 h-12 rounded-lg overflow-hidden bg-muted flex-shrink-0">
{/* Icon overlapping banner */}
<div className="absolute bottom-0 translate-y-1/2 left-4">
<div className="h-14 w-14 rounded-xl border-2 border-background shadow-md overflow-hidden bg-muted flex-shrink-0">
{app.appIconUrl && !iconError ? (
<img
src={app.appIconUrl}
alt={`${app.appName} icon`}
className="w-full h-full object-cover"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
}}
onError={() => setIconError(true)}
/>
</div>
<div>
<h3 className="text-xl font-semibold text-foreground mb-1" title={app.appName}>
{app.appName.length > 50 ? `${app.appName.slice(0, 50)}...` : app.appName}
</h3>
</div>
) : (
<div className="w-full h-full flex items-center justify-center">
<ExternalLink className="w-5 h-5 text-muted-foreground" />
</div>
)}
</div>
</div>
</a>
<p className="text-muted-foreground mb-3 line-clamp-3">{app.description}</p>
<CardContent className="pt-10 px-4 pb-4 flex flex-col flex-1">
<h3 className="text-base font-semibold text-foreground mb-1 truncate" title={app.appName}>
{app.appName}
</h3>
{/* Author Information */}
{app.description && (
<p className="text-sm text-muted-foreground mb-3 line-clamp-2">{app.description}</p>
)}
{/* Author */}
<div className="flex items-center gap-2 mb-4">
<div className="w-6 h-6 rounded-full overflow-hidden bg-muted flex-shrink-0">
<div className="w-5 h-5 rounded-full overflow-hidden bg-muted flex-shrink-0">
{authorData?.metadata?.picture ? (
<img
src={authorData.metadata.picture}
alt={`${authorData.metadata.name || 'Author'} avatar`}
alt={authorData.metadata.name || 'Author'}
className="w-full h-full object-cover"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
target.parentElement!.innerHTML = '<div class="w-full h-full flex items-center justify-center"><svg class="w-3 h-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path></svg></div>';
}}
/>
) : (
<div className="w-full h-full flex items-center justify-center">
@@ -544,10 +84,10 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
</div>
)}
</div>
<span className="text-sm text-muted-foreground">
<span className="text-xs text-muted-foreground">
by{' '}
<a
href={`https://ditto.pub/${app.authorNpub || nip19.npubEncode(authorPubkey)}`}
href={`https://ditto.pub/${authorNpub}`}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:text-primary/80 transition-colors hover:underline"
@@ -557,33 +97,24 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
</span>
</div>
{/* Spacer to push action links to bottom */}
<div className="flex-1"></div>
<div className="flex-1" />
{/* Action Links */}
<div className="flex items-center gap-2 mt-auto">
<Link
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
className="flex-1"
>
<img
src="/badge.svg"
alt="Edit with Shakespeare"
className="h-6 hover:opacity-80 transition-opacity"
/>
</Link>
<Button variant="outline" size="sm" asChild>
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
title="Visit app"
>
<ExternalLink className="w-4 h-4" />
</a>
</Button>
{app.repositoryUrl && (
<Link to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`} className="flex-1">
<img src="/badge.svg" alt="Edit with Shakespeare" className="h-6 hover:opacity-80 transition-opacity" />
</Link>
)}
{app.websiteUrl && (
<Button variant="outline" size="sm" asChild>
<a href={app.websiteUrl} target="_blank" rel="noopener noreferrer" title="Visit app">
<ExternalLink className="w-4 h-4" />
</a>
</Button>
)}
</div>
</CardContent>
</Card>
);
}
}
+2 -1
View File
@@ -3,9 +3,10 @@ import { DeploySettingsContext, type DeploySettings, type DeployProvider } from
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
import { DEFAULT_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
const DEFAULT_SETTINGS: DeploySettings = {
providers: [],
providers: [...DEFAULT_DEPLOY_PROVIDERS],
};
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
+28
View File
@@ -1,8 +1,26 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl } from '@/lib/faviconUrl';
import { cn } from '@/lib/utils';
import { Globe } from 'lucide-react';
import { ReactNode, useMemo } from 'react';
/**
* Icons for known providers whose URLs can't resolve a favicon,
* such as services running on localhost.
*/
function knownProviderIcon(url: string | URL | undefined, size: number): ReactNode | undefined {
if (!url) return;
try {
const u = new URL(url);
// Meridian local bridge
if (u.hostname === '127.0.0.1' && u.port === '3456') {
return <Globe size={size} className="text-purple-500" />;
}
} catch {
return;
}
}
interface ExternalFaviconProps {
/** The URL to fetch the favicon for */
url: string | URL | undefined;
@@ -42,6 +60,16 @@ export function ExternalFavicon({
}
}, [url, config.faviconUrl]);
// Providers with a known icon (e.g. local services) skip the favicon service
const knownIcon = knownProviderIcon(url, size);
if (knownIcon) {
return (
<span className={cn('inline-flex items-center justify-center', className)}>
{knownIcon}
</span>
);
}
// If faviconSrc is not available, render the fallback directly
if (!faviconSrc) {
return (
@@ -0,0 +1,344 @@
import git from 'isomorphic-git';
import { Loader2, Zap } from 'lucide-react';
import { DropdownMenuItem } from '@/components/ui/dropdown-menu';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { toast } from '@/hooks/useToast';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
/**
* "Optimize Repository" entry for the project dropdown.
*
* Fully self-contained recovery action: clicking it consolidates the
* project's git pack files into a single pack containing every reachable
* object, deletes the old packs and redundant loose objects, and reports
* the size reduction in a toast. A spinner toast is shown while it runs.
*
* Everything (UI, gc algorithm, state) lives in this one file so the
* feature can be removed by deleting this file and its single render
* line in ProjectTitleMenu.
*/
/** Projects with an optimization currently in flight (reentrancy guard). */
const running = new Set<string>();
// ---------------------------------------------------------------------------
// Repository optimization (simplified `git gc` for isomorphic-git repos)
// ---------------------------------------------------------------------------
/** Yield to the event loop so the UI can paint between batches of work. */
function yieldToMain(): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, 0));
}
/** Recursively sum the size of all files under `path`. */
async function dirSize(fs: JSRuntimeFS, path: string): Promise<number> {
let total = 0;
let entries: string[];
try {
entries = await fs.readdir(path);
} catch {
return 0;
}
for (const name of entries) {
const child = `${path}/${name}`;
try {
const stat = await fs.stat(child);
if (stat.isDirectory()) {
total += await dirSize(fs, child);
} else {
total += stat.size ?? 0;
}
} catch {
// Skip unreadable entries.
}
}
return total;
}
/**
* Recursively walk a tree, adding every blob/tree OID to `reachable`.
* Returns the number of objects that could not be read.
*/
async function walkTree(
fs: JSRuntimeFS,
gitdir: string,
treeOid: string,
reachable: Set<string>,
visitedTrees: Set<string>,
): Promise<number> {
if (visitedTrees.has(treeOid)) return 0;
visitedTrees.add(treeOid);
let tree: Awaited<ReturnType<typeof git.readTree>>;
try {
tree = await git.readTree({ fs, gitdir, oid: treeOid });
} catch {
return 1;
}
reachable.add(treeOid);
let errors = 0;
for (const entry of tree.tree) {
if (entry.type === 'tree') {
errors += await walkTree(fs, gitdir, entry.oid, reachable, visitedTrees);
} else if (entry.type === 'blob') {
reachable.add(entry.oid);
}
// entry.type === 'commit' is a submodule gitlink; skip.
}
return errors;
}
interface OptimizeResult {
bytesBefore: number;
bytesAfter: number;
/** True when some objects could not be read, so the repo was left untouched. */
incomplete: boolean;
}
/**
* Consolidate all reachable objects into one new pack, then delete the old
* packs and redundant loose objects.
*
* Non-destructive: every object reachable from any ref or HEAD is preserved.
* If any object fails to read during the reachability walk, or the new pack
* would be larger than the files it replaces, the repository is left
* completely untouched.
*/
async function optimizeRepository(fs: JSRuntimeFS, dir: string): Promise<OptimizeResult> {
const gitdir = `${dir}/.git`;
const objectsDir = `${gitdir}/objects`;
const packDir = `${objectsDir}/pack`;
const bytesBefore = await dirSize(fs, objectsDir);
let oldPackEntries: string[];
try {
oldPackEntries = await fs.readdir(packDir);
} catch {
oldPackEntries = [];
}
// 1. Collect ref tips (branches, tags, remotes, stash, HEAD).
const tips = new Set<string>();
let refs: string[] = [];
try {
refs = await git.listRefs({ fs, gitdir, filepath: 'refs' });
} catch {
refs = [];
}
for (const ref of refs) {
try {
tips.add(await git.resolveRef({ fs, gitdir, ref: `refs/${ref}` }));
} catch {
// Broken ref; skip.
}
}
try {
tips.add(await git.resolveRef({ fs, gitdir, ref: 'HEAD' }));
} catch {
// No HEAD (fresh repo).
}
// 2. Walk reachability from every tip.
const reachable = new Set<string>();
const visitedTrees = new Set<string>();
const stack = [...tips];
let walkErrors = 0;
let steps = 0;
while (stack.length > 0) {
const oid = stack.pop()!;
if (reachable.has(oid)) continue;
let parsed: Awaited<ReturnType<typeof git.readObject>>;
try {
parsed = await git.readObject({ fs, gitdir, oid, format: 'parsed' });
} catch {
walkErrors++;
continue;
}
reachable.add(oid);
if (parsed.type === 'commit') {
const commit = parsed.object as { tree: string; parent: string[] };
for (const parent of commit.parent) stack.push(parent);
walkErrors += await walkTree(fs, gitdir, commit.tree, reachable, visitedTrees);
} else if (parsed.type === 'tag') {
stack.push((parsed.object as { object: string }).object);
} else if (parsed.type === 'tree') {
walkErrors += await walkTree(fs, gitdir, oid, reachable, visitedTrees);
}
if (++steps % 64 === 0) await yieldToMain();
}
if (walkErrors > 0 || reachable.size === 0) {
// Damaged repo (or empty repo) — change nothing.
return { bytesBefore, bytesAfter: bytesBefore, incomplete: walkErrors > 0 };
}
// 3. Write the consolidated pack and its index.
await yieldToMain();
const { filename } = await git.packObjects({
fs,
gitdir,
oids: [...reachable],
write: true,
});
await git.indexPack({ fs, dir, gitdir, filepath: `.git/objects/pack/${filename}` });
// 4. Safety check: isomorphic-git writes undeltified packs, which can be
// larger than the (server-deltified) packs they replace. Only proceed if
// deleting the old packs and loose copies reclaims more than the new pack
// costs; otherwise remove the new pack and leave the repo exactly as-is.
const fileSize = async (path: string): Promise<number> => {
try {
return (await fs.stat(path)).size ?? 0;
} catch {
return 0;
}
};
const newBase = filename!.replace(/\.pack$/, '');
const newPackBytes =
(await fileSize(`${packDir}/${filename}`)) + (await fileSize(`${packDir}/${newBase}.idx`));
let reclaimableBytes = 0;
for (const name of oldPackEntries) {
if (name.startsWith(`${newBase}.`)) continue;
if (!/\.(pack|idx)$/.test(name)) continue;
reclaimableBytes += await fileSize(`${packDir}/${name}`);
}
steps = 0;
for (const oid of reachable) {
reclaimableBytes += await fileSize(`${objectsDir}/${oid.slice(0, 2)}/${oid.slice(2)}`);
if (++steps % 64 === 0) await yieldToMain();
}
if (newPackBytes >= reclaimableBytes) {
for (const name of [filename!, `${newBase}.idx`]) {
try {
await fs.unlink(`${packDir}/${name}`);
} catch {
// Best-effort.
}
}
return { bytesBefore, bytesAfter: bytesBefore, incomplete: false };
}
// 5. Delete the old pack files.
for (const name of oldPackEntries) {
if (name.startsWith(`${newBase}.`)) continue;
if (!/\.(pack|idx)$/.test(name)) continue;
try {
await fs.unlink(`${packDir}/${name}`);
} catch {
// Best-effort.
}
}
// 6. Delete loose copies of objects now stored in the new pack.
const touchedDirs = new Set<string>();
steps = 0;
for (const oid of reachable) {
const looseDir = `${objectsDir}/${oid.slice(0, 2)}`;
try {
await fs.unlink(`${looseDir}/${oid.slice(2)}`);
touchedDirs.add(looseDir);
} catch {
// Object wasn't loose; nothing to do.
}
if (++steps % 64 === 0) await yieldToMain();
}
// Remove now-empty loose object shards.
for (const looseDir of touchedDirs) {
try {
if ((await fs.readdir(looseDir)).length === 0) await fs.rmdir(looseDir);
} catch {
// Best-effort.
}
}
const bytesAfter = await dirSize(fs, objectsDir);
return { bytesBefore, bytesAfter, incomplete: false };
}
// ---------------------------------------------------------------------------
// UI
// ---------------------------------------------------------------------------
function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
const units = ['KB', 'MB', 'GB'];
let value = bytes;
let unit = 'B';
for (const next of units) {
if (value < 1024) break;
value /= 1024;
unit = next;
}
return `${value.toFixed(1)} ${unit}`;
}
async function run(fs: JSRuntimeFS, dir: string, projectId: string) {
if (running.has(projectId)) return;
running.add(projectId);
const progress = toast({
description: (
<span className="flex items-center gap-2">
<Loader2 className="h-4 w-4 animate-spin" />
Optimizing repository…
</span>
),
duration: Infinity,
});
try {
const result = await optimizeRepository(fs, dir);
const saved = result.bytesBefore - result.bytesAfter;
progress.update({
id: progress.id,
title: 'Repository optimized',
description: result.incomplete
? 'Some objects could not be read, so the repository was left untouched for safety.'
: saved > 0
? `${formatBytes(result.bytesBefore)} → ${formatBytes(result.bytesAfter)} (saved ${formatBytes(saved)})`
: `No size reduction (${formatBytes(result.bytesAfter)})`,
duration: 10000,
});
} catch (error) {
progress.update({
id: progress.id,
title: 'Repository optimization failed',
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
duration: 10000,
});
} finally {
running.delete(projectId);
}
}
interface OptimizeRepositoryMenuItemProps {
projectId: string;
disabled?: boolean;
}
export function OptimizeRepositoryMenuItem({ projectId, disabled }: OptimizeRepositoryMenuItemProps) {
const { fs } = useFS();
const { projectsPath } = useFSPaths();
return (
<DropdownMenuItem
onClick={() => run(fs, `${projectsPath}/${projectId}`, projectId)}
disabled={disabled}
className="gap-2"
>
<Zap className="h-4 w-4" />
Optimize Repository
</DropdownMenuItem>
);
}
+3
View File
@@ -19,6 +19,7 @@ import {
import { cn } from '@/lib/utils';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useQueryClient } from '@tanstack/react-query';
import { OptimizeRepositoryMenuItem } from '@/components/OptimizeRepositoryMenuItem';
interface ProjectTitleMenuProps {
projectId: string;
@@ -119,6 +120,8 @@ export function ProjectTitleMenu({
Rollback
</DropdownMenuItem>
<OptimizeRepositoryMenuItem projectId={projectId} disabled={isAnyLoading} />
<DropdownMenuItem
onClick={onNewChat}
disabled={isAnyLoading}
+51 -17
View File
@@ -74,18 +74,16 @@ export function ProviderConfigDialog({
// Use baseURL from configured provider, falling back to preset baseURL
const baseURL = ('baseURL' in localProvider && localProvider.baseURL) || preset?.baseURL;
// For Shakespeare, special handling for host field
const shakespeareUrl = localProvider.type === 'shakespeare' && 'host' in localProvider && localProvider.host
? normalizeUrl(localProvider.host)
: undefined;
// A gateway is recognised by the domain it serves, not by its API origin
const gatewayUrl = localProvider.type === 'npanel' ? normalizeUrl(localProvider.domain) : undefined;
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogContent className="max-w-md max-h-[90vh] flex flex-col">
<DialogHeader className="shrink-0">
<div className="flex items-center gap-2">
<ExternalFavicon
url={shakespeareUrl || baseURL}
url={gatewayUrl || baseURL}
size={20}
fallback={<Rocket size={20} />}
/>
@@ -96,7 +94,10 @@ export function ProviderConfigDialog({
</DialogDescription>
</DialogHeader>
<div className="space-y-4 py-4">
{/* The fields scroll, the buttons don't: a provider with relay and
blossom lists is taller than a phone, and a Save button below the
fold is a Save button nobody can press. */}
<div className="flex-1 overflow-y-auto space-y-4 py-4 px-1 -mx-1">
<div className="grid gap-2">
<Label htmlFor="provider-name">
Name <span className="text-destructive">*</span>
@@ -109,22 +110,55 @@ export function ProviderConfigDialog({
/>
</div>
{localProvider.type === 'shakespeare' ? (
{localProvider.type === 'npanel' ? (
<>
<p className="text-sm text-muted-foreground">
{t('shakespeareDeployNostrAuth')}
</p>
<div className="grid gap-2">
<Label htmlFor="provider-host">
Host (Optional)
<Label htmlFor="provider-domain">
Domain <span className="text-destructive">*</span>
</Label>
<Input
id="provider-host"
id="provider-domain"
placeholder="shakespeare.wtf"
value={localProvider.host || ''}
onChange={(e) => setLocalProvider({ ...localProvider, host: e.target.value })}
value={localProvider.domain}
onChange={(e) => setLocalProvider({ ...localProvider, domain: e.target.value })}
/>
<p className="text-xs text-muted-foreground">
Sites get a name under this domain.
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="provider-dashboard-host">
Gateway API <span className="text-destructive">*</span>
</Label>
<Input
id="provider-dashboard-host"
placeholder="npanel.shakespeare.to"
value={localProvider.dashboardHost}
onChange={(e) => setLocalProvider({ ...localProvider, dashboardHost: e.target.value })}
/>
<p className="text-xs text-muted-foreground">
Where names are claimed. Usually a different host from the one above.
</p>
</div>
<UrlListEditor
label="Relay URLs"
items={localProvider.relayUrls ?? []}
onChange={(urls) => setLocalProvider({ ...localProvider, relayUrls: urls })}
protocol="wss"
placeholder="relay.ditto.pub"
required
/>
<UrlListEditor
label="Blossom Servers"
items={localProvider.blossomServers ?? []}
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
protocol="https"
placeholder="blossom.ditto.pub"
required
/>
</>
) : localProvider.type === 'nsite' ? (
<>
@@ -134,7 +168,7 @@ export function ProviderConfigDialog({
</Label>
<Input
id="provider-gateway"
placeholder="nsite.lol"
placeholder="shakespeare.to"
value={localProvider.gateway || ''}
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
/>
@@ -152,7 +186,7 @@ export function ProviderConfigDialog({
items={localProvider.blossomServers ?? []}
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
protocol="https"
placeholder="blossom.primal.net"
placeholder="blossom.ditto.pub"
required
/>
</>
@@ -272,7 +306,7 @@ export function ProviderConfigDialog({
)}
</div>
<DialogFooter className="gap-2">
<DialogFooter className="gap-2 shrink-0">
<Button
variant="destructive"
onClick={handleDelete}
+4 -4
View File
@@ -39,7 +39,7 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
showcaseCurator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -83,7 +83,7 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
showcaseCurator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -128,7 +128,7 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
showcaseCurator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
@@ -176,7 +176,7 @@ describe('SentryProvider', () => {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'test.dev',
showcaseEnabled: false,
showcaseModerator: '',
showcaseCurator: '',
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
+108 -32
View File
@@ -1,5 +1,5 @@
import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
@@ -25,6 +25,8 @@ import { Terminal as TerminalComponent } from '@/components/Terminal';
import { useSearchParams } from 'react-router-dom';
import { useAppContext } from '@/hooks/useAppContext';
import { isMediaFile } from '@/lib/fileUtils';
import { deriveIframeSubdomain } from '@/lib/iframeSubdomain';
import { getPreviewInjectedScript } from '@/lib/previewInjectedScript';
interface PreviewPaneProps {
projectId: string;
@@ -67,6 +69,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const { t } = useTranslation();
const { config } = useAppContext();
const { previewDomain } = config;
// Derive a private, stable subdomain from a device-local seed + the project ID.
// This prevents malicious project names from colliding with another project's
// origin on iframe.diy, protecting localStorage/IndexedDB isolation.
const previewSubdomain = useMemo(() => deriveIframeSubdomain('preview', projectId), [projectId]);
const previewOrigin = useMemo(() => `https://${previewSubdomain}.${previewDomain}`, [previewSubdomain, previewDomain]);
const [selectedFile, setSelectedFile] = useState<string | null>(null);
const [fileContent, setFileContent] = useState<string>('');
const [isLoading, setIsLoading] = useState(false);
@@ -82,6 +91,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const [isFullscreen, setIsFullscreen] = useState(false);
const [deviceMode, setDeviceMode] = useState<DeviceMode>('laptop');
const [isLogsOpen, setIsLogsOpen] = useState(false);
// Incremented to force a full remount of the preview iframe. Using a
// remount (via React key) is more reliable than sending a `refresh`
// JSON-RPC to the nested iframe.diy frames: messages can be silently
// dropped if the inner iframe is mid-reload, not yet mounted, or if
// the outer frame's handshake is still pending. A remount always works.
const [iframeReloadKey, setIframeReloadKey] = useState(0);
const previewContainerRef = useRef<HTMLDivElement>(null);
const iframeRef = useRef<HTMLIFrameElement>(null);
const iframePanelRef = useRef<ImperativePanelHandle>(null);
@@ -182,18 +197,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [projectId, previewDomain]);
}, [previewOrigin]);
const sendError = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [projectId, previewDomain]);
}, [previewOrigin]);
const handleConsoleMessage = useCallback((message: {
jsonrpc: '2.0';
@@ -248,6 +260,17 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}
}, [historyIndex, navigationHistory]);
const sendNotification = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
jsonrpc: '2.0' as const,
method,
params: params || {},
};
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [previewOrigin]);
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
@@ -256,10 +279,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
params: params || {},
id: Date.now()
};
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
}
}, [projectId, previewDomain]);
}, [previewOrigin]);
const navigateIframe = useCallback((url: string) => {
// Send semantic path directly (e.g., "/about", "/contact")
@@ -268,13 +290,31 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
}, [sendNavigationCommand]);
const refreshIframe = useCallback(() => {
sendNavigationCommand('refresh');
}, [sendNavigationCommand]);
// Force a full remount of the iframe rather than sending a `refresh`
// JSON-RPC command. The RPC path is unreliable during rapid build
// cycles because the command has to traverse two iframes (outer
// iframe.diy frame → inner app iframe) and can be silently dropped
// if the inner iframe is mid-reload, not yet mounted, or the outer
// frame's handshake is still pending.
setIframeReloadKey((n) => n + 1);
}, []);
const toggleFullscreen = useCallback(() => {
setIsFullscreen(prev => !prev);
}, []);
/** Virtual path where the injected preview script is served. */
const INJECTED_SCRIPT_PATH = '/__injected__/preview.js';
/** Inject a script tag into an HTML string using DOMParser. */
const injectScript = useCallback((html: string): string => {
const doc = new DOMParser().parseFromString(html, 'text/html');
const tag = doc.createElement('script');
tag.src = INJECTED_SCRIPT_PATH;
doc.head.insertBefore(tag, doc.head.firstChild);
return '<!DOCTYPE html>\n' + doc.documentElement.outerHTML;
}, []);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -282,16 +322,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
try {
// Parse the URL and validate origin
const url = new URL(fetchRequest.url);
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (url.origin !== expectedOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
if (url.origin !== previewOrigin) {
console.log(`Invalid origin: ${url.origin}, expected: ${previewOrigin}`);
sendError({
jsonrpc: '2.0',
error: {
code: -32003,
message: 'Invalid URL - origin mismatch',
data: { url: fetchRequest.url, expectedOrigin }
data: { url: fetchRequest.url, expectedOrigin: previewOrigin }
},
id
});
@@ -301,24 +340,52 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const path = url.pathname;
const filePath = path;
// Serve the injected preview script at its virtual path
if (path === INJECTED_SCRIPT_PATH) {
sendResponse({
jsonrpc: '2.0',
result: {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': 'application/javascript',
'Cache-Control': 'no-cache',
},
body: encodeBase64(new TextEncoder().encode(getPreviewInjectedScript())),
},
id
});
return;
}
// Skip SPA fallback for static assets (files with extensions)
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
// SPA routing: try to serve the exact file first
try {
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
const contentType = getContentType(filePath);
console.log(`Serving file: ${filePath}`);
// Inject preview script into HTML responses
let body: string;
if (contentType === 'text/html') {
const html = new TextDecoder().decode(bytes);
body = encodeBase64(new TextEncoder().encode(injectScript(html)));
} else {
body = encodeBase64(bytes);
}
sendResponse({
jsonrpc: '2.0',
result: {
status: 200,
statusText: 'OK',
headers: {
'Content-Type': getContentType(filePath),
'Content-Type': contentType,
'Cache-Control': 'no-cache',
},
body: encodeBase64(bytes),
body,
},
id
});
@@ -349,6 +416,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
console.log(`Serving index.html fallback for: ${path}`);
// Inject preview script into SPA fallback HTML
const html = new TextDecoder().decode(bytes);
const body = encodeBase64(new TextEncoder().encode(injectScript(html)));
sendResponse({
jsonrpc: '2.0',
result: {
@@ -358,7 +429,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
'Content-Type': 'text/html',
'Cache-Control': 'no-cache',
},
body: encodeBase64(bytes),
body,
},
id
});
@@ -389,32 +460,37 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
id
});
}
}, [projectId, projectsManager, sendResponse, sendError, previewDomain]);
}, [projectId, projectsManager, sendResponse, sendError, previewOrigin, injectScript]);
// Setup messaging protocol for iframe communication
useEffect(() => {
const handleMessage = (event: MessageEvent) => {
// Verify origin for security
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
if (event.origin !== previewOrigin) {
return;
}
const message = event.data;
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return;
// Handle iframe.diy handshake: respond to "ready" with "init"
if (message.method === 'ready') {
sendNotification('init', { version: 1 });
return;
}
if (message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
} else if (message.method === 'console') {
handleConsoleMessage(message);
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
} else if (message.method === 'updateNavigationState') {
handleUpdateNavigationState(message);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, previewOrigin]);
useEffect(() => {
if (selectedFile) {
@@ -645,12 +721,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
)}
>
<iframe
key={projectId}
key={`${projectId}:${iframeReloadKey}`}
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
src={`${previewOrigin}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin allow-forms"
allow="microphone; camera; display-capture; geolocation; clipboard-read; clipboard-write; encrypted-media; fullscreen; autoplay; midi; accelerometer; gyroscope; magnetometer; ambient-light-sensor; payment; usb; xr-spatial-tracking"
/>
</div>
) : (
+38 -271
View File
@@ -1,15 +1,14 @@
// NOTE: This file is stable and usually should not be modified.
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
import React, { useRef, useState, useEffect } from 'react';
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
import React, { useState, useEffect } from 'react';
import { Shield, AlertTriangle, UserPlus, Sparkles } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils';
import LoginPanel from '@/components/auth/LoginPanel';
interface LoginDialogProps {
isOpen: boolean;
@@ -18,47 +17,21 @@ interface LoginDialogProps {
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
};
const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
file?: string;
extension?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const [isExtensionLoading, setIsExtensionLoading] = useState(false);
const [extensionError, setExtensionError] = useState<string | null>(null);
const login = useLoginActions();
// Reset all state when dialog opens/closes
useEffect(() => {
if (isOpen) {
// Reset state when dialog opens
setIsLoading(false);
setIsFileLoading(false);
setNsec('');
setBunkerUri('');
setErrors({});
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
setIsExtensionLoading(false);
setExtensionError(null);
}
}, [isOpen]);
const handleExtensionLogin = async () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
setIsExtensionLoading(true);
setExtensionError(null);
try {
if (!('nostr' in window)) {
@@ -69,107 +42,15 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
onClose();
} catch (e: unknown) {
const error = e as Error;
console.error('Bunker login failed:', error);
console.error('Nsec login failed:', error);
console.error('Extension login failed:', error);
setErrors(prev => ({
...prev,
extension: error instanceof Error ? error.message : 'Extension login failed'
}));
setExtensionError(
error instanceof Error ? error.message : 'Extension login failed',
);
} finally {
setIsLoading(false);
setIsExtensionLoading(false);
}
};
const executeLogin = (key: string) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleKeyLogin = () => {
if (!nsec.trim()) {
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
}
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
executeLogin(nsec);
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim()) {
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
return;
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
return;
}
setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try {
await login.bunker(bunkerUri);
onLogin();
onClose();
// Clear the URI from memory
setBunkerUri('');
} catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
} finally {
setIsLoading(false);
}
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
} else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
} else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
};
reader.readAsText(file);
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
@@ -177,7 +58,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
}
};
const defaultTab = 'nostr' in window ? 'extension' : 'key';
const handleLoggedIn = () => {
onLogin();
onClose();
};
const hasExtension = typeof window !== 'undefined' && 'nostr' in window;
return (
<Dialog open={isOpen} onOpenChange={onClose}>
@@ -225,148 +111,29 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
</div>
</div>
{/* Login Methods */}
<Tabs defaultValue={defaultTab} className="w-full">
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
<TabsTrigger value="extension" className="flex items-center gap-2">
<Shield className="w-4 h-4" />
<span>Extension</span>
</TabsTrigger>
<TabsTrigger value="key" className="flex items-center gap-2">
<KeyRound className="w-4 h-4" />
<span>Key</span>
</TabsTrigger>
<TabsTrigger value="bunker" className="flex items-center gap-2">
<Cloud className="w-4 h-4" />
<span>Bunker</span>
</TabsTrigger>
</TabsList>
<TabsContent value='extension' className='space-y-3 bg-muted'>
{errors.extension && (
{/* Unified login panel — QR + nsec/bunker input + file upload */}
<LoginPanel onLoggedIn={handleLoggedIn} />
{/* Extension login (only shown when a NIP-07 extension is present) */}
{hasExtension && (
<div className='rounded-lg bg-muted p-3 space-y-2'>
{extensionError && (
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertDescription>{errors.extension}</AlertDescription>
<AlertDescription>{extensionError}</AlertDescription>
</Alert>
)}
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
Login with one click using the browser extension
</p>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleExtensionLogin}
disabled={isLoading}
>
{isLoading ? 'Logging in...' : 'Login with Extension'}
</Button>
</div>
</div>
</TabsContent>
<TabsContent value='key' className='space-y-4'>
<div className='space-y-4'>
<div className='space-y-2'>
<label htmlFor='nsec' className='text-sm font-medium'>
Secret Key (nsec)
</label>
<Input
id='nsec'
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
className={`rounded-lg ${
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
}`}
placeholder='nsec1...'
autoComplete="off"
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<Button
className='w-full rounded-full py-3'
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
>
{isLoading ? 'Verifying...' : 'Log In'}
</Button>
<div className='relative'>
<div className='absolute inset-0 flex items-center'>
<div className='w-full border-t border-muted'></div>
</div>
<div className='relative flex justify-center text-xs'>
<span className='px-2 bg-background text-muted-foreground'>
or
</span>
</div>
</div>
<div className='text-center'>
<input
type='file'
accept='.txt'
className='hidden'
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant='outline'
className='w-full'
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
>
<Upload className='w-4 h-4 mr-2' />
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
</Button>
{errors.file && (
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
)}
</div>
</div>
</TabsContent>
<TabsContent value='bunker' className='space-y-3 bg-muted'>
<div className='space-y-2'>
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
Bunker URI
</label>
<Input
id='bunkerUri'
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
errors.bunker ? 'border-red-500' : ''
}`}
placeholder='bunker://'
autoComplete="off"
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<div className="flex justify-center">
<Button
className='w-full rounded-full py-4'
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
>
{isLoading ? 'Connecting...' : 'Login with Bunker'}
</Button>
</div>
</TabsContent>
</Tabs>
<Button
variant='outline'
className='w-full rounded-full'
onClick={handleExtensionLogin}
disabled={isExtensionLoading}
>
<Shield className='w-4 h-4 mr-2' />
{isExtensionLoading ? 'Logging in…' : 'Sign in with browser extension'}
</Button>
</div>
)}
</div>
</DialogContent>
</Dialog>
+427
View File
@@ -0,0 +1,427 @@
import React, { useCallback, useEffect, useRef, useState } from 'react';
import QRCode from 'qrcode';
import { ExternalLink, Loader2, Upload } from 'lucide-react';
import {
generateNostrConnectParams,
generateNostrConnectURI,
type NostrConnectParams,
} from '@nostrify/react/login';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useAppContext } from '@/hooks/useAppContext';
interface LoginPanelProps {
/** Called after a successful login (nostrconnect QR, nsec, bunker URI, or key file). */
onLoggedIn: () => void;
}
const NSEC_REGEX = /^nsec1[a-zA-Z0-9]{58}$/;
type InputKind = 'nsec' | 'bunker' | 'unknown';
const detectInputKind = (value: string): InputKind => {
const trimmed = value.trim();
if (NSEC_REGEX.test(trimmed)) return 'nsec';
if (trimmed.startsWith('bunker://')) return 'bunker';
return 'unknown';
};
// UA-based mobile check. Distinct from the viewport-based `useIsMobile` —
// here we care whether the platform can deep-link into a signer app, not
// whether the window is narrow.
const isMobileDevice = (): boolean => {
if (typeof navigator === 'undefined') return false;
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
};
/**
* Unified login panel for all string-based methods:
* - `nostrconnect://` flow gated behind a button. Desktop reveals a QR code;
* mobile redirects to a signer-app deep-link.
* - A single paste input that accepts either an `nsec1…` secret key OR a
* `bunker://` URI — the type is detected from the string on submit.
* - File upload for plain-text nsec / bunker URI files.
*
* The nostrconnect session is only opened when the user clicks the button
* (so the dialog doesn't open a relay subscription for users who just want
* to paste a key). Panel unmount aborts any in-flight listener.
*/
export const LoginPanel: React.FC<LoginPanelProps> = ({ onLoggedIn }) => {
const login = useLoginActions();
const { config } = useAppContext();
// Session is gated: stays idle until the user clicks the remote-signer
// button. Bumping `sessionToken` while started restarts the session
// (used by "Try again").
const [sessionStarted, setSessionStarted] = useState(false);
const [sessionToken, setSessionToken] = useState(0);
const [nostrConnectUri, setNostrConnectUri] = useState('');
const [qrDataUrl, setQrDataUrl] = useState('');
const [connectError, setConnectError] = useState<string | null>(null);
const [hasOpenedSigner, setHasOpenedSigner] = useState(false);
// Mobile-only: tracks "user pressed Open signer app but the URI isn't
// generated yet — navigate as soon as it is."
const [pendingNavigate, setPendingNavigate] = useState(false);
// Unified text input — accepts nsec or bunker URI, type detected on submit.
const [input, setInput] = useState('');
const [inputError, setInputError] = useState<string | null>(null);
const [isInputLoggingIn, setIsInputLoggingIn] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const abortControllerRef = useRef<AbortController | null>(null);
// Refs so the listener effect can read the latest values without
// re-running on every parent re-render. `config` is rebuilt every render
// by AppProvider, so we must NOT depend on it in the effect's dep array —
// otherwise the in-flight subscription is torn down on each parent render.
const loginRef = useRef(login);
const onLoggedInRef = useRef(onLoggedIn);
const configRef = useRef(config);
useEffect(() => {
loginRef.current = login;
onLoggedInRef.current = onLoggedIn;
configRef.current = config;
});
const isMobile = isMobileDevice();
// Open a nostrconnect session and start listening for the signer. Runs
// only after the user clicks the start button (`sessionStarted=true`),
// and re-runs when `sessionToken` is bumped by "Try again".
useEffect(() => {
if (!sessionStarted) return;
let cancelled = false;
const controller = new AbortController();
abortControllerRef.current?.abort();
abortControllerRef.current = controller;
const run = async () => {
const relayUrls = (configRef.current.relayMetadata?.relays ?? [])
.filter((r) => r.write !== false)
.map((r) => r.url);
if (relayUrls.length === 0) {
if (!cancelled) {
setConnectError(
'No relays configured. Add a relay in settings to use this login method.',
);
}
return;
}
const params: NostrConnectParams = generateNostrConnectParams(relayUrls);
const uri = generateNostrConnectURI(params, {
name: 'Shakespeare',
callback: isMobileDevice()
? `${window.location.origin}/remoteloginsuccess`
: undefined,
});
// Publish the URI ASAP so a pending mobile navigate can fire while
// the QR renders in the background.
if (cancelled) return;
setNostrConnectUri(uri);
setConnectError(null);
// Desktop renders a QR; mobile redirects, so skip the work there.
if (!isMobileDevice()) {
try {
const dataUrl = await QRCode.toDataURL(uri, {
width: 400,
margin: 2,
color: { dark: '#000000', light: '#FFFFFF' },
});
if (cancelled) return;
setQrDataUrl(dataUrl);
} catch (e) {
console.error('Failed to render nostrconnect QR:', e);
}
}
try {
await loginRef.current.nostrconnect(params, controller.signal);
if (cancelled || controller.signal.aborted) return;
onLoggedInRef.current();
} catch (error) {
if (cancelled || controller.signal.aborted) return;
if (error instanceof Error && error.name === 'AbortError') return;
console.error('nostrconnect failed:', error);
setConnectError(
error instanceof Error ? error.message : 'Failed to connect to signer.',
);
}
};
void run();
return () => {
cancelled = true;
controller.abort();
};
// Intentional: deps limited to `sessionStarted` + `sessionToken` so
// parent re-renders don't tear down the in-flight subscription. Config
// + login are read via refs that are updated each render.
}, [sessionStarted, sessionToken]);
// Mobile: once the URI is ready and the user already tapped "Open signer
// app", navigate to the deep-link. Runs once per click; the flag is
// consumed here.
useEffect(() => {
if (!pendingNavigate || !nostrConnectUri || connectError) return;
setPendingNavigate(false);
setHasOpenedSigner(true);
window.location.href = nostrConnectUri;
}, [pendingNavigate, nostrConnectUri, connectError]);
const handleStartDesktopSession = () => {
setSessionStarted(true);
};
const handleOpenSignerApp = () => {
// Mobile: arm the navigate-when-ready effect and start the session.
// If the session is already running (e.g. retry after error), this
// just navigates with the existing URI.
setPendingNavigate(true);
setSessionStarted(true);
};
const handleConnectRetry = useCallback(() => {
setNostrConnectUri('');
setQrDataUrl('');
setConnectError(null);
setHasOpenedSigner(false);
setPendingNavigate(false);
setSessionToken((t) => t + 1);
}, []);
const submitInput = async (rawValue: string) => {
const trimmed = rawValue.trim();
if (!trimmed) {
setInputError('Enter a secret key or bunker URI');
return;
}
const kind = detectInputKind(trimmed);
if (kind === 'unknown') {
setInputError('Unrecognized format. Expected nsec1… or bunker://…');
return;
}
setIsInputLoggingIn(true);
setInputError(null);
try {
if (kind === 'nsec') {
// login.nsec is synchronous but throws on bad keys.
login.nsec(trimmed);
} else {
await login.bunker(trimmed);
}
onLoggedIn();
} catch {
setInputError(
kind === 'nsec'
? "Failed to log in with this key. Please check that it's correct."
: 'Failed to connect to bunker. Please check the URI.',
);
} finally {
setIsInputLoggingIn(false);
}
};
const handleSubmit = () => {
void submitInput(input);
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsFileLoading(true);
setInputError(null);
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string;
if (!content) {
setInputError('Could not read file content.');
return;
}
const trimmed = content.trim();
if (detectInputKind(trimmed) === 'unknown') {
setInputError('File does not contain a valid nsec or bunker URI.');
return;
}
setInput(trimmed);
void submitInput(trimmed);
};
reader.onerror = () => {
setIsFileLoading(false);
setInputError('Failed to read file.');
};
reader.readAsText(file);
// Reset so the same file can be selected again after a failure.
if (fileInputRef.current) fileInputRef.current.value = '';
};
const renderRemoteSignerSection = () => {
// Idle: just a button. Clicking it generates the session and either
// reveals the QR (desktop) or deep-links to a signer app (mobile).
if (!sessionStarted) {
return (
<Button
variant="outline"
onClick={isMobile ? handleOpenSignerApp : handleStartDesktopSession}
className="w-full h-12"
>
<ExternalLink className="w-5 h-5 mr-2" />
{isMobile ? 'Open signer app' : 'Login with remote signer'}
</Button>
);
}
if (connectError) {
return (
<div className="flex flex-col items-center space-y-3 py-4 w-full">
<Alert variant="destructive">
<AlertDescription>{connectError}</AlertDescription>
</Alert>
<Button variant="outline" onClick={handleConnectRetry}>
Try again
</Button>
</div>
);
}
if (isMobile && hasOpenedSigner) {
return (
<div className="flex flex-col items-center space-y-4 py-6 w-full">
<Loader2 className="w-8 h-8 animate-spin text-primary" />
<p className="text-sm text-muted-foreground text-center">
Waiting for signer&hellip;
</p>
<button
type="button"
onClick={handleConnectRetry}
className="text-sm text-primary hover:underline underline-offset-4 font-medium"
>
Cancel
</button>
</div>
);
}
if (!isMobile && qrDataUrl) {
return (
<div className="flex flex-col items-center space-y-4 w-full">
<div className="p-3 bg-white rounded-xl">
<img
src={qrDataUrl}
alt="nostrconnect QR code"
width={200}
height={200}
className="block"
/>
</div>
<p className="text-xs text-muted-foreground text-center max-w-[260px]">
Scan this QR code with your Nostr signer app to log in.
</p>
<button
type="button"
onClick={handleConnectRetry}
className="text-xs text-muted-foreground hover:text-foreground underline underline-offset-4"
>
Generate a new code
</button>
</div>
);
}
// Mobile pre-navigate or desktop pre-QR — short transient state.
return (
<div className="flex items-center justify-center h-[120px]">
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
</div>
);
};
return (
<div className="space-y-4">
{renderRemoteSignerSection()}
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t"></div>
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">
or paste a key or URI
</span>
</div>
</div>
<div className="space-y-2">
<Input
type="password"
value={input}
onChange={(e) => {
setInput(e.target.value);
if (inputError) setInputError(null);
}}
onKeyDown={(e) => {
if (e.key === 'Enter' && input.trim() && !isInputLoggingIn) {
e.preventDefault();
handleSubmit();
}
}}
placeholder="nsec1… or bunker://…"
className={inputError ? 'border-red-500' : ''}
autoComplete="off"
/>
{inputError && (
<p className="text-sm text-red-500">{inputError}</p>
)}
</div>
<div className="flex space-x-2">
<Button
onClick={handleSubmit}
disabled={isInputLoggingIn || isFileLoading || !input.trim()}
className="flex-1"
>
{isInputLoggingIn ? 'Adding…' : 'Add account'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant="outline"
onClick={() => fileInputRef.current?.click()}
disabled={isInputLoggingIn || isFileLoading}
className="px-3"
title="Upload a file containing an nsec or bunker URI"
>
{isFileLoading ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
<Upload className="w-4 h-4" />
)}
</Button>
</div>
</div>
);
};
export default LoginPanel;
+41 -279
View File
@@ -1,13 +1,7 @@
import React, { useState, useEffect, useRef } from 'react';
import { Cloud, Upload } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import React, { useState, useEffect } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
// Alert components removed as they're not used in the simplified design
import { useLoginActions } from '@/hooks/useLoginActions';
import { cn } from '@/lib/utils';
// Only using key-add step now
import LoginPanel from '@/components/auth/LoginPanel';
interface SimpleLoginDialogProps {
isOpen: boolean;
@@ -16,55 +10,27 @@ interface SimpleLoginDialogProps {
onSignup?: () => void;
}
const validateNsec = (nsec: string) => {
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
};
const validateBunkerUri = (uri: string) => {
return uri.startsWith('bunker://');
};
const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
isOpen,
onClose,
onLogin,
onSignup
}) => {
// Removed step state - we only have one step now
const [isLoading, setIsLoading] = useState(false);
const [isFileLoading, setIsFileLoading] = useState(false);
const [nsec, setNsec] = useState('');
const [bunkerUri, setBunkerUri] = useState('');
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
const [errors, setErrors] = useState<{
nsec?: string;
bunker?: string;
extension?: string;
file?: string;
}>({});
const fileInputRef = useRef<HTMLInputElement>(null);
const [isExtensionLoading, setIsExtensionLoading] = useState(false);
const [extensionError, setExtensionError] = useState<string | null>(null);
const login = useLoginActions();
// Reset state when dialog opens/closes
useEffect(() => {
if (isOpen) {
setIsLoading(false);
setIsFileLoading(false);
setNsec('');
setBunkerUri('');
setActiveTab('nsec');
setErrors({});
// Reset file input
if (fileInputRef.current) {
fileInputRef.current.value = '';
}
setIsExtensionLoading(false);
setExtensionError(null);
}
}, [isOpen]);
const handleExtensionLogin = async () => {
setIsLoading(true);
setErrors(prev => ({ ...prev, extension: undefined }));
setIsExtensionLoading(true);
setExtensionError(null);
try {
if (!('nostr' in window)) {
@@ -75,103 +41,12 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
onClose();
} catch (e: unknown) {
const error = e as Error;
setErrors(prev => ({
...prev,
extension: error instanceof Error ? error.message : 'Extension login failed'
}));
setExtensionError(error instanceof Error ? error.message : 'Extension login failed');
} finally {
setIsLoading(false);
setIsExtensionLoading(false);
}
};
const handleKeyLogin = () => {
if (!nsec.trim()) {
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
return;
}
if (!validateNsec(nsec)) {
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
return;
}
executeLogin(nsec);
};
const handleBunkerLogin = async () => {
if (!bunkerUri.trim()) {
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
return;
}
if (!validateBunkerUri(bunkerUri)) {
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
return;
}
setIsLoading(true);
setErrors(prev => ({ ...prev, bunker: undefined }));
try {
await login.bunker(bunkerUri);
onLogin();
onClose();
setBunkerUri('');
} catch {
setErrors(prev => ({
...prev,
bunker: 'Failed to connect to bunker. Please check the URI.'
}));
} finally {
setIsLoading(false);
}
};
const executeLogin = (key: string) => {
setIsLoading(true);
setErrors({});
// Use a timeout to allow the UI to update before the synchronous login call
setTimeout(() => {
try {
login.nsec(key);
onLogin();
onClose();
} catch {
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
setIsLoading(false);
}
}, 50);
};
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
setIsFileLoading(true);
setErrors({});
const reader = new FileReader();
reader.onload = (event) => {
setIsFileLoading(false);
const content = event.target?.result as string;
if (content) {
const trimmedContent = content.trim();
if (validateNsec(trimmedContent)) {
executeLogin(trimmedContent);
} else {
setErrors({ file: 'File does not contain a valid secret key.' });
}
} else {
setErrors({ file: 'Could not read file content.' });
}
};
reader.onerror = () => {
setIsFileLoading(false);
setErrors({ file: 'Failed to read file.' });
};
reader.readAsText(file);
};
const handleSignupClick = () => {
onClose();
if (onSignup) {
@@ -179,6 +54,11 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
}
};
const handleLoggedIn = () => {
onLogin();
onClose();
};
return (
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent className="max-w-sm">
@@ -186,159 +66,41 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
<DialogTitle className="text-center">Log in</DialogTitle>
</DialogHeader>
<div className="flex flex-col items-center space-y-6 py-6">
<div className="flex flex-col items-center space-y-6 py-4">
<div className="text-center">
<h3 className="font-semibold mb-2">Welcome back to Shakespeare</h3>
<p className="text-sm text-muted-foreground">Sign in to your existing account</p>
</div>
<div className="w-40 h-40 flex items-center justify-center">
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
<span className="text-8xl">🔑</span>
</div>
<div className="w-full">
<LoginPanel onLoggedIn={handleLoggedIn} />
</div>
<div className="w-full space-y-4">
{/* Tab selector */}
<div className="flex space-x-1 bg-muted rounded-lg p-1">
<button
onClick={() => setActiveTab('nsec')}
className={cn(
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
activeTab === 'nsec'
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
)}
>
Secret Key
</button>
<button
onClick={() => setActiveTab('bunker')}
className={cn(
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
activeTab === 'bunker'
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
)}
>
Bunker
</button>
</div>
{activeTab === 'nsec' && (
<div className="space-y-4">
<div className="space-y-2">
<Input
type="password"
value={nsec}
onChange={(e) => {
setNsec(e.target.value);
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
}}
placeholder="nsec1..."
className={errors.nsec ? 'border-red-500' : ''}
/>
{errors.nsec && (
<p className="text-sm text-red-500">{errors.nsec}</p>
)}
</div>
<div className="flex space-x-2">
<Button
size="lg"
onClick={handleKeyLogin}
disabled={isLoading || !nsec.trim()}
className="flex-1"
>
{isLoading ? 'Verifying...' : 'Add Key'}
</Button>
<input
type="file"
accept=".txt"
className="hidden"
ref={fileInputRef}
onChange={handleFileUpload}
/>
<Button
variant="outline"
size="lg"
onClick={() => fileInputRef.current?.click()}
disabled={isLoading || isFileLoading}
className="px-3"
>
<Upload className="w-4 h-4" />
</Button>
</div>
{errors.file && (
<p className="text-sm text-red-500 text-center">{errors.file}</p>
)}
</div>
)}
{activeTab === 'bunker' && (
<div className="space-y-4">
<div className="space-y-2">
<Input
value={bunkerUri}
onChange={(e) => {
setBunkerUri(e.target.value);
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
}}
placeholder="bunker://"
className={errors.bunker ? 'border-red-500' : ''}
/>
{errors.bunker && (
<p className="text-sm text-red-500">{errors.bunker}</p>
)}
</div>
<Button
size="lg"
onClick={handleBunkerLogin}
disabled={isLoading || !bunkerUri.trim()}
className="w-full"
{window.nostr && (
<div className="w-full rounded-lg bg-muted p-3">
<p className="text-xs text-center">
<button
onClick={handleExtensionLogin}
className="text-blue-500 hover:underline disabled:opacity-50"
disabled={isExtensionLoading}
>
<Cloud className="w-4 h-4 mr-2" />
{isLoading ? 'Connecting...' : 'Connect'}
</Button>
</div>
)}
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t"></div>
</div>
<div className="relative flex justify-center text-xs uppercase">
<span className="bg-background px-2 text-muted-foreground">or</span>
</div>
{isExtensionLoading ? 'Connecting…' : 'Sign in with browser extension'}
</button>
</p>
{extensionError && (
<p className="text-xs text-red-500 text-center mt-2">{extensionError}</p>
)}
</div>
)}
{/* Extension indicator - only show if extension is detected */}
{window.nostr && (
<div className="rounded-lg bg-muted p-3">
<p className="text-xs text-center">
<button
onClick={handleExtensionLogin}
className="text-blue-500 hover:underline"
disabled={isLoading}
>
Sign in with browser extension
</button>
</p>
</div>
)}
<div className="flex justify-center space-x-2 text-xs">
<span className="text-muted-foreground">New to Shakespeare?</span>
<button
onClick={handleSignupClick}
className="text-blue-500 hover:underline"
>
Create Account
</button>
</div>
<div className="flex justify-center space-x-2 text-xs">
<span className="text-muted-foreground">New to Shakespeare?</span>
<button
onClick={handleSignupClick}
className="text-blue-500 hover:underline"
>
Create Account
</button>
</div>
</div>
</DialogContent>
@@ -346,4 +108,4 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
);
};
export default SimpleLoginDialog;
export default SimpleLoginDialog;
+121 -39
View File
@@ -17,10 +17,11 @@ import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useGit } from '@/hooks/useGit';
import { NostrURI } from '@/lib/NostrURI';
import { Link } from 'react-router-dom';
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
import type { DeployProvider, NpanelProvider } from '@/contexts/DeploySettingsContext';
import { NpanelMigrationDialog } from '@/components/deploy/NpanelMigrationDialog';
import type { PresetDeployProvider } from '@/lib/deploy/types';
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NpanelDeployForm } from '@/components/deploy/NpanelDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
@@ -29,7 +30,7 @@ import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
import { RailwayDeployForm } from '@/components/deploy/RailwayDeployForm';
import { cn } from '@/lib/utils';
import { DeployAdapter } from '@/lib/deploy/types';
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
import { NpanelAdapter } from '@/lib/deploy/NpanelAdapter';
import { NsiteAdapter } from '@/lib/deploy/NsiteAdapter';
import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
@@ -74,12 +75,11 @@ function renderProviderIcon(provider: DeployProvider, preset: PresetDeployProvid
// Use baseURL from configured provider, falling back to preset baseURL
const baseURL = ('baseURL' in provider && provider.baseURL) || preset?.baseURL;
// For Shakespeare, special handling for host field
const shakespeareUrl = provider.type === 'shakespeare' && 'host' in provider && provider.host
? normalizeUrl(provider.host)
: undefined;
// A gateway is recognised by the domain it serves, not by its API origin —
// that is the name the user picked it for and the one with an icon.
const gatewayUrl = provider.type === 'npanel' ? normalizeUrl(provider.domain) : undefined;
const url = shakespeareUrl || baseURL;
const url = gatewayUrl || baseURL;
if (url) {
return (
@@ -100,8 +100,10 @@ interface DeployStepsProps {
onClose: () => void;
}
interface ShakespeareFormData {
interface NpanelFormData {
subdomain: string;
siteTitle: string;
siteDescription: string;
}
interface NsiteFormData {
@@ -152,7 +154,25 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const [isDeploying, setIsDeploying] = useState(false);
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
const [error, setError] = useState<string | null>(null);
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
const [isNpanelFormValid, setIsNpanelFormValid] = useState(true);
/**
* The gateway whose held names are being looked at, if any.
*
* Owned here rather than by the name field, because what someone recognising
* one of their names wants is usually all of them, and because the dialog
* that hands them back outlives the field that prompted it.
*/
const [migratingProvider, setMigratingProvider] = useState<NpanelProvider | null>(null);
/**
* Whether the deploy failed because the gateway is holding the name for this
* user, which is a refusal with something to do about it.
*
* Read off the sentence npanel sent rather than a status code, since the 409
* it arrives as also covers a name somebody else holds and a name that is
* simply configured already.
*/
const heldName = error !== null && /being held for you/i.test(error);
// .nsite/config.json state — loaded once on mount, used to skip config form on re-deploy
const [nsiteVfsConfig, setNsiteVfsConfig] = useState<NsiteVfsConfig | null>(null);
@@ -187,8 +207,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
}, [fs, projectsPath, projectId]);
// Provider-specific form data
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
const [npanelForm, setNpanelForm] = useState<NpanelFormData>({
subdomain: projectId,
siteTitle: projectName || projectId,
siteDescription: '',
});
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
siteTitle: '',
@@ -245,18 +267,36 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
let adapter: DeployAdapter;
if (selectedProvider.type === 'shakespeare') {
if (selectedProvider.type === 'npanel') {
if (!user) {
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
throw new Error('You must be logged in with Nostr to deploy here.');
}
const shakespeareProvider = selectedProvider;
adapter = new ShakespeareAdapter({
const npanelProvider = selectedProvider;
const subdomain = npanelForm.subdomain.trim();
if (!subdomain) {
throw new Error('Choose an address for this site.');
}
const sourceUrl = await resolveNsiteSourceUrl(
await git.getRemoteURL(projectPath, 'origin')
);
adapter = new NpanelAdapter({
fs,
nostr,
signer: user.signer,
host: shakespeareProvider.host,
subdomain: shakespeareForm.subdomain || undefined,
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
dashboardHost: npanelProvider.dashboardHost,
domain: npanelProvider.domain,
subdomain,
// The gateway serves the site, so it is also the gateway whose URL the
// underlying nsite deploy reports.
gateway: npanelProvider.domain,
relayUrls: npanelProvider.relayUrls,
blossomServers: npanelProvider.blossomServers,
siteTitle: npanelForm.siteTitle || undefined,
siteDescription: npanelForm.siteDescription || undefined,
sourceUrl,
});
} else if (selectedProvider.type === 'nsite') {
const nsiteProvider = selectedProvider;
@@ -375,12 +415,14 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
});
// Save project-specific settings (updateSettings now automatically sets currentProvider)
if (selectedProvider.type === 'shakespeare') {
if (selectedProvider.type === 'npanel') {
await updateProjectSettings(selectedProviderId, {
type: 'shakespeare',
type: 'npanel',
url: result.url,
data: {
subdomain: shakespeareForm.subdomain || undefined,
subdomain: npanelForm.subdomain.trim() || undefined,
siteTitle: npanelForm.siteTitle || undefined,
siteDescription: npanelForm.siteDescription || undefined,
},
});
} else if (selectedProvider.type === 'nsite') {
@@ -516,7 +558,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
setDeployResult(null);
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNpanelForm({ subdomain: projectId, siteTitle: projectName || projectId, siteDescription: '' });
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '' });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
@@ -528,12 +570,20 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
onClose();
};
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
setShakespeareForm({ subdomain });
const handleNpanelSubdomainChange = useCallback((subdomain: string) => {
setNpanelForm(prev => ({ ...prev, subdomain }));
}, []);
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
setIsShakespeareFormValid(isValid);
const handleNpanelSiteTitleChange = useCallback((siteTitle: string) => {
setNpanelForm(prev => ({ ...prev, siteTitle }));
}, []);
const handleNpanelSiteDescriptionChange = useCallback((siteDescription: string) => {
setNpanelForm(prev => ({ ...prev, siteDescription }));
}, []);
const handleNpanelValidationChange = useCallback((isValid: boolean) => {
setIsNpanelFormValid(isValid);
}, []);
const handleNsiteSiteTitleChange = useCallback((siteTitle: string) => {
@@ -578,18 +628,25 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
const renderProviderFields = () => {
if (!selectedProvider) return null;
if (selectedProvider.type === 'shakespeare') {
const shakespeareProvider = selectedProvider;
if (selectedProvider.type === 'npanel') {
const npanelProvider = selectedProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedSubdomain = savedConfig?.type === 'shakespeare' ? savedConfig.data.subdomain : undefined;
const saved = savedConfig?.type === 'npanel' ? savedConfig.data : undefined;
return (
<ShakespeareDeployForm
host={shakespeareProvider.host}
<NpanelDeployForm
dashboardHost={npanelProvider.dashboardHost}
domain={npanelProvider.domain}
projectId={projectId}
savedSubdomain={savedSubdomain}
onSubdomainChange={handleShakespeareSubdomainChange}
onValidationChange={handleShakespeareValidationChange}
projectName={projectName}
savedSubdomain={saved?.subdomain}
savedSiteTitle={saved?.siteTitle}
savedSiteDescription={saved?.siteDescription}
onSubdomainChange={handleNpanelSubdomainChange}
onSiteTitleChange={handleNpanelSiteTitleChange}
onSiteDescriptionChange={handleNpanelSiteDescriptionChange}
onValidationChange={handleNpanelValidationChange}
onTakeBackSites={() => setMigratingProvider(npanelProvider)}
/>
);
}
@@ -612,6 +669,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
<span className="font-medium">{nsiteVfsConfig.title}</span>
</div>
)}
<div className="flex justify-between">
<span className="text-muted-foreground">Relays</span>
<span className="font-medium">{relayCount} configured</span>
@@ -798,6 +856,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
@@ -904,11 +963,11 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
{selectedProvider && renderProviderFields()}
{selectedProvider?.type === 'shakespeare' && !user && (
{selectedProvider?.type === 'npanel' && !user && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
You must be logged in with Nostr to publish a site.{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline"
@@ -939,7 +998,22 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
<AlertDescription className="space-y-2">
<p>{error}</p>
{/* The gateway refuses a name it is holding for this user
and says to take it back instead. Saying so and leaving
them to find out where is the worst of both. */}
{heldName && selectedProvider?.type === 'npanel' && (
<Button
type="button"
variant="outline"
size="sm"
onClick={() => setMigratingProvider(selectedProvider)}
>
Take back your sites
</Button>
)}
</AlertDescription>
</Alert>
)}
@@ -948,8 +1022,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
onClick={handleDeploy}
disabled={
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'npanel' && !user) ||
(selectedProvider.type === 'npanel' && !isNpanelFormValid) ||
(selectedProvider.type === 'nsite' && !user) ||
(selectedProvider.type === 'nsite' && !nsiteForm.dTag) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
@@ -976,6 +1050,14 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
)}
</div>
)}
{migratingProvider && (
<NpanelMigrationDialog
open
onOpenChange={(open) => !open && setMigratingProvider(null)}
provider={migratingProvider}
/>
)}
</div>
);
}
+267
View File
@@ -0,0 +1,267 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { AlertCircle, Check, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { checkNameAvailable, type NameAvailability } from '@/lib/deploy/NpanelAdapter';
/** How long typing has to stop before the gateway is asked about a name. */
const AVAILABILITY_DEBOUNCE_MS = 400;
interface NpanelDeployFormProps {
/** The gateway's API origin, e.g. `npanel.shakespeare.to`. */
dashboardHost: string;
/** The domain sites are served under, e.g. `shakespeare.wtf`. */
domain: string;
/** Falls back to the project id when nothing has been deployed yet. */
projectId: string;
projectName: string;
savedSubdomain?: string;
savedSiteTitle?: string;
savedSiteDescription?: string;
onSubdomainChange: (subdomain: string) => void;
onSiteTitleChange: (title: string) => void;
onSiteDescriptionChange: (description: string) => void;
onValidationChange?: (isValid: boolean) => void;
/**
* Open the list of names this gateway is holding for whoever signs in.
*
* Passed in rather than opened here: recognising one name is usually not the
* whole of what somebody has waiting, and the dialog that hands them all back
* belongs above this field rather than inside it.
*/
onTakeBackSites?: () => void;
}
/** What the field is currently saying about the name in it. */
type NameState =
| { kind: 'empty' }
| { kind: 'mine' }
| { kind: 'waiting' }
| { kind: 'checking' }
| { kind: 'free' }
| { kind: 'unavailable'; message: string };
function describe(availability: NameAvailability, domain: string): NameState {
// A name the gateway recognises as this user's own. It is spoken for, and
// they are who it is spoken for by — deploying updates the site already
// there rather than taking anything.
if (availability.reason === 'mine') return { kind: 'mine' };
// Theirs from before the gateway, and still held for them. Not somewhere
// they can deploy until they take it back, which is a thing they can do
// from here rather than a wall.
if (availability.reason === 'waiting') return { kind: 'waiting' };
if (availability.available) return { kind: 'free' };
if (availability.reason === 'taken') {
return { kind: 'unavailable', message: `That name is taken on ${domain}. Try another.` };
}
return { kind: 'unavailable', message: availability.error ?? 'That name cannot be used.' };
}
export function NpanelDeployForm({
dashboardHost,
domain,
projectId,
projectName,
savedSubdomain,
savedSiteTitle,
savedSiteDescription,
onSubdomainChange,
onSiteTitleChange,
onSiteDescriptionChange,
onValidationChange,
onTakeBackSites,
}: NpanelDeployFormProps) {
const { user } = useCurrentUser();
const [subdomain, setSubdomain] = useState(savedSubdomain || projectId);
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
const [nameState, setNameState] = useState<NameState>({ kind: 'empty' });
// Keyed by provider id in DeploySteps, so this runs once with fresh props.
const initializedRef = useRef(false);
const syncToParent = useCallback(() => {
if (initializedRef.current) return;
initializedRef.current = true;
onSubdomainChange(savedSubdomain || projectId);
onSiteTitleChange(savedSiteTitle ?? projectName);
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
}, [
savedSubdomain,
savedSiteTitle,
savedSiteDescription,
projectId,
projectName,
onSubdomainChange,
onSiteTitleChange,
onSiteDescriptionChange,
]);
useEffect(() => {
syncToParent();
}, [syncToParent]);
// The name this project already deployed to is not "taken" — it is theirs,
// and asking the gateway would truthfully say taken and alarm them about
// their own site. Compared trimmed, since that is what gets deployed: a
// trailing space is not a different name.
const trimmed = subdomain.trim();
const isOwnName = Boolean(savedSubdomain) && trimmed === savedSubdomain;
useEffect(() => {
if (!trimmed) {
setNameState({ kind: 'empty' });
return;
}
if (isOwnName) {
setNameState({ kind: 'mine' });
return;
}
setNameState({ kind: 'checking' });
const controller = new AbortController();
const timer = setTimeout(async () => {
// Signed, where there is someone to sign: a name this user owns but this
// project has never deployed to — one they took back through the
// migration — is otherwise indistinguishable from a stranger's.
const availability = await checkNameAvailable(
dashboardHost,
`${trimmed}.${domain}`,
controller.signal,
user?.signer,
);
if (!controller.signal.aborted) setNameState(describe(availability, domain));
}, AVAILABILITY_DEBOUNCE_MS);
return () => {
controller.abort();
clearTimeout(timer);
};
}, [trimmed, isOwnName, dashboardHost, domain, user?.signer]);
// A name still being checked stays deployable: the gateway decides for real
// when the deploy runs, and blocking the button on an in-flight request would
// make the form feel stuck on a slow connection.
// A name still waiting is not one to deploy to: the gateway would refuse,
// because taking it back is what turns it into somewhere this user can
// publish. The field says so and offers the step rather than the refusal.
const isValid =
subdomain.trim() !== '' && nameState.kind !== 'unavailable' && nameState.kind !== 'waiting';
useEffect(() => {
onValidationChange?.(isValid);
}, [isValid, onValidationChange]);
const handleSubdomainChange = (value: string) => {
setSubdomain(value);
onSubdomainChange(value);
};
const handleSiteTitleChange = (value: string) => {
setSiteTitle(value);
onSiteTitleChange(value);
};
const handleSiteDescriptionChange = (value: string) => {
setSiteDescription(value);
onSiteDescriptionChange(value);
};
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="npanel-subdomain">Address</Label>
<div className="flex items-center gap-2">
<Input
id="npanel-subdomain"
value={subdomain}
onChange={(e) => handleSubdomainChange(e.target.value)}
placeholder={projectId}
className={nameState.kind === 'unavailable' ? 'border-destructive' : ''}
/>
<span className="text-sm text-muted-foreground font-mono whitespace-nowrap">
.{domain}
</span>
</div>
{nameState.kind === 'checking' && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" />
<span>Checking availability…</span>
</div>
)}
{nameState.kind === 'free' && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<Check className="h-3 w-3" />
<span>
<span className="font-mono">{subdomain.trim()}.{domain}</span> is available.
</span>
</div>
)}
{nameState.kind === 'mine' && (
<p className="text-xs text-muted-foreground">
Updating <span className="font-mono">{subdomain.trim()}.{domain}</span>.
</p>
)}
{nameState.kind === 'waiting' && (
<div className="rounded-md border border-dashed p-3 space-y-2">
<p className="text-sm">
<span className="font-mono">{subdomain.trim()}.{domain}</span> is being held for you.
</p>
<p className="text-xs text-muted-foreground">
You published it before {domain} moved to this gateway. It is being served from an
archive until you take it back, which publishes your own copy and points the name at
it.
</p>
{onTakeBackSites && (
<Button type="button" variant="outline" size="sm" onClick={onTakeBackSites}>
Take back your sites
</Button>
)}
</div>
)}
{nameState.kind === 'unavailable' && (
<div className="flex items-start gap-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
<span>{nameState.message}</span>
</div>
)}
</div>
<div className="space-y-2">
<Label htmlFor="npanel-title">Site Title</Label>
<Input
id="npanel-title"
value={siteTitle}
onChange={(e) => handleSiteTitleChange(e.target.value)}
placeholder="My Nostr Site"
/>
</div>
<div className="space-y-2">
<Label htmlFor="npanel-description">
Description <span className="text-muted-foreground font-normal">(optional)</span>
</Label>
<Textarea
id="npanel-description"
value={siteDescription}
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
placeholder="A short description of this site…"
rows={3}
/>
</div>
</div>
);
}
@@ -0,0 +1,745 @@
import { useState } from 'react';
import { useQueryClient } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
import { AlertCircle, Check, ExternalLink, Eye, Loader2, Rocket, Tag, Trash2 } from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNpanelClaims, type NpanelClaimPlan, type NpanelTakenSite } from '@/hooks/useNpanelClaims';
import type { NpanelProvider } from '@/contexts/DeploySettingsContext';
import { claimNpanelHostname, deleteNpanelClaim } from '@/lib/deploy/npanelApi';
import {
NAMED_SITE_KIND,
nsitePreviewUrl,
republishTags,
retitleTags,
sitePreviewUrl,
} from '@/lib/deploy/npanelMigration';
import { checkRelayCoverage, forwardMissing, host, publishToRelays } from '@/lib/deploy/publishToRelays';
/** Where a single name has got to. */
type RowStatus =
| { kind: 'waiting' }
| { kind: 'publishing' }
| { kind: 'claiming' }
| { kind: 'deleting' }
| { kind: 'deleted'; note?: string }
| { kind: 'done'; partial?: string }
| { kind: 'failed'; error: string };
/** A name a person has asked to delete, and has not confirmed yet. */
interface PendingDeletion {
hostname: string;
/** Whether a copy of the site is published under their own key. */
published: boolean;
}
/** What the last coverage run found, as a sentence per relay. */
interface CoverageReport {
lines: string[];
}
interface NpanelMigrationDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
provider: NpanelProvider;
}
function describeStep(claim: NpanelClaimPlan): string {
switch (claim.step.kind) {
case 'claim':
return claim.step.reason === 'mine'
? 'Already published under your key — only the record changes.'
: 'You already publish a site under this name; the address will point at it.';
case 'republish':
return 'A copy will be published under your key, then the name repointed.';
case 'blocked':
return claim.step.reason;
}
}
/** The `d` tag of an event, which for a named site is the site's identifier. */
function eventIdentifier(event: NostrEvent): string {
return event.tags.find(([name]) => name === 'd')?.[1] ?? '';
}
/** "took 3 of 5 relays", where that is worth saying. */
function coverageNote(accepted: string[], rejected: { url: string; reason: string }[]): string | undefined {
if (!rejected.length) return undefined;
const total = accepted.length + rejected.length;
return `${accepted.length} of ${total} relays took it — ${host(rejected[0].url)}: ${rejected[0].reason}`;
}
export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMigrationDialogProps) {
const { user } = useCurrentUser();
const { nostr } = useNostr();
const queryClient = useQueryClient();
const { data, isLoading, error } = useNpanelClaims(open ? provider : undefined);
const [statuses, setStatuses] = useState<Record<string, RowStatus>>({});
const [running, setRunning] = useState<null | 'migrate' | 'titles' | 'coverage' | 'row'>(null);
const [coverage, setCoverage] = useState<CoverageReport | null>(null);
const [confirming, setConfirming] = useState<PendingDeletion | null>(null);
/** Whether anything has happened that the cached lists do not know about. */
const [dirty, setDirty] = useState(false);
const claims = data?.waiting ?? [];
const actionable = claims.filter((claim) => claim.step.kind !== 'blocked');
const blocked = claims.filter((claim) => claim.step.kind === 'blocked');
const retitlable = (data?.taken ?? []).filter((site) => site.needsTitle && !site.stray);
const strays = (data?.taken ?? []).filter((site) => site.stray);
const done = Object.values(statuses).filter((status) => status.kind === 'done').length;
const deleted = Object.values(statuses).filter((status) => status.kind === 'deleted').length;
const failed = Object.values(statuses).filter((status) => status.kind === 'failed').length;
const setStatus = (hostname: string, status: RowStatus) => {
setStatuses((previous) => ({ ...previous, [hostname]: status }));
};
/** Whether a row has already reached a state no further action applies to. */
const settled = (hostname: string): boolean => {
const kind = statuses[hostname]?.kind;
return kind === 'done' || kind === 'deleted';
};
/**
* Take back one name.
*
* Publish before claiming, always: a hostname pointed at an event the gateway
* has never seen serves nothing until it catches up, and the order that gap
* is smallest in is this one.
*/
const migrate = async (claim: NpanelClaimPlan): Promise<void> => {
if (!user || claim.step.kind === 'blocked') return;
let address: string;
let note: string | undefined;
if (claim.step.kind === 'republish') {
setStatus(claim.hostname, { kind: 'publishing' });
const event = await user.signer.signEvent({
kind: NAMED_SITE_KIND,
content: claim.step.manifest.content,
created_at: Math.floor(Date.now() / 1000),
tags: republishTags(claim.step.manifest, claim.step.identifier, {
title: claim.suggestedTitle,
description: claim.suggestedDescription,
}),
});
const published = await publishToRelays(nostr, event, provider.relayUrls);
note = coverageNote(published.accepted, published.rejected);
address = `${NAMED_SITE_KIND}:${user.pubkey}:${claim.step.identifier}`;
} else {
address = claim.step.address;
}
setStatus(claim.hostname, { kind: 'claiming' });
await claimNpanelHostname(provider.dashboardHost, user.signer, claim.hostname, address);
setStatus(claim.hostname, { kind: 'done', partial: note });
};
/** Republish one already-claimed site under the name it chose for itself. */
const retitle = async (site: NpanelTakenSite): Promise<void> => {
if (!user) return;
setStatus(site.hostname, { kind: 'publishing' });
const event = await user.signer.signEvent({
kind: site.event.kind,
content: site.event.content,
created_at: Math.floor(Date.now() / 1000),
tags: retitleTags(site.event, {
title: site.suggestedTitle,
description: site.suggestedDescription,
}),
});
const published = await publishToRelays(nostr, event, provider.relayUrls);
setStatus(site.hostname, {
kind: 'done',
partial: coverageNote(published.accepted, published.rejected),
});
};
/**
* Give a name up rather than take it back.
*
* Only npanel forgets anything. The archive's manifest stays on relays under
* the archive's key, and a copy published under the user's own key stays
* theirs — what ends is this gateway serving the name and holding it for
* them. Saying otherwise in the confirmation would be a promise nothing here
* can keep.
*/
const removeClaim = async (hostname: string): Promise<void> => {
if (!user) return;
setStatus(hostname, { kind: 'deleting' });
await deleteNpanelClaim(provider.dashboardHost, user.signer, hostname);
setStatus(hostname, { kind: 'deleted' });
};
/**
* Undo a manifest published for a name that can never load.
*
* Both halves, because there is no useful middle state: a relay is asked to
* forget the event, and the gateway to forget the name. Keeping the record
* for a hostname whose TLS handshake has always failed and always will would
* leave a row in this list forever with nothing to do about it.
*
* The gateway going second is deliberate — it is the recoverable half. A
* deletion request cannot be taken back, so it is the one that has to be
* worth making on its own.
*/
const removeStray = async (site: NpanelTakenSite): Promise<void> => {
if (!user) return;
setStatus(site.hostname, { kind: 'publishing' });
const deletion = await user.signer.signEvent({
kind: 5,
content: 'Published for a hostname no certificate can cover.',
created_at: Math.floor(Date.now() / 1000),
tags: [
['e', site.event.id],
['a', `${site.event.kind}:${user.pubkey}:${eventIdentifier(site.event)}`],
['k', String(site.event.kind)],
],
});
await publishToRelays(nostr, deletion, provider.relayUrls);
await removeClaim(site.hostname);
setStatus(site.hostname, { kind: 'deleted', note: 'Retracted, and taken off the gateway.' });
};
/** Run `action` over `rows`, one at a time, recording failures per row. */
const runEach = async <T,>(
rows: T[],
key: (row: T) => string,
action: (row: T) => Promise<void>,
): Promise<void> => {
for (const row of rows) {
if (settled(key(row))) continue;
try {
await action(row);
} catch (err) {
setStatus(key(row), {
kind: 'failed',
error: err instanceof Error ? err.message : 'Failed',
});
}
}
};
/**
* One row's action, on its own.
*
* Still holds the whole dialog while it runs. A signer answers one request at
* a time whatever the UI allows, and two buttons that look live but queue
* behind each other read as a hang.
*/
const runRow = async (hostname: string, action: () => Promise<void>): Promise<void> => {
setRunning('row');
try {
await action();
// Deliberately not refetched here. Somebody clearing out twenty sites
// clicks twenty times, and re-reading the list after each one would cost
// a signature and a relay round trip to learn what the row already says.
// The list is caught up when the dialog closes.
setDirty(true);
} catch (err) {
setStatus(hostname, { kind: 'failed', error: err instanceof Error ? err.message : 'Failed' });
}
setRunning(null);
};
const migrateAll = async () => {
setRunning('migrate');
// One at a time: a remote signer answers one request at a time anyway, and
// a failure halfway through should leave a list somebody can read rather
// than a hundred simultaneous errors.
await runEach(actionable, (claim) => claim.hostname, migrate);
setRunning(null);
setDirty(true);
// Whatever succeeded is no longer waiting, and whatever failed still is.
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
};
const fixTitles = async () => {
setRunning('titles');
await runEach(retitlable, (site) => site.hostname, retitle);
setRunning(null);
setDirty(true);
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
};
/**
* Fill in the relays that are missing these manifests.
*
* Costs no signatures: the events go out exactly as they are, ids and
* signatures unchanged, so a relay that already has one says `duplicate:`
* and a relay that refused before says why.
*/
const fixCoverage = async () => {
const events = data?.events ?? [];
if (!events.length) return;
setRunning('coverage');
setCoverage(null);
try {
const found = await checkRelayCoverage(
nostr,
provider.relayUrls,
events.map((event) => event.id),
);
const result = await forwardMissing(nostr, found, events);
const lines = found.map((relay) => {
const had = relay.present.size;
const sent = result.filled.get(relay.url) ?? 0;
const why = result.refused.get(relay.url);
if (why) return `${host(relay.url)}: had ${had} of ${events.length}, refused the rest — ${why}`;
if (sent) return `${host(relay.url)}: had ${had} of ${events.length}, sent ${sent} more`;
return `${host(relay.url)}: has all ${events.length}`;
});
setCoverage({ lines });
} catch (err) {
setCoverage({ lines: [err instanceof Error ? err.message : 'Could not check relay coverage.'] });
}
setRunning(null);
};
const renderStatus = (hostname: string, fallback: string) => {
const status = statuses[hostname] ?? { kind: 'waiting' as const };
switch (status.kind) {
case 'publishing':
return (
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" /> Publishing…
</span>
);
case 'claiming':
return (
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" /> Claiming…
</span>
);
case 'deleting':
return (
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Loader2 className="h-3 w-3 animate-spin" /> Deleting…
</span>
);
case 'deleted':
return (
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Check className="h-3 w-3 shrink-0" />
{status.note ?? `Deleted from ${provider.domain}.`}
</span>
);
case 'done':
return (
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
<Check className="h-3 w-3 shrink-0" />
{status.partial ? (
<span>{status.partial}</span>
) : (
<a
href={`https://${hostname}`}
target="_blank"
rel="noreferrer"
className="flex items-center gap-1 hover:text-foreground"
>
Yours <ExternalLink className="h-3 w-3" />
</a>
)}
</span>
);
case 'failed':
return <span className="text-xs text-destructive">{status.error}</span>;
case 'waiting':
return <span className="text-xs text-muted-foreground">{fallback}</span>;
}
};
const busy = running !== null;
/** Names still worth running the bulk button over. */
const remaining = actionable.filter((claim) => !settled(claim.hostname)).length;
/**
* Where this sitting has got to, said once.
*
* Deleting is reported alongside taking names back rather than folded into
* it, because they are opposite decisions and somebody who has just made
* thirty of them should be able to see that they did.
*/
const summary = (() => {
const parts: string[] = [];
if (done) parts.push(`${done} done`);
if (deleted) parts.push(`${deleted} deleted`);
if (failed) parts.push(`${failed} failed`);
if (failed) return `${parts.join(', ')} — try the failed ones again.`;
if (parts.length) {
return `${parts.join(', ')}. A republished site takes the gateway about a minute to pick up.`;
}
return `${remaining} to migrate.`;
})();
/**
* Close, and let the lists catch up.
*
* Marked stale rather than refetched: the query is disabled while the dialog
* is shut, so nothing is asked until somebody opens it again — and asking
* costs a signature, which on a remote signer costs a round trip.
*/
const close = () => {
if (dirty) {
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
queryClient.invalidateQueries({ queryKey: ['npanel-claim-count'] });
}
onOpenChange(false);
};
/**
* What can be done about one name, minus whatever does not apply to it.
*
* Every row gets its own controls rather than only the bulk button, because
* the list is not a queue of decisions already made. Somebody with forty
* names on file wants three of them back and the rest gone, and until now the
* only thing the dialog would do was hand them all forty.
*/
const renderActions = (
hostname: string,
options: {
/** Where the site can be looked at, when anywhere can show it. */
preview?: string;
/** The one thing this row's section does to a name that is staying. */
act?: { label: string; icon: LucideIcon; run: () => Promise<void> };
/** Present when the name can be given up. `published` decides what the confirmation promises. */
deletable?: { published: boolean };
},
) => {
const gone = settled(hostname);
const ActionIcon = options.act?.icon;
return (
<div className="shrink-0 flex items-center gap-1">
{options.preview && (
<Button size="sm" variant="ghost" className="h-8 px-2 text-muted-foreground" asChild>
<a href={options.preview} target="_blank" rel="noreferrer">
<Eye className="h-4 w-4 sm:mr-1.5" />
<span className="hidden sm:inline">Show</span>
</a>
</Button>
)}
{options.act && ActionIcon && !gone && (
<Button
size="sm"
variant="outline"
className="h-8 px-2"
disabled={busy}
onClick={() => runRow(hostname, options.act!.run)}
>
<ActionIcon className="h-4 w-4 sm:mr-1.5" />
<span className="hidden sm:inline">{options.act.label}</span>
</Button>
)}
{options.deletable && !gone && (
<Button
size="sm"
variant="ghost"
className="h-8 px-2 text-muted-foreground hover:text-destructive"
disabled={busy}
aria-label={`Delete ${hostname}`}
onClick={() => setConfirming({ hostname, published: options.deletable!.published })}
>
<Trash2 className="h-4 w-4" />
</Button>
)}
</div>
);
};
return (
<>
<Dialog open={open} onOpenChange={busy ? undefined : (next) => (next ? onOpenChange(true) : close())}>
<DialogContent className="max-w-2xl max-h-[85vh] flex flex-col">
<DialogHeader className="shrink-0">
<DialogTitle>Take back your sites</DialogTitle>
<DialogDescription>
These names on {provider.domain} were yours before this gateway took the domain over.
They are being served from an archive key until you publish your own copy.
</DialogDescription>
</DialogHeader>
<div className="flex-1 overflow-y-auto space-y-6 py-2">
{isLoading && (
<div className="space-y-2">
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
<Skeleton className="h-12 w-full" />
</div>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error.message}</AlertDescription>
</Alert>
)}
{data && !claims.length && !data.taken.length && (
<p className="text-sm text-muted-foreground py-8 text-center">
Nothing is waiting for you here.
</p>
)}
{actionable.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Waiting for you</h4>
<div className="rounded-md border divide-y">
{actionable.map((claim) => (
<div key={claim.hostname} className="flex items-center justify-between gap-3 p-3">
<div className="min-w-0">
<div className="font-mono text-sm truncate">{claim.hostname}</div>
<div className="truncate">{renderStatus(claim.hostname, describeStep(claim))}</div>
</div>
{renderActions(claim.hostname, {
preview: sitePreviewUrl(claim.address, claim.hostname, provider.domain),
// The word the button uses is the work it does. A name
// whose site is already on this key publishes nothing.
act: {
label: claim.step.kind === 'republish' ? 'Publish' : 'Claim',
icon: Rocket,
run: () => migrate(claim),
},
// A `claim` step, either reason, means a copy of the site
// is already published under this key and survives the
// name going away. A `republish` step means it is not.
deletable: { published: claim.step.kind === 'claim' },
})}
</div>
))}
</div>
</div>
)}
{retitlable.length > 0 && (
<div className="space-y-2">
<div className="flex items-end justify-between gap-4">
<div>
<h4 className="text-sm font-medium">Titled after their address</h4>
<p className="text-xs text-muted-foreground">
The archive could only call a site by its hostname. These say what they are
actually called, so the name they publish under can too.
</p>
</div>
<Button size="sm" variant="outline" onClick={fixTitles} disabled={busy}>
{running === 'titles' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Fix titles'}
</Button>
</div>
<div className="rounded-md border divide-y">
{retitlable.map((site) => (
<div key={site.hostname} className="flex items-center justify-between gap-3 p-3">
<div className="min-w-0">
<div className="font-mono text-sm truncate">{site.hostname}</div>
<div className="truncate">
{renderStatus(
site.hostname,
site.suggestedTitle ? `Will be titled "${site.suggestedTitle}".` : 'The title will be removed.',
)}
</div>
</div>
{renderActions(site.hostname, {
preview: sitePreviewUrl(
`${site.event.kind}:${site.event.pubkey}:${eventIdentifier(site.event)}`,
site.hostname,
provider.domain,
),
act: { label: 'Retitle', icon: Tag, run: () => retitle(site) },
deletable: { published: true },
})}
</div>
))}
</div>
</div>
)}
{(data?.events.length ?? 0) > 0 && (
<div className="space-y-2">
<div className="flex items-end justify-between gap-4">
<div>
<h4 className="text-sm font-medium">Relay coverage</h4>
<p className="text-xs text-muted-foreground">
A site is only as findable as the relays holding its manifest. This sends the
events you already published to the relays that do not have them — same events,
no signing.
</p>
</div>
<Button size="sm" variant="outline" onClick={fixCoverage} disabled={busy}>
{running === 'coverage' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Check relays'}
</Button>
</div>
{coverage && (
<div className="rounded-md border bg-muted/30 p-3 space-y-1">
{coverage.lines.map((line) => (
<p key={line} className="text-xs font-mono text-muted-foreground break-words">
{line}
</p>
))}
</div>
)}
</div>
)}
{strays.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Published for a name that cannot load</h4>
<div className="rounded-md border border-dashed divide-y">
{strays.map((site) => (
<div key={site.hostname} className="flex items-center justify-between gap-3 p-3">
<div className="min-w-0 space-y-0.5">
<div className="font-mono text-sm truncate">{site.hostname}</div>
<div className="truncate">
{renderStatus(
site.hostname,
`No certificate covers a name this deep under ${provider.domain}.`,
)}
</div>
</div>
{/*
One button, not two. What is wrong with these is that
they exist at all, so there is no version of retracting
the manifest that leaves the gateway's record worth
keeping — the name has never loaded for anyone and never
will. The hostname is unservable, so the preview can only
come from the address.
*/}
{renderActions(site.hostname, {
preview: nsitePreviewUrl(
`${site.event.kind}:${site.event.pubkey}:${eventIdentifier(site.event)}`,
),
act: { label: 'Retract', icon: Trash2, run: () => removeStray(site) },
})}
</div>
))}
</div>
</div>
)}
{blocked.length > 0 && (
<div className="space-y-2">
<h4 className="text-sm font-medium">Needs a decision</h4>
<p className="text-xs text-muted-foreground">
Nothing here can be taken back safely without you choosing something first. Deleting
is a decision too, and for most of these it is the right one.
</p>
<div className="rounded-md border border-dashed divide-y">
{blocked.map((claim) => (
<div key={claim.hostname} className="flex items-center justify-between gap-3 p-3">
<div className="min-w-0 space-y-0.5">
<div className="font-mono text-sm truncate">{claim.hostname}</div>
<div className="truncate">{renderStatus(claim.hostname, describeStep(claim))}</div>
</div>
{renderActions(claim.hostname, {
preview: sitePreviewUrl(claim.address, claim.hostname, provider.domain),
deletable: { published: claim.mine },
})}
</div>
))}
</div>
</div>
)}
</div>
<DialogFooter className="shrink-0 gap-2 sm:justify-between items-center">
<span className="text-xs text-muted-foreground">{summary}</span>
<div className="flex gap-2">
<Button variant="outline" onClick={() => close()} disabled={busy}>
Close
</Button>
<Button onClick={migrateAll} disabled={busy || remaining === 0}>
{running === 'migrate' ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
Migrating…
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
{failed > 0 ? 'Retry' : `Migrate all (${remaining})`}
</>
)}
</Button>
</div>
</DialogFooter>
</DialogContent>
</Dialog>
<AlertDialog open={confirming !== null} onOpenChange={(next) => !next && setConfirming(null)}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete {confirming?.hostname}?</AlertDialogTitle>
<AlertDialogDescription>
{provider.name} stops serving this name and stops holding it for you, and it goes back
to being anybody's to take. This cannot be undone.{' '}
{confirming?.published
? 'The site itself stays published under your key, and can still be reached by its address.'
: 'The archived copy stays on Nostr under the key that published it — this only ends the gateway serving it.'}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
onClick={() => {
const hostname = confirming?.hostname;
setConfirming(null);
if (hostname) void runRow(hostname, () => removeClaim(hostname));
}}
>
Delete
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
@@ -1,65 +0,0 @@
import { useState, useEffect } from 'react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { AlertCircle } from 'lucide-react';
interface ShakespeareDeployFormProps {
host?: string;
projectId: string;
savedSubdomain?: string;
onSubdomainChange: (subdomain: string) => void;
onValidationChange?: (isValid: boolean) => void;
}
export function ShakespeareDeployForm({
host = 'shakespeare.wtf',
projectId,
savedSubdomain,
onSubdomainChange,
onValidationChange,
}: ShakespeareDeployFormProps) {
const [subdomain, setSubdomain] = useState(savedSubdomain || projectId);
// Update subdomain when savedSubdomain changes (e.g., when switching providers)
useEffect(() => {
setSubdomain(savedSubdomain || projectId);
}, [savedSubdomain, projectId]);
// Validate subdomain: no periods allowed (only single-level subdomains)
const hasPeriod = subdomain.includes('.');
const isValid = subdomain.trim() !== '' && !hasPeriod;
useEffect(() => {
onSubdomainChange(subdomain);
}, [subdomain, onSubdomainChange]);
useEffect(() => {
onValidationChange?.(isValid);
}, [isValid, onValidationChange]);
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
return (
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="shakespeare-subdomain">Subdomain</Label>
<Input
id="shakespeare-subdomain"
value={subdomain}
onChange={(e) => setSubdomain(e.target.value)}
placeholder={projectId}
className={hasPeriod ? 'border-destructive' : ''}
/>
{hasPeriod && (
<div className="flex items-start gap-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
<span>Subdomain cannot contain periods. Use hyphens instead (e.g., "nostr-radar").</span>
</div>
)}
<p className="text-xs text-muted-foreground">
Will deploy to: <span className="font-mono">{fullDomain}</span>
</p>
</div>
</div>
);
}
+3 -3
View File
@@ -44,14 +44,14 @@ export interface AppConfig {
faviconUrl: string;
/** Nostr Git web URL template (e.g., "https://nostrhub.io/{naddr}") */
ngitWebUrl: string;
/** Preview domain for iframe sandboxing (e.g., "local-shakespeare.dev") */
/** Preview domain for iframe sandboxing (e.g., "iframe.diy") */
previewDomain: string;
/** Selected language */
language?: string;
/** Whether to show the showcase section */
showcaseEnabled: boolean;
/** Npub of the showcase moderator */
showcaseModerator: string;
/** NIP-19 identifier (note1, nevent1, or naddr1) pointing at an event with p tags used as curator authors */
showcaseCurator: string;
/** VFS path for projects directory */
fsPathProjects: string;
/** VFS path for config directory */
+15 -5
View File
@@ -5,10 +5,20 @@ export interface BaseDeployProvider {
name: string;
}
export interface ShakespeareDeployProvider extends BaseDeployProvider {
type: 'shakespeare';
host?: string;
proxy?: boolean;
/**
* A gateway that serves nsites under a domain it hands out names on.
*
* The site is an ordinary nsite under the user's own key; what the gateway adds
* is the hostname, which it has to be asked for. `dashboardHost` is where that
* asking happens and `domain` is what the site is served under — usually two
* different names, and never assumed to be the same one.
*/
export interface NpanelProvider extends BaseDeployProvider {
type: 'npanel';
dashboardHost: string;
domain: string;
relayUrls: string[];
blossomServers: string[];
}
export interface NetlifyProvider extends BaseDeployProvider {
@@ -57,7 +67,7 @@ export interface RailwayProvider extends BaseDeployProvider {
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
export type DeployProvider = NpanelProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
export interface DeploySettings {
providers: DeployProvider[];
+152 -191
View File
@@ -1,24 +1,9 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { nip19 } from 'nostr-tools';
import type { NostrEvent } from '@nostrify/nostrify';
// Kind 31733 for app submissions (addressable events)
const APP_SUBMISSION_KIND = 31733;
// The moderator npub and hex
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
const MODERATOR_HEX = (() => {
try {
const decoded = nip19.decode(MODERATOR_NPUB);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
})();
// Soapbox team follow pack naddr (same as used on About page)
const SOAPBOX_TEAM_NADDR = 'naddr1qvzqqqyckypzpyexz3t34l966ngh5xg7u2q788hthdqmj0av3lv8s2tz9t43zt6dqqxxkdrsx4mnqm3jxfeh2ess5pyrw';
import type { NostrEvent, NostrFilter, NRelay, NPool } from '@nostrify/nostrify';
import { useAppContext } from '@/hooks/useAppContext';
import { NostrURI } from '@/lib/NostrURI';
export interface AppSubmission extends NostrEvent {
appName: string;
@@ -26,195 +11,171 @@ export interface AppSubmission extends NostrEvent {
repositoryUrl: string;
description: string;
appIconUrl: string;
screenshotUrl: string;
appTags: string[];
authorNpub: string;
isFeatured: boolean;
isApproved: boolean;
isHidden: boolean;
isHomepage: boolean;
bannerUrl: string;
}
/**
* Extract pubkeys from the `p` tags of a Nostr event.
*/
function extractPubkeys(event: NostrEvent): string[] {
return event.tags
.filter(([name]) => name === 'p')
.map(([, pubkey]) => pubkey)
.filter(Boolean);
}
/**
* Resolve a NIP-19 identifier (note1, nevent1, or naddr1) to an event.
*/
async function resolveCuratorEvent(
curatorIdentifier: string,
nostr: NPool<NRelay>,
): Promise<NostrEvent | null> {
try {
const decoded = nip19.decode(curatorIdentifier);
if (decoded.type === 'note') {
const events = await nostr.query(
[{ ids: [decoded.data], limit: 1 }],
{ signal: AbortSignal.timeout(3000) },
);
return events[0] ?? null;
}
if (decoded.type === 'nevent') {
const filter: NostrFilter = { ids: [decoded.data.id], limit: 1 };
if (decoded.data.author) filter.authors = [decoded.data.author];
const events = await nostr.query([filter], { signal: AbortSignal.timeout(3000) });
return events[0] ?? null;
}
if (decoded.type === 'naddr') {
const { kind, pubkey, identifier } = decoded.data;
const events = await nostr.query(
[{ kinds: [kind], authors: [pubkey], '#d': [identifier], limit: 1 }],
{ signal: AbortSignal.timeout(3000) },
);
return events[0] ?? null;
}
} catch {
// Invalid identifier or query failure — handled by caller
}
return null;
}
/**
* Returns true if a kind 31990 event can render an "Edit with Shakespeare" button.
* Requires an `a` tag referencing a kind 30617 git repository event.
*/
function hasGitRepository(event: NostrEvent): boolean {
return event.tags.some(([name, value]) => name === 'a' && value?.startsWith('30617:'));
}
/**
* Build a git clone URL from a kind 30617 `a` tag value (`30617:pubkey:d-tag`).
* Returns a nostr:// URI usable with isomorphic-git / Shakespeare clone flow.
*/
function repositoryUrlFromATag(aTagValue: string): string {
const parts = aTagValue.split(':');
if (parts.length < 3) return '';
const [, pubkey, identifier] = parts;
return new NostrURI({ pubkey, identifier }).toString();
}
export function useAppSubmissions() {
const { nostr } = useNostr();
const { config } = useAppContext();
const curatorIdentifier = config.showcaseCurator;
return useQuery({
queryKey: ['nostr', 'app-submissions'],
queryKey: ['nostr', 'app-submissions', curatorIdentifier],
queryFn: async (): Promise<AppSubmission[]> => {
// Get Soapbox team follow pack for auto-approval
const teamPubkeys = new Set<string>();
try {
const decoded = nip19.decode(SOAPBOX_TEAM_NADDR);
if (decoded.type === 'naddr') {
const addrData = decoded.data;
const teamEvents = await nostr.query([{
kinds: [addrData.kind],
authors: [addrData.pubkey],
'#d': [addrData.identifier],
limit: 1
}], { signal: AbortSignal.timeout(1000) });
// No curator configured — nothing to show
if (!curatorIdentifier.trim()) return [];
if (teamEvents.length > 0) {
const teamEvent = teamEvents[0];
// Extract pubkeys from 'p' tags
teamEvent.tags
.filter(([name]) => name === 'p')
.forEach(([, pubkey]) => {
if (pubkey) teamPubkeys.add(pubkey);
});
}
}
} catch (error) {
console.warn('Failed to fetch Soapbox team follow pack:', error);
}
// 1. Resolve the curator event to extract author pubkeys
const curatorEvent = await resolveCuratorEvent(curatorIdentifier, nostr);
if (!curatorEvent) return [];
// Get all app submissions (kind 31733)
const submissionEvents = await nostr.query([{
kinds: [APP_SUBMISSION_KIND],
'#t': ['soapbox-app-submission'],
limit: 100,
}], { signal: AbortSignal.timeout(3000) });
const authorPubkeys = extractPubkeys(curatorEvent);
if (authorPubkeys.length === 0) return [];
// Get list events from moderators (NIP-51 kind 30267)
const moderatorListEvents = await nostr.query([{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': [
'soapbox-featured-apps',
'soapbox-approved-apps',
'soapbox-homepage-apps',
],
limit: 3,
}], { signal: AbortSignal.timeout(1000) });
// 2. Query kind 31990 events from those authors tagged with #t:shakespeare
const appEvents = await nostr.query(
[{
kinds: [31990],
authors: authorPubkeys,
'#t': ['shakespeare'],
limit: 200,
}],
{ signal: AbortSignal.timeout(5000) },
);
// Get reporting events for hidden apps (NIP-56 kind 1984)
const reportEvents = await nostr.query([{
kinds: [1984],
authors: [MODERATOR_HEX],
limit: 1000
}], { signal: AbortSignal.timeout(1000) });
// Process submissions and apply moderation
const submissions: AppSubmission[] = [];
const submissionMap = new Map<string, NostrEvent>();
// Group regular submissions by d-tag (identifier) to get latest version
for (const event of submissionEvents) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const existing = submissionMap.get(dTag);
if (!existing || event.created_at > existing.created_at) {
submissionMap.set(dTag, event);
}
}
// Get the latest featured list
const featuredList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-featured-apps'));
const approvedList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-approved-apps'));
const homepageList = moderatorListEvents.find(e => e.tags.find(tag => tag[0] === 'd' && tag[1] === 'soapbox-homepage-apps'));
// Extract featured app coordinates from the list
const featuredAppCoords = new Set<string>();
if (featuredList) {
featuredList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => featuredAppCoords.add(tag[1]));
}
// Extract approved app coordinates from the list
const approvedAppCoords = new Set<string>();
if (approvedList) {
approvedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => approvedAppCoords.add(tag[1]));
}
// Extract homepage app coordinates from the list
const homepageAppCoords = new Set<string>();
if (homepageList) {
homepageList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => homepageAppCoords.add(tag[1]));
}
// Get hidden app coordinates from reports
const hiddenAppCoords = new Set<string>();
const appReports = new Map<string, { hidden: number; unhidden: number }>();
for (const report of reportEvents) {
// Look for app coordinate in 'a' tags
const aTag = report.tags.find(tag => tag[0] === 'a');
if (!aTag || !aTag[1]) continue;
const appCoord = aTag[1];
const reportType = aTag[2];
// Check if this is a moderation label
const moderationLabel = report.tags.find(tag =>
tag[0] === 'l' && tag[2] === 'soapbox.moderation'
)?.[1];
if (moderationLabel === 'hidden' && (reportType === 'spam' || reportType === 'other')) {
if (!appReports.has(appCoord)) {
appReports.set(appCoord, { hidden: 0, unhidden: 0 });
}
appReports.get(appCoord)!.hidden = Math.max(
appReports.get(appCoord)!.hidden,
report.created_at
);
} else if (moderationLabel === 'unhidden' && reportType === 'other') {
if (!appReports.has(appCoord)) {
appReports.set(appCoord, { hidden: 0, unhidden: 0 });
}
appReports.get(appCoord)!.unhidden = Math.max(
appReports.get(appCoord)!.unhidden,
report.created_at
);
}
}
// Determine which apps are currently hidden (latest action wins)
for (const [appCoord, reports] of appReports) {
if (reports.hidden > reports.unhidden) {
hiddenAppCoords.add(appCoord);
}
}
// Convert to AppSubmission objects
for (const [dTag, event] of submissionMap) {
// 3. Client-side filter: only keep events with a git repo, icon, and banner
const filteredEvents = appEvents.filter(event => {
if (!hasGitRepository(event)) return false;
try {
const appName = event.tags.find(tag => tag[0] === 'title')?.[1] || '';
const websiteUrl = event.tags.find(tag => tag[0] === 'website')?.[1] || '';
const repositoryUrl = event.tags.find(tag => tag[0] === 'repository')?.[1] || '';
const appIconUrl = event.tags.find(tag => tag[0] === 'icon')?.[1] || '';
const screenshotUrl = event.tags.find(tag => tag[0] === 'screenshot')?.[1] || '';
const authorNpub = event.tags.find(tag => tag[0] === 'author')?.[1] || event.pubkey;
const appTags = event.tags.filter(tag => tag[0] === 'app-tag').map(tag => tag[1]);
const meta = JSON.parse(event.content) as Record<string, unknown>;
return typeof meta.picture === 'string' && meta.picture &&
typeof meta.banner === 'string' && meta.banner;
} catch {
return false;
}
});
// Check if app is featured, approved, homepage, or hidden
const appCoordinate = `${APP_SUBMISSION_KIND}:${event.pubkey}:${dTag}`;
const isFeatured = featuredAppCoords.has(appCoordinate);
const isHomepage = homepageAppCoords.has(appCoordinate);
const isSubmittedByModerator = event.pubkey === MODERATOR_HEX;
const isSubmittedByTeamMember = teamPubkeys.has(event.pubkey);
const isApproved = approvedAppCoords.has(appCoordinate) || isFeatured || isSubmittedByModerator || isSubmittedByTeamMember;
const isHidden = hiddenAppCoords.has(appCoordinate);
// 4. Deduplicate: for each pubkey+d-tag, keep only the latest event
const latestMap = new Map<string, NostrEvent>();
for (const event of filteredEvents) {
const dTag = event.tags.find(([name]) => name === 'd')?.[1] ?? '';
const key = `${event.pubkey}:${dTag}`;
const existing = latestMap.get(key);
if (!existing || event.created_at > existing.created_at) {
latestMap.set(key, event);
}
}
// 5. Shape into AppSubmission objects
const submissions: AppSubmission[] = [];
for (const event of latestMap.values()) {
try {
let appName = '';
let appIconUrl = '';
let bannerUrl = '';
let websiteUrl = '';
let description = '';
// Parse kind-0-style metadata from content
if (event.content) {
try {
const meta = JSON.parse(event.content) as Record<string, unknown>;
if (typeof meta.name === 'string') appName = meta.name;
if (typeof meta.about === 'string') description = meta.about;
if (typeof meta.picture === 'string') appIconUrl = meta.picture;
if (typeof meta.banner === 'string') bannerUrl = meta.banner;
if (typeof meta.website === 'string') websiteUrl = meta.website;
} catch {
// Non-JSON content — ignore
}
}
// Fallback: title tag
if (!appName) {
appName = event.tags.find(([name]) => name === 'title')?.[1] ?? '';
}
// Build repository URL from the first 30617 `a` tag
const repoATag = event.tags.find(([name, value]) => name === 'a' && value?.startsWith('30617:'));
const repositoryUrl = repoATag ? repositoryUrlFromATag(repoATag[1]) : '';
submissions.push({
...event,
appName,
websiteUrl,
repositoryUrl,
description: event.content,
description,
appIconUrl,
screenshotUrl,
appTags: appTags,
authorNpub,
isFeatured,
isApproved,
isHidden,
isHomepage
bannerUrl,
});
} catch (error) {
console.warn('Failed to parse app submission:', error);
@@ -223,8 +184,8 @@ export function useAppSubmissions() {
return submissions;
},
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
staleTime: 30000,
refetchInterval: 60000,
});
}
@@ -235,6 +196,6 @@ export function useUserAppSubmissions(userPubkey?: string) {
return {
data: userSubmissions,
...rest
...rest,
};
}
}
+4 -4
View File
@@ -66,9 +66,9 @@ describe('useGenerateProjectInfo', () => {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
showcaseCurator: '',
graspMetadata: {
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
updatedAt: 0,
@@ -230,9 +230,9 @@ describe('useGenerateProjectInfo', () => {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
showcaseCurator: '',
graspMetadata: {
relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }],
updatedAt: 0,
+1 -1
View File
@@ -45,7 +45,7 @@ function createWrapper(corsProxy: string) {
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-test.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
showcaseCurator: '',
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
fsPathProjects: '/projects',
fsPathConfig: '/config',
+9
View File
@@ -1,5 +1,6 @@
import { useNostr } from '@nostrify/react';
import { NLogin, useNostrLogin } from '@nostrify/react/login';
import type { NostrConnectParams } from '@nostrify/react/login';
// NOTE: This file should not be edited except for adding new login methods.
@@ -18,6 +19,14 @@ export function useLoginActions() {
const login = await NLogin.fromBunker(uri, nostr);
addLogin(login);
},
// Login via client-initiated NIP-46 ("nostrconnect://" QR code).
// Caller generates params with `generateNostrConnectParams`, renders the
// URI as a QR/deep-link, and awaits this promise — it resolves when the
// remote signer connects back over the relay.
async nostrconnect(params: NostrConnectParams, signal?: AbortSignal): Promise<void> {
const login = await NLogin.fromNostrConnect(params, nostr, { signal });
addLogin(login);
},
// Login with a NIP-07 browser extension
async extension(): Promise<void> {
const login = await NLogin.fromExtension();
+11 -1
View File
@@ -2,6 +2,7 @@ import { useState, useCallback } from 'react';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useToast } from '@/hooks/useToast';
import { LN } from '@getalby/sdk';
import { assertInvoiceAmount } from '@/lib/bolt11';
export interface NWCConnection {
connectionString: string;
@@ -159,12 +160,21 @@ export function useNWCInternal() {
// Send payment using the SDK
const sendPayment = useCallback(async (
connection: NWCConnection,
invoice: string
invoice: string,
/**
* Amount in millisatoshis the user approved. The wallet is handed only the
* invoice, so this is the last point at which the sum the user agreed to
* and the sum the invoice charges can be compared — without it, whoever
* issued the invoice decides how much leaves the wallet.
*/
expectedAmountMsat: number,
): Promise<{ preimage: string }> => {
if (!connection.connectionString) {
throw new Error('Invalid connection: missing connection string');
}
assertInvoiceAmount(invoice, expectedAmountMsat);
let client: LN;
try {
client = new LN(connection.connectionString);
+192
View File
@@ -0,0 +1,192 @@
import { useQuery } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import type { NpanelProvider } from '@/contexts/DeploySettingsContext';
import {
fetchNpanelClaimCount,
fetchNpanelClaims,
type NpanelClaim,
type NpanelClaimCount,
} from '@/lib/deploy/npanelApi';
import {
NAMED_SITE_KIND,
hasArchiveTitle,
isServableHostname,
manifestIdentifier,
planClaim,
type MigrationStep,
} from '@/lib/deploy/npanelMigration';
/** How long the relay round trip for one's own sites is given. */
const RELAY_TIMEOUT_MS = 6_000;
/** A waiting name, with what it would take to get it back. */
export interface NpanelClaimPlan extends NpanelClaim {
step: MigrationStep;
}
/** A name already taken back, and the event currently serving it. */
export interface NpanelTakenSite {
hostname: string;
/** The claimant's own manifest, as relays hold it right now. */
event: NostrEvent;
/** What the site calls itself, per the gateway. Null when it never said. */
suggestedTitle: string | null;
suggestedDescription: string | null;
/** Whether the event is still titled after its hostname. */
needsTitle: boolean;
/** A name no certificate can cover, which should never have been published. */
stray: boolean;
}
export interface NpanelClaims {
/** Names still waiting, each with a plan. */
waiting: NpanelClaimPlan[];
/** Names already taken back whose manifest could be improved or removed. */
taken: NpanelTakenSite[];
/** Every event of the user's this query saw, for checking relay coverage. */
events: NostrEvent[];
}
/** The `identifier` half of a `kind:pubkey:identifier` address. */
function addressIdentifier(address: string): string {
return address.split(':').slice(2).join(':');
}
/** The `d` tag of an event, which for a named site is the site's identifier. */
function eventIdentifier(event: NostrEvent): string {
return event.tags.find(([name]) => name === 'd')?.[1] ?? '';
}
/**
* The names waiting for the logged-in user on a gateway, and what each needs.
*
* Half the answer comes from relays rather than the gateway: to know whether a
* name can simply be repointed, one has to know which sites this user already
* publishes, and that is on the network, not in npanel. The same query answers
* two more questions at no extra cost — which taken names are still titled
* after their hostname, and which of them should never have been published at
* all — so it is made once and its events are kept.
*/
export function useNpanelClaims(provider: NpanelProvider | undefined) {
const { user } = useCurrentUser();
const { nostr } = useNostr();
return useQuery<NpanelClaims>({
queryKey: ['npanel-claims', provider?.dashboardHost, user?.pubkey],
enabled: Boolean(provider && user),
// Nobody's list of waiting names changes on its own, and every refetch
// costs a signature — which on a remote signer costs a round trip.
staleTime: 5 * 60 * 1000,
refetchOnWindowFocus: false,
retry: false,
queryFn: async ({ signal }) => {
const empty: NpanelClaims = { waiting: [], taken: [], events: [] };
if (!provider || !user) return empty;
const claims = await fetchNpanelClaims(provider.dashboardHost, user.signer, signal, { taken: true });
if (!claims.length) return empty;
// Only the names actually in play are asked about, rather than every
// site this key has ever published.
const wanted = new Set<string>();
for (const claim of claims) {
const identifier = claim.manifest ? manifestIdentifier(claim.manifest) : '';
if (identifier) wanted.add(identifier);
if (claim.address) wanted.add(addressIdentifier(claim.address));
}
wanted.delete('');
const events = wanted.size
? await nostr.group(provider.relayUrls).query(
[{ kinds: [NAMED_SITE_KIND], authors: [user.pubkey], '#d': [...wanted] }],
{ signal: AbortSignal.any([signal, AbortSignal.timeout(RELAY_TIMEOUT_MS)]) },
)
: [];
const byIdentifier = new Map<string, NostrEvent>();
for (const event of events) {
const identifier = eventIdentifier(event);
if (!identifier) continue;
const seen = byIdentifier.get(identifier);
if (!seen || seen.created_at < event.created_at) byIdentifier.set(identifier, event);
}
const published = new Set(byIdentifier.keys());
// A name npanel serves from this user's own key is a site this user
// published, so relays that know nothing about any of them are relays
// that are not answering. Planning against that silence would mean
// republishing over live sites, so it fails loudly instead.
const known = claims
.filter((claim) => claim.mine && claim.address)
.map((claim) => addressIdentifier(claim.address ?? ''))
.filter(Boolean);
if (known.length && !known.some((identifier) => published.has(identifier))) {
throw new Error(
'Relays did not answer with the sites you already publish, so it is not safe to work out what needs republishing. Try again in a moment.',
);
}
const waiting: NpanelClaimPlan[] = [];
const taken: NpanelTakenSite[] = [];
for (const claim of claims) {
if (!claim.claimed) {
waiting.push({ ...claim, step: planClaim(claim, user.pubkey, published, provider.domain) });
continue;
}
const identifier = claim.address ? addressIdentifier(claim.address) : '';
const event = identifier ? byIdentifier.get(identifier) : undefined;
// A claimed name whose event no relay answered with is not a name with
// nothing wrong; it is a name nothing can be said about. Leaving it out
// is the only option that cannot make it worse.
if (!event) continue;
const stray = !isServableHostname(claim.hostname, provider.domain);
taken.push({
hostname: claim.hostname,
event,
suggestedTitle: claim.suggestedTitle ?? null,
suggestedDescription: claim.suggestedDescription ?? null,
needsTitle: hasArchiveTitle(event, claim.hostname),
stray,
});
}
return { waiting, taken, events: [...byIdentifier.values()] };
},
});
}
/**
* How many names a gateway is holding for the logged-in user.
*
* Separate from {@link useNpanelClaims} because it is asked at a different
* moment and must cost a different amount. That one runs when somebody opens
* the dialog and has already decided to look; it reads every claimed deploy on
* the gateway and queries relays for this user's own events. This one runs
* because a settings page was opened, so it is one signature and two counted
* rows, and a gateway that cannot answer it says nothing rather than failing.
*/
export function useNpanelClaimCount(provider: NpanelProvider | undefined) {
const { user } = useCurrentUser();
return useQuery<NpanelClaimCount>({
queryKey: ['npanel-claim-count', provider?.dashboardHost, user?.pubkey],
enabled: Boolean(provider && user),
// Nobody's list of waiting names changes on its own, and every refetch
// costs a signature — which on a remote signer costs a round trip. Long
// enough that opening settings twice in a sitting asks once.
staleTime: 30 * 60 * 1000,
refetchOnWindowFocus: false,
retry: false,
queryFn: async ({ signal }) => {
if (!provider || !user) return { waiting: 0, taken: 0 };
return await fetchNpanelClaimCount(provider.dashboardHost, user.signer, signal);
},
});
}
+37 -6
View File
@@ -3,11 +3,14 @@ import { z } from 'zod';
import { useFS } from './useFS';
import { useFSPaths } from './useFSPaths';
const shakespeareProjectConfigSchema = z.object({
type: z.literal('shakespeare'),
const npanelProjectConfigSchema = z.object({
type: z.literal('npanel'),
url: z.string(),
data: z.object({
/** The single label in front of the gateway's domain. */
subdomain: z.string().optional(),
siteTitle: z.string().optional(),
siteDescription: z.string().optional(),
}),
});
@@ -71,7 +74,7 @@ const railwayProjectConfigSchema = z.object({
});
const projectProviderConfigSchema = z.discriminatedUnion('type', [
shakespeareProjectConfigSchema,
npanelProjectConfigSchema,
nsiteProjectConfigSchema,
netlifyProjectConfigSchema,
vercelProjectConfigSchema,
@@ -85,7 +88,7 @@ const projectDeploySettingsSchema = z.object({
currentProvider: z.string().optional(),
});
export type ShakespeareProjectConfig = z.infer<typeof shakespeareProjectConfigSchema>;
export type NpanelProjectConfig = z.infer<typeof npanelProjectConfigSchema>;
export type NsiteProjectConfig = z.infer<typeof nsiteProjectConfigSchema>;
export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
@@ -95,6 +98,24 @@ export type RailwayProjectConfig = z.infer<typeof railwayProjectConfigSchema>;
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
/**
* Bring a record written by an older version up to date.
*
* `shakespeare` deploys became `npanel` ones against the same domain, and the
* subdomain carries straight over. Worth doing rather than letting the schema
* reject it: this file holds one record per provider a project has ever
* deployed to, so a single unparseable entry would take a Netlify site id and a
* Vercel project id down with it.
*/
function migrateProjectProviderConfig(config: unknown): unknown {
if (typeof config !== 'object' || config === null) return config;
const candidate = config as Record<string, unknown>;
if (candidate.type !== 'shakespeare') return config;
return { ...candidate, type: 'npanel' };
}
/**
* Hook to manage project-specific deployment settings
* Stores settings in .git/shakespeare/deploy.json
@@ -118,10 +139,20 @@ export function useProjectDeploySettings(projectId: string | null) {
try {
setIsLoading(true);
const content = await fs.fs.readFile(settingsPath, 'utf8');
const parsed = JSON.parse(content as string);
const parsed = JSON.parse(content as string) as { providers?: Record<string, unknown> };
const migrated = {
...parsed,
providers: Object.fromEntries(
Object.entries(parsed?.providers ?? {}).map(([id, config]) => [
id,
migrateProjectProviderConfig(config),
]),
),
};
// Validate with Zod
const validated = projectDeploySettingsSchema.parse(parsed);
const validated = projectDeploySettingsSchema.parse(migrated);
setSettings(validated);
} catch (error) {
// File doesn't exist, is invalid JSON, or doesn't match schema - use empty settings
+2 -1
View File
@@ -14,8 +14,9 @@ export function useUploadFile() {
const uploader = new BlossomUploader({
servers: [
'https://blossom.primal.net/',
'https://blossom.ditto.pub/',
'https://blossom.dreamith.to/',
'https://blossom.primal.net/',
],
signer: user.signer,
});
+54 -8
View File
@@ -11,6 +11,8 @@ import type { WebLNProvider } from 'webln';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
import { assertInvoiceAmount, invoiceCommitsTo } from '@/lib/bolt11';
import { resolveLnurlPay, type LnurlPayParams } from '@/lib/lnurlPay';
export function useZaps(
target: Event | Event[],
@@ -180,12 +182,19 @@ export function useZaps(
return;
}
// Get zap endpoint using the old reliable method
const zapEndpoint = await nip57.getZapEndpoint(author.data.event);
if (!zapEndpoint) {
// Resolve the recipient's LNURL-pay endpoint in-repo instead of via
// nip57.getZapEndpoint, which returns only the callback URL and discards
// the minSendable/maxSendable bounds and metadata needed to validate the
// invoice we get back.
let lnurlParams: LnurlPayParams;
try {
lnurlParams = await resolveLnurlPay({ lud06, lud16 });
} catch (endpointError) {
toast({
title: 'Zap endpoint not found',
description: 'Could not find a zap endpoint for the author.',
description: endpointError instanceof Error
? endpointError.message
: 'Could not find a zap endpoint for the author.',
variant: 'destructive',
});
setIsZapping(false);
@@ -194,6 +203,20 @@ export function useZaps(
const zapAmount = amount * 1000; // convert to millisats
// The endpoint advertises what it will accept; asking for anything
// outside that range can only produce an invoice we'd have to reject.
if (zapAmount < lnurlParams.minSendable || zapAmount > lnurlParams.maxSendable) {
toast({
title: 'Amount out of range',
description:
`This lightning address accepts between ${Math.ceil(lnurlParams.minSendable / 1000)} and ` +
`${Math.floor(lnurlParams.maxSendable / 1000)} sats.`,
variant: 'destructive',
});
setIsZapping(false);
return;
}
const writeRelays = config.relayMetadata.relays
.filter(r => r.write)
.map(r => r.url);
@@ -209,9 +232,14 @@ export function useZaps(
throw new Error('No signer available');
}
const signedZapRequest = await user.signer.signEvent(zapRequest);
const zapRequestJson = JSON.stringify(signedZapRequest);
try {
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`);
const zapUrl = new URL(lnurlParams.callback);
zapUrl.searchParams.set('amount', String(zapAmount));
zapUrl.searchParams.set('nostr', zapRequestJson);
const res = await fetch(zapUrl.toString());
const responseData = await res.json();
if (!res.ok) {
@@ -223,13 +251,31 @@ export function useZaps(
throw new Error('Lightning service did not return a valid invoice');
}
// The endpoint that produced this invoice is chosen by the recipient,
// so the invoice is not trusted: decode it and require that it charges
// exactly what the user approved. Without this, the recipient — not the
// sender — decides how much the sender pays. Throwing here aborts
// before any wallet is touched, on every payment path.
const decodedInvoice = assertInvoiceAmount(newInvoice, zapAmount);
// LUD-06 binds the invoice to the endpoint's `metadata`; NIP-57 binds
// it to the zap request instead. Either is fine, anything else means
// the invoice was not issued for this request.
if (!invoiceCommitsTo(decodedInvoice, [zapRequestJson, lnurlParams.metadata])) {
throw new Error('Lightning service returned an invoice for a different request. Payment cancelled.');
}
// Report what the invoice actually charges rather than what was asked
// for, so a success screen can never understate a spend.
const paidSats = Math.round(decodedInvoice.amountMsat / 1000);
// Get the current active NWC connection dynamically
const currentNWCConnection = getActiveConnection();
// Try NWC first if available and properly connected
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
try {
await sendPayment(currentNWCConnection, newInvoice);
await sendPayment(currentNWCConnection, newInvoice, zapAmount);
// Clear states immediately on success
setIsZapping(false);
@@ -237,7 +283,7 @@ export function useZaps(
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats via NWC to the author.`,
description: `You sent ${paidSats} sats via NWC to the author.`,
});
// Invalidate zap queries to refresh counts
@@ -269,7 +315,7 @@ export function useZaps(
toast({
title: 'Zap successful!',
description: `You sent ${amount} sats to the author.`,
description: `You sent ${paidSats} sats to the author.`,
});
// Invalidate zap queries to refresh counts
+2 -2
View File
@@ -46,10 +46,10 @@ const testConfig: AppConfig = {
gitProxyOrigins: ['https://github.com', 'https://gitlab.com'],
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
ngitWebUrl: 'https://nostrhub.io/{naddr}',
previewDomain: 'local-shakespeare.dev',
previewDomain: 'iframe.diy',
language: 'en',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
showcaseCurator: '',
graspMetadata: { relays: [{ url: 'wss://git.shakespeare.diy/' }, { url: 'wss://relay.ngit.dev/' }], updatedAt: 0 },
fsPathProjects: '/projects',
fsPathConfig: '/config',
+144
View File
@@ -0,0 +1,144 @@
import { describe, it, expect } from 'vitest';
import type OpenAI from 'openai';
import { applyOpenRouterTransforms } from './ai-client';
/**
* Helper: minimal valid ChatCompletionCreateParams for transform tests.
*/
function makeBody(overrides: Partial<OpenAI.Chat.Completions.ChatCompletionCreateParams> = {})
: OpenAI.Chat.Completions.ChatCompletionCreateParams {
return {
model: 'anthropic/claude-opus-4.6',
messages: [
{ role: 'system', content: 'you are helpful' },
{ role: 'user', content: 'hello' },
],
...overrides,
};
}
describe('applyOpenRouterTransforms', () => {
it('adds usage accounting to the body regardless of model', () => {
const body = makeBody({ model: 'openai/gpt-4' });
applyOpenRouterTransforms(body);
expect((body as { usage?: { include?: boolean } }).usage).toEqual({ include: true });
});
it('does not apply cache_control for non-Anthropic models', () => {
const body = makeBody({
model: 'openai/gpt-4',
tools: [
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
],
});
applyOpenRouterTransforms(body);
// messages remain as plain strings (no normalization)
expect(body.messages[0].content).toBe('you are helpful');
// tools untouched
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
});
it('places cache_control on the last tool for Anthropic models', () => {
const body = makeBody({
tools: [
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
{ type: 'function', function: { name: 't2', description: '', parameters: { type: 'object' } } },
{ type: 'function', function: { name: 't3', description: '', parameters: { type: 'object' } } },
],
});
applyOpenRouterTransforms(body);
// Only the LAST tool gets cache_control — Anthropic caches everything
// up to and including the marked block, so marking the last tool is
// sufficient and we spend only one of the 4 breakpoints.
expect((body.tools![0] as { cache_control?: unknown }).cache_control).toBeUndefined();
expect((body.tools![1] as { cache_control?: unknown }).cache_control).toBeUndefined();
expect((body.tools![2] as { cache_control?: { type: string } }).cache_control)
.toEqual({ type: 'ephemeral' });
});
it('places cache_control on the system message and last two non-system messages', () => {
const body = makeBody({
messages: [
{ role: 'system', content: 'you are helpful' },
{ role: 'user', content: 'first' },
{ role: 'assistant', content: 'reply 1' },
{ role: 'user', content: 'second' },
{ role: 'assistant', content: 'reply 2' },
],
});
applyOpenRouterTransforms(body);
const hasCache = (m: OpenAI.Chat.Completions.ChatCompletionMessageParam): boolean => {
if (!Array.isArray(m.content)) return false;
return m.content.some((b) => {
const block = b as { cache_control?: unknown };
return block.cache_control !== undefined;
});
};
// System: cached
expect(hasCache(body.messages[0])).toBe(true);
// Old turns: not cached
expect(hasCache(body.messages[1])).toBe(false);
expect(hasCache(body.messages[2])).toBe(false);
// Last two non-system: cached
expect(hasCache(body.messages[3])).toBe(true);
expect(hasCache(body.messages[4])).toBe(true);
});
it('normalizes string content to text block arrays for Anthropic', () => {
const body = makeBody();
applyOpenRouterTransforms(body);
// System and user both turned into arrays of text blocks
expect(Array.isArray(body.messages[0].content)).toBe(true);
expect(Array.isArray(body.messages[1].content)).toBe(true);
const sysBlocks = body.messages[0].content as Array<{ type: string; text: string }>;
expect(sysBlocks[0]).toEqual(
expect.objectContaining({ type: 'text', text: 'you are helpful' }),
);
});
it('does not crash when tools is undefined or empty', () => {
const a = makeBody();
expect(() => applyOpenRouterTransforms(a)).not.toThrow();
expect(a.tools).toBeUndefined();
const b = makeBody({ tools: [] });
expect(() => applyOpenRouterTransforms(b)).not.toThrow();
expect(b.tools).toEqual([]);
});
it('does not mutate the original tools array reference (uses structuredClone)', () => {
const originalTools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{ type: 'function', function: { name: 't1', description: '', parameters: { type: 'object' } } },
];
const originalRef = originalTools;
const body = makeBody({ tools: originalTools });
applyOpenRouterTransforms(body);
// body.tools is now a clone, original array untouched
expect(body.tools).not.toBe(originalRef);
expect((originalTools[0] as { cache_control?: unknown }).cache_control).toBeUndefined();
// But body.tools has cache_control
expect((body.tools![0] as { cache_control?: { type: string } }).cache_control)
.toEqual({ type: 'ephemeral' });
});
it('produces byte-identical output across two calls with the same input (cache stability)', () => {
// This is the property the Anthropic cache relies on: the tools block
// hashes to the same value on every turn. If this test ever fails, tool
// caching will silently stop working.
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{ type: 'function', function: { name: 'a', description: 'x', parameters: { type: 'object', properties: { foo: { type: 'string' } } } } },
{ type: 'function', function: { name: 'b', description: 'y', parameters: { type: 'object' } } },
];
const body1 = makeBody({ tools: structuredClone(tools) });
const body2 = makeBody({ tools: structuredClone(tools) });
applyOpenRouterTransforms(body1);
applyOpenRouterTransforms(body2);
expect(JSON.stringify(body1.tools)).toEqual(JSON.stringify(body2.tools));
});
});
+70 -28
View File
@@ -64,34 +64,7 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
// OpenRouter-specific hacks
if (provider.id === "openrouter" || provider.baseURL === "https://openrouter.ai/api/v1") {
// Usage accounting field to get token usage and cost per request
// https://openrouter.ai/docs/use-cases/usage-accounting
(body as { usage?: { include?: boolean } }).usage = { include: true };
// Prompt caching for Claude models
// https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
if (body.model.startsWith("anthropic/")) {
// First normalize the message history to use content blocks
body.messages = structuredClone(body.messages);
body.messages = body.messages.map((m) => {
if (m.role !== "function" && typeof m.content === "string") {
return { ...m, content: [{ type: "text", text: m.content }] };
} else {
return m;
}
});
const systemMessage = body.messages.find((m) => m.role === "system");
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
const lastTwoMessages = nonSystemMessages.slice(-2);
if (systemMessage) {
addCacheControl(systemMessage);
}
for (const msg of lastTwoMessages) {
addCacheControl(msg);
}
}
applyOpenRouterTransforms(body);
}
return createCompletion(body, options);
@@ -100,6 +73,75 @@ export function createAIClient(provider: AIProvider, user?: NUser, corsProxy?: s
return openai;
}
/**
* Apply OpenRouter-specific request body mutations: opt into usage accounting,
* and (for Anthropic models) place `cache_control` breakpoints so the tools
* array, system prompt, and last two messages get cached. Exported for tests.
*
* References:
* - OpenRouter prompt caching guide:
* https://openrouter.ai/docs/guides/best-practices/prompt-caching#anthropic-claude
* - OpenRouter tool caching announcement: "gif-prompts-omni-search-tool-caching-and-byok-flags"
* - Anthropic prompt caching docs:
* https://docs.anthropic.com/en/docs/build-with-claude/prompt-caching
*
* Anthropic's cache hierarchy is `tools` → `system` → `messages`. We use all
* four breakpoints Anthropic allows per request:
* 1. last tool definition (caches the entire tools array)
* 2. system message (caches system prompt + AGENTS.md)
* 3. second-to-last non-system (caches most of conversation)
* 4. last non-system (caches everything including latest msg)
*/
export function applyOpenRouterTransforms(
body: OpenAI.Chat.Completions.ChatCompletionCreateParams,
): void {
// Usage accounting field to get token usage and cost per request.
// https://openrouter.ai/docs/use-cases/usage-accounting
(body as { usage?: { include?: boolean } }).usage = { include: true };
if (!body.model.startsWith("anthropic/")) return;
// Normalize the message history to use content blocks so we can attach
// cache_control to individual text parts.
body.messages = structuredClone(body.messages);
body.messages = body.messages.map((m) => {
if (m.role !== "function" && typeof m.content === "string") {
return { ...m, content: [{ type: "text", text: m.content }] };
} else {
return m;
}
});
const systemMessage = body.messages.find((m) => m.role === "system");
const nonSystemMessages = body.messages.filter((m) => m.role !== "system");
const lastTwoMessages = nonSystemMessages.slice(-2);
if (systemMessage) {
addCacheControl(systemMessage);
}
for (const msg of lastTwoMessages) {
addCacheControl(msg);
}
// Cache the tools array by marking the last tool with cache_control.
// Anthropic caches everything up to and including the marked block, so
// marking just the last tool caches the whole array. The tools array
// must be byte-stable across turns for cache hits — Shakespeare builds
// it once per session in `ChatPane`, so this holds as long as we don't
// mutate session.tools mid-session.
//
// Note: the OpenAI SDK serializes the body via plain `JSON.stringify`
// (see node_modules/openai/internal/request-options) and does not strip
// unknown fields, so the `cache_control` property survives the trip to
// OpenRouter.
if (body.tools && body.tools.length > 0) {
body.tools = structuredClone(body.tools);
const lastTool = body.tools[body.tools.length - 1];
(lastTool as { cache_control?: { type: "ephemeral" } })
.cache_control = { type: "ephemeral" };
}
}
/** Mutate msg to add an Anthropic `cache_control` property to its last text block */
function addCacheControl(msg: OpenAI.Chat.Completions.ChatCompletionMessageParam) {
if (Array.isArray(msg.content)) {
+11 -1
View File
@@ -7,6 +7,8 @@ export interface PresetProvider {
tosURL?: string;
proxy?: boolean;
openSecret?: string;
/** Default API key for providers where the key is a required placeholder */
apiKey?: string;
}
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
@@ -106,4 +108,12 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://vercel.com/legal/terms",
proxy: true,
},
];
{
// Local Anthropic/OpenAI-compatible bridge; authenticates via the
// Claude Code SDK. The API key is a placeholder — any value works.
id: "meridian",
name: "Meridian",
baseURL: "http://127.0.0.1:3456/v1",
apiKey: "x",
},
];
+28 -7
View File
@@ -9,10 +9,16 @@ export interface AppEventInput {
name: string;
about?: string;
picture?: string;
banner?: string;
website?: string;
dTag: string;
tTags?: string[];
supportedKinds?: string[];
webHandlers?: Array<{ url: string; type?: string }>;
/** Explicit "a" tag value for the ngit repo (kind:pubkey:identifier). Overrides auto-detection from git remote. */
ngitRepo?: string;
/** Explicit "a" tag value for the nsite deployment (kind:pubkey:identifier). Overrides auto-detection from .nsite/config.json. */
nsiteDeployment?: string;
}
/** The content and tags for a kind 31990 event, ready to be signed/published. */
@@ -41,6 +47,7 @@ export async function buildAppEvent(
if (input.name.trim()) content.name = input.name.trim();
if (input.about?.trim()) content.about = input.about.trim();
if (input.picture?.trim()) content.picture = input.picture.trim();
if (input.banner?.trim()) content.banner = input.banner.trim();
if (input.website?.trim()) content.website = input.website.trim();
// Build tags
@@ -68,13 +75,23 @@ export async function buildAppEvent(
}
}
// Add t-tags for categorization (shakespeare + template name)
// Add user-defined t-tags
if (input.tTags) {
for (const tag of input.tTags) {
if (tag.trim()) tags.push(['t', tag.trim()]);
}
}
// Add t-tags for categorization (shakespeare + template name), skipping duplicates
if (opts?.fs && opts.cwd) {
tags.push(['t', 'shakespeare']);
const existingTTags = new Set(input.tTags?.map(t => t.trim().toLowerCase()) ?? []);
if (!existingTTags.has('shakespeare')) {
tags.push(['t', 'shakespeare']);
}
try {
const dotAI = new DotAI(opts.fs, opts.cwd);
const template = await dotAI.readTemplate();
if (template) {
if (template && !existingTTags.has(template.name.toLowerCase())) {
tags.push(['t', template.name.toLowerCase()]);
}
} catch {
@@ -82,8 +99,10 @@ export async function buildAppEvent(
}
}
// If origin remote is a nostr:// URI owned by the given pubkey, add an "a" tag for the repo
if (opts?.fs && opts.cwd && opts.pubkey) {
// Add "a" tag for the ngit repo — use explicit override if provided, otherwise auto-detect from git remote
if (input.ngitRepo?.trim()) {
tags.push(['a', input.ngitRepo.trim()]);
} else if (opts?.fs && opts.cwd && opts.pubkey) {
try {
const remotes = await git.listRemotes({ fs: opts.fs, dir: opts.cwd });
const originUrl = remotes.find(r => r.remote === 'origin')?.url;
@@ -98,8 +117,10 @@ export async function buildAppEvent(
}
}
// If an nsite deployment exists, add an "a" tag referencing the kind 35128 site manifest event
if (opts?.fs && opts.cwd && opts.pubkey) {
// Add "a" tag for the nsite deployment — use explicit override if provided, otherwise auto-detect from .nsite/config.json
if (input.nsiteDeployment?.trim()) {
tags.push(['a', input.nsiteDeployment.trim()]);
} else if (opts?.fs && opts.cwd && opts.pubkey) {
try {
const nsiteConfig = await readNsiteVfsConfig(opts.fs, opts.cwd);
if (nsiteConfig?.id) {
+115
View File
@@ -0,0 +1,115 @@
import { describe, it, expect } from 'vitest';
import { assertInvoiceAmount, decodeBolt11, invoiceCommitsTo } from './bolt11';
// BOLT 11 specification test vectors.
/** 2500u = 250,000,000 msat, with a plain-text description. */
const INVOICE_2500U =
'lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypq' +
'dq5xysxxatsyp3k7enxv4jsxqzpuaztrnwngzn3kdzw5hydlzf03qdgm2hdq27cqv3agm2aw' +
'hz5se903vruatfhq77w3ls4evs3ch9zw97j25emudupq63nyw24cg27h2rspfj9srp';
/** No amount in the human-readable part — the payer or payee picks the sum. */
const INVOICE_AMOUNTLESS =
'lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpl2p' +
'kx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq8rkx3yf5tcs' +
'yz3d73gafnh3cax9rn449d9p5uxz9ezhhypd0elx87sjle52x86fux2ypatgddc6k63n7erq' +
'z25le42c4u4ecky03ylcqca784w';
/** 20m = 2,000,000,000 msat, carrying a description hash rather than text. */
const INVOICE_20M_WITH_HASH =
'lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqhp' +
'58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqscc6gd6ql3jrc5yzme8v' +
'4ntcewwz5cnw92tz0pc8qcuufvq7khhr8wpald05e92xw006sq94mg8v2ndf4sefvf9sygks' +
'hp5zfem29trqq2yxxz7';
/** The string whose sha256 is the description hash in {@link INVOICE_20M_WITH_HASH}. */
const HASHED_DESCRIPTION =
'One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, ' +
'one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, ' +
'and one slice of watermelon';
describe('decodeBolt11', () => {
it('decodes the amount from the human-readable part', () => {
expect(decodeBolt11(INVOICE_2500U).amountMsat).toBe(250_000_000);
expect(decodeBolt11(INVOICE_20M_WITH_HASH).amountMsat).toBe(2_000_000_000);
});
it('reports an amountless invoice as null rather than zero', () => {
expect(decodeBolt11(INVOICE_AMOUNTLESS).amountMsat).toBeNull();
});
it('reads the network, timestamp and payment hash', () => {
const decoded = decodeBolt11(INVOICE_2500U);
expect(decoded.network).toBe('bc');
expect(decoded.timestamp).toBe(1496314658);
expect(decoded.paymentHash).toBe(
'0001020304050607080900010203040506070809000102030405060708090102',
);
});
it('reads the plain-text description', () => {
expect(decodeBolt11(INVOICE_2500U).description).toBe('1 cup coffee');
});
it('reads the description hash', () => {
expect(decodeBolt11(INVOICE_20M_WITH_HASH).descriptionHash).toHaveLength(64);
});
it('tolerates a lightning: URI prefix, whitespace and uppercase', () => {
expect(decodeBolt11(` LIGHTNING:${INVOICE_2500U.toUpperCase()} `).amountMsat).toBe(250_000_000);
});
it('rejects a string that is not an invoice', () => {
expect(() => decodeBolt11('not-an-invoice')).toThrow();
expect(() => decodeBolt11('')).toThrow();
});
it('rejects an invoice whose checksum has been tampered with', () => {
// Flip the last character of the bech32 checksum.
const tampered = INVOICE_2500U.slice(0, -1) + (INVOICE_2500U.endsWith('p') ? 'q' : 'p');
expect(() => decodeBolt11(tampered)).toThrow();
});
});
describe('assertInvoiceAmount', () => {
it('accepts an invoice for exactly the requested amount', () => {
expect(assertInvoiceAmount(INVOICE_2500U, 250_000_000).amountMsat).toBe(250_000_000);
});
it('rejects an invoice for more than was requested', () => {
// The reported attack: the user approves 776 sats and the recipient's own
// LNURL server answers with an invoice for 5,000,000 sats.
expect(() => assertInvoiceAmount(INVOICE_2500U, 776_000)).toThrow(/250000 sats.*776 sats/);
});
it('rejects an invoice for less than was requested', () => {
expect(() => assertInvoiceAmount(INVOICE_2500U, 250_000_001)).toThrow();
});
it('rejects an amountless invoice, which would let the wallet pick the sum', () => {
expect(() => assertInvoiceAmount(INVOICE_AMOUNTLESS, 250_000_000)).toThrow(/no amount/);
});
it('rejects an unparseable invoice rather than passing it through', () => {
expect(() => assertInvoiceAmount('lnbc-garbage', 1000)).toThrow(/unreadable/);
});
});
describe('invoiceCommitsTo', () => {
it('accepts an invoice whose description hash matches a candidate', () => {
const decoded = decodeBolt11(INVOICE_20M_WITH_HASH);
expect(invoiceCommitsTo(decoded, ['something else', HASHED_DESCRIPTION])).toBe(true);
});
it('rejects an invoice bound to a different request', () => {
const decoded = decodeBolt11(INVOICE_20M_WITH_HASH);
expect(invoiceCommitsTo(decoded, ['a different zap request'])).toBe(false);
});
it('accepts an invoice with no description hash at all', () => {
// Many providers use a plain `d` description; the amount check is what
// stops an overcharge, this is only defence in depth.
expect(invoiceCommitsTo(decodeBolt11(INVOICE_2500U), ['anything'])).toBe(true);
});
});
+258
View File
@@ -0,0 +1,258 @@
/**
* BOLT11 lightning invoice decoding.
*
* This is an *authentication* decoder, not a display heuristic: before any
* wallet is asked to pay an invoice we have to know exactly what that invoice
* commits to. `nip57.getSatoshisAmountFromBolt11` reads the human-readable
* part of a string that is assumed to already be an invoice — it will happily
* report an amount for a string that is not a valid invoice at all, and it
* cannot see the tagged fields. Use {@link decodeBolt11} for anything that
* moves money.
*
* Built on `@scure/base` + `@noble/hashes`, both already in the entry bundle
* via `nostr-tools`, so this adds no new dependency.
*
* Reference: BOLT 11, "Invoice Protocol for Lightning Payments".
*/
import { bech32 } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils';
/** A decoded BOLT11 invoice. Only the fields we need are surfaced. */
export interface DecodedInvoice {
/**
* Amount in millisatoshis, or `null` when the invoice is *amountless* —
* meaning the payer or the payee chooses the sum. Never pay an amountless
* invoice on the user's behalf.
*/
amountMsat: number | null;
/** Network prefix from the human-readable part: `bc`, `tb`, `bcrt`, `sb`. */
network: string;
/** Hex 32-byte payment hash (`p` field). */
paymentHash?: string;
/** Hex 32-byte description hash (`h` field), if the invoice carries one. */
descriptionHash?: string;
/** Plain-text description (`d` field), if the invoice carries one. */
description?: string;
/** Hex 33-byte payee node id (`n` field), if the invoice carries one. */
payee?: string;
/** Invoice creation time, in Unix seconds. */
timestamp: number;
/** Seconds after {@link timestamp} that the invoice expires. */
expiry: number;
}
/** Millisatoshis in one bitcoin. */
const MSAT_PER_BTC = 100_000_000_000n;
/**
* BOLT11 amount multipliers, as the divisor applied to {@link MSAT_PER_BTC}.
* `p` (pico) divides to 1/10 msat, so pico amounts must be a multiple of 10.
*/
const MULTIPLIERS: Record<string, bigint> = {
m: 1_000n,
u: 1_000_000n,
n: 1_000_000_000n,
p: 1_000_000_000_000n,
};
/** `ln` + network + optional amount. Longer prefixes first (`bcrt` vs `bc`). */
const HRP_RE = /^ln(bcrt|bc|tbs|tb|sb)(?:(\d+)([munp])?)?$/;
/** BOLT11 tagged-field types, as bech32 word values. */
const TAG_PAYMENT_HASH = 1; // 'p'
const TAG_DESCRIPTION = 13; // 'd'
const TAG_PAYEE = 19; // 'n'
const TAG_DESCRIPTION_HASH = 23; // 'h'
const TAG_EXPIRY = 6; // 'x'
/** Words occupied by the trailing signature (65 bytes = 520 bits). */
const SIGNATURE_WORDS = 104;
/** Words occupied by the leading timestamp (35 bits). */
const TIMESTAMP_WORDS = 7;
/** BOLT11's default expiry when no `x` field is present. */
const DEFAULT_EXPIRY = 3600;
/**
* Pack 5-bit bech32 words into bytes, discarding any trailing bits that do
* not complete a byte. BOLT11 fields are not all byte-aligned (a 32-byte hash
* occupies 52 words = 260 bits), so `bech32.fromWords` — which rejects
* leftover bits — cannot be used here.
*/
function wordsToBytes(words: number[]): Uint8Array {
const out = new Uint8Array(Math.floor((words.length * 5) / 8));
let acc = 0;
let bits = 0;
let i = 0;
for (const word of words) {
acc = (acc << 5) | word;
bits += 5;
while (bits >= 8) {
bits -= 8;
out[i++] = (acc >> bits) & 0xff;
}
}
return out;
}
/** Read a big-endian integer out of 5-bit words. */
function wordsToInt(words: number[]): number {
let value = 0;
for (const word of words) {
value = value * 32 + word;
}
return value;
}
/** Parse the amount out of a BOLT11 human-readable part, in millisatoshis. */
function parseHrpAmount(digits: string | undefined, multiplier: string | undefined): number | null {
if (!digits) return null;
const value = BigInt(digits);
const divisor = multiplier ? MULTIPLIERS[multiplier] : 1n;
const numerator = value * MSAT_PER_BTC;
if (numerator % divisor !== 0n) {
// Sub-millisatoshi precision. BOLT11 forbids it, and we can't pay it.
throw new Error('Invalid BOLT11 invoice: amount is not a whole number of millisatoshis');
}
const msat = numerator / divisor;
if (msat > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new Error('Invalid BOLT11 invoice: amount is implausibly large');
}
return Number(msat);
}
/**
* Decode a BOLT11 invoice, verifying its bech32 checksum and structure.
*
* Throws on anything that is not a well-formed invoice. The signature is not
* checked — verifying it would only prove the invoice was signed by whoever
* the invoice itself names as payee, which tells us nothing we didn't already
* decide by choosing to talk to that endpoint. What matters to callers is the
* *amount* and the *description hash*, both of which are covered here.
*/
export function decodeBolt11(invoice: string): DecodedInvoice {
const trimmed = invoice.trim().replace(/^lightning:/i, '');
const lowered = trimmed.toLowerCase();
if (!lowered.startsWith('ln')) {
throw new Error('Invalid BOLT11 invoice: missing "ln" prefix');
}
// `false` disables bech32's 90-character limit, which invoices exceed.
const { prefix, words } = bech32.decode(lowered as `${Lowercase<string>}1${string}`, false);
const hrp = HRP_RE.exec(prefix);
if (!hrp) {
throw new Error('Invalid BOLT11 invoice: unrecognized prefix');
}
const [, network, digits, multiplier] = hrp;
const amountMsat = parseHrpAmount(digits, multiplier);
if (words.length < TIMESTAMP_WORDS + SIGNATURE_WORDS) {
throw new Error('Invalid BOLT11 invoice: truncated');
}
const timestamp = wordsToInt(words.slice(0, TIMESTAMP_WORDS));
const tagged = words.slice(TIMESTAMP_WORDS, words.length - SIGNATURE_WORDS);
const decoded: DecodedInvoice = { amountMsat, network, timestamp, expiry: DEFAULT_EXPIRY };
for (let i = 0; i + 3 <= tagged.length;) {
const type = tagged[i];
const length = tagged[i + 1] * 32 + tagged[i + 2];
const start = i + 3;
const end = start + length;
if (end > tagged.length) {
throw new Error('Invalid BOLT11 invoice: tagged field overruns the invoice');
}
const data = tagged.slice(start, end);
i = end;
switch (type) {
case TAG_PAYMENT_HASH:
if (length === 52) decoded.paymentHash = bytesToHex(wordsToBytes(data));
break;
case TAG_DESCRIPTION_HASH:
if (length === 52) decoded.descriptionHash = bytesToHex(wordsToBytes(data));
break;
case TAG_PAYEE:
if (length === 53) decoded.payee = bytesToHex(wordsToBytes(data));
break;
case TAG_DESCRIPTION:
decoded.description = new TextDecoder().decode(wordsToBytes(data));
break;
case TAG_EXPIRY:
decoded.expiry = wordsToInt(data);
break;
}
}
return decoded;
}
/**
* Assert that `invoice` is payable for exactly `expectedMsat`.
*
* LNURL-pay endpoints are chosen by the *recipient*, so the invoice they hand
* back is attacker-controlled whenever the recipient is hostile. Without this
* check the recipient — not the sender — decides how much the sender pays.
*
* Returns the decoded invoice so callers can report the amount they actually
* paid rather than the one they asked for.
*/
export function assertInvoiceAmount(
invoice: string,
expectedMsat: number,
): DecodedInvoice & { amountMsat: number } {
let decoded: DecodedInvoice;
try {
decoded = decodeBolt11(invoice);
} catch (error) {
throw new Error(
`Lightning service returned an unreadable invoice: ${
error instanceof Error ? error.message : 'unknown error'
}`,
);
}
if (decoded.amountMsat === null) {
throw new Error(
'Lightning service returned an invoice with no amount, which would let it charge any sum. Payment cancelled.',
);
}
if (decoded.amountMsat !== expectedMsat) {
throw new Error(
`Lightning service returned an invoice for ${Math.round(decoded.amountMsat / 1000)} sats, ` +
`but ${Math.round(expectedMsat / 1000)} sats was requested. Payment cancelled.`,
);
}
return { ...decoded, amountMsat: decoded.amountMsat };
}
/**
* Check an invoice's `h` field against the strings it is allowed to commit to.
*
* LUD-06 binds the invoice to the LNURL endpoint's `metadata`; NIP-57 replaces
* that with the zap request JSON. Providers implement one or the other, so any
* match is accepted. An invoice with no `h` field at all is accepted too —
* plenty of providers use a plain `d` description — because the amount check
* is what actually stops an overcharge; this is defence in depth against a
* substituted invoice on an otherwise honest response.
*/
export function invoiceCommitsTo(decoded: DecodedInvoice, candidates: string[]): boolean {
if (!decoded.descriptionHash) return true;
// Use noble's own `utf8ToBytes` rather than `TextEncoder`: under jsdom the
// latter returns a Uint8Array from a different realm, which `sha256` rejects.
return candidates.some(
(candidate) => bytesToHex(sha256(utf8ToBytes(candidate))) === decoded.descriptionHash,
);
}
+174
View File
@@ -0,0 +1,174 @@
import { describe, it, expect, vi, afterEach } from "vitest";
import {
isEffectivelyEmptyModule,
resolveEmptyModuleFallback,
stripAssetUrlWildcard,
} from "./esmPlugin";
describe("stripAssetUrlWildcard", () => {
it("strips esm.sh's leading /* wildcard prefix from asset URLs", () => {
expect(
stripAssetUrlWildcard(
"https://esm.sh/*@fontsource/[email protected]/files/x.woff2",
),
).toBe("https://esm.sh/@fontsource/[email protected]/files/x.woff2");
});
it("preserves the query string (e.g. the lp breadcrumb)", () => {
expect(
stripAssetUrlWildcard(
"https://esm.sh/*@fontsource/foo@1/files/y.woff?lp=node_modules%252F%2540fontsource%252Ffoo",
),
).toBe(
"https://esm.sh/@fontsource/foo@1/files/y.woff?lp=node_modules%252F%2540fontsource%252Ffoo",
);
});
it("leaves URLs without a wildcard prefix unchanged", () => {
const url = "https://esm.sh/@fontsource/foo@1/files/y.woff2?lp=abc";
expect(stripAssetUrlWildcard(url)).toBe(url);
});
it("only strips a leading /* in the path, not a * elsewhere", () => {
const url = "https://esm.sh/@scope/pkg@1/a*b/file.woff2";
expect(stripAssetUrlWildcard(url)).toBe(url);
});
it("returns the input unchanged when it is not a valid URL", () => {
expect(stripAssetUrlWildcard("not a url")).toBe("not a url");
});
it("produces a url() value with no literal /* (the Tailwind tokenizer trap)", () => {
const fixed = stripAssetUrlWildcard(
"https://esm.sh/*@fontsource/[email protected]/files/x.woff2",
);
expect(`src: url(${fixed})`).not.toContain("/*");
});
});
describe("isEffectivelyEmptyModule", () => {
it("treats a file with only source-map comments as empty", () => {
const source =
"\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map";
expect(isEffectivelyEmptyModule(source)).toBe(true);
});
it("treats a jsDelivr-bannered empty bundle as empty", () => {
const source = [
"/**",
" * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.48.0.",
" * Original file: /npm/@solana/[email protected]/dist/index.browser.mjs",
" */",
"//# sourceMappingURL=/sm/abc.map",
].join("\n");
expect(isEffectivelyEmptyModule(source)).toBe(true);
});
it("treats a 'use strict' prologue with no code as empty", () => {
expect(isEffectivelyEmptyModule("'use strict';\n//# sourceMappingURL=x.map")).toBe(true);
});
it("treats a bare `export {};` as empty", () => {
expect(isEffectivelyEmptyModule("export {};")).toBe(true);
});
it("does not treat a module with real exports as empty", () => {
expect(isEffectivelyEmptyModule("export const x = 1;")).toBe(false);
});
it("does not treat a module with imports as empty", () => {
expect(isEffectivelyEmptyModule("import './side-effect.js';")).toBe(false);
});
it("does not treat a module with executable code as empty", () => {
expect(isEffectivelyEmptyModule("console.log('hi');")).toBe(false);
});
});
describe("resolveEmptyModuleFallback", () => {
afterEach(() => {
vi.restoreAllMocks();
});
it("synthesizes an empty module when jsDelivr runtime is empty", async () => {
const fetchMock = vi.fn(async () => ({
ok: true,
text: async () => "\n//# sourceMappingURL=index.browser.mjs.map",
})) as unknown as typeof fetch;
vi.stubGlobal("fetch", fetchMock);
const result = await resolveEmptyModuleFallback(
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
new Map(),
);
expect(result).toBe("export {};\n");
expect(fetchMock).toHaveBeenCalledWith(
"https://cdn.jsdelivr.net/npm/@solana/rpc-parsed-types/+esm",
);
});
it("recovers the version from the lockfile index", async () => {
const fetchMock = vi.fn(async () => ({
ok: true,
text: async () => "//# sourceMappingURL=x.map",
})) as unknown as typeof fetch;
vi.stubGlobal("fetch", fetchMock);
const nameVersionToPaths = new Map<string, string[]>([
["@solana/[email protected]", ["node_modules/@solana/rpc-parsed-types"]],
]);
await resolveEmptyModuleFallback(
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
nameVersionToPaths,
);
expect(fetchMock).toHaveBeenCalledWith(
"https://cdn.jsdelivr.net/npm/@solana/[email protected]/+esm",
);
});
it("returns undefined for a non-empty package (does not mask real failures)", async () => {
const fetchMock = vi.fn(async () => ({
ok: true,
text: async () => "export const isNumber = () => true;",
})) as unknown as typeof fetch;
vi.stubGlobal("fetch", fetchMock);
const result = await resolveEmptyModuleFallback(
"https://esm.sh/*[email protected]?target=esnext",
new Map(),
);
expect(result).toBeUndefined();
});
it("returns undefined when the jsDelivr fallback also fails", async () => {
const fetchMock = vi.fn(async () => ({
ok: false,
text: async () => "",
})) as unknown as typeof fetch;
vi.stubGlobal("fetch", fetchMock);
const result = await resolveEmptyModuleFallback(
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
new Map(),
);
expect(result).toBeUndefined();
});
it("does not attempt recovery for non-JS asset requests", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const result = await resolveEmptyModuleFallback(
"https://esm.sh/[email protected]/styles.css?target=esnext",
new Map(),
);
expect(result).toBeUndefined();
expect(fetchMock).not.toHaveBeenCalled();
});
});
+160 -10
View File
@@ -255,14 +255,22 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
? path.split("/").slice(0, 2).join("/")
: path.split("/")[0];
// If the importer is CSS, ignore (no JS deps)
try {
const { pathname } = new URL(args.importer);
if (/\.css$/.test(pathname)) {
return; // CSS imports don't have external dependencies
}
} catch {
// not a URL; continue
// When the importer is a CSS file, treat `@import "tailwindcss"`
// and its subpaths (`tailwindcss/preflight`, `/theme`, `/utilities`)
// as external so the Tailwind v4 `@tailwindcss/browser` runtime can
// process them at runtime (the v4 runtime special-cases these and
// rejects all other `@import` specifiers). Any other bare CSS
// `@import` falls through to the normal CDN resolution below, which
// will load the dependency as CSS content and bundle it inline
// (esm.sh redirects bare package specifiers for CSS-only packages
// to their `.css` entry, which the `onLoad` handler picks up via
// the `text/css` content-type -> `loader: "css"` mapping).
const importerIsCss = /\.css(?:\?|$)/.test(args.importer ?? "");
if (importerIsCss && /^tailwindcss(?:\/|$)/.test(path)) {
return {
path: args.path,
external: true,
};
}
// Check if this is a file: dependency
@@ -408,7 +416,10 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
const ext = extname(fullURL.pathname).slice(1);
if (ext && !["ts", "tsx", "js", "jsx", "mjs", "cjs", "css", "json"].includes(ext)) {
return {
path: fullURL.toString(),
// Strip esm.sh's `/*` wildcard prefix so the URL is safe to embed
// verbatim in CSS `url()` (a literal `/*` there is misread as a CSS
// comment by some parsers, including the Tailwind v4 runtime).
path: stripAssetUrlWildcard(fullURL.toString()),
external: true,
};
}
@@ -439,6 +450,20 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
}
if (!res.ok) {
// Some packages ship only TypeScript types with an effectively-empty
// runtime JS file (e.g. `@solana/rpc-parsed-types`). esm.sh's build
// pipeline rejects these zero-export modules with an HTTP 500, even
// though the package is perfectly valid — consumers only import its
// types at compile time. When that happens, fall back to a raw CDN
// (jsDelivr) to inspect the actual runtime. If the runtime is indeed
// empty (no exports/imports/code), synthesize an empty ES module so
// the build can proceed. Genuine failures (non-empty modules that
// failed for other reasons) are re-thrown unchanged.
const empty = await resolveEmptyModuleFallback(args.path, nameVersionToPaths);
if (empty !== undefined) {
return { contents: empty, loader: "js" };
}
throw new Error(`Failed to fetch ${args.path}`);
}
@@ -469,8 +494,11 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
// Convert `?url` imports to URL strings pointing to the ESM CDN
build.onLoad({ filter: /.*/, namespace: "esm-file-external" }, (args) => {
// Strip esm.sh's `/*` wildcard prefix: these URLs are asset references
// that may be embedded in CSS, where a literal `/*` in `url()` breaks
// some CSS parsers (including the Tailwind v4 runtime).
return {
contents: `export default ${JSON.stringify(args.path)};`,
contents: `export default ${JSON.stringify(stripAssetUrlWildcard(args.path))};`,
loader: "js",
};
});
@@ -501,3 +529,125 @@ function extractPackageName(esmURL: string): { pkg?: string; version?: string }
return { pkg, version };
}
/**
* Remove esm.sh's leading `/*` wildcard prefix from an asset URL's path.
*
* Shakespeare resolves CDN modules through esm.sh's `*` ("externalize all
* dependencies") prefix, e.g. `https://esm.sh/*@fontsource/x@1/...`. That `*`
* only influences how esm.sh builds JavaScript modules; for raw static assets
* (fonts, images, wasm, …) it is meaningless and esm.sh serves the identical
* file with or without it.
*
* The prefix is harmful when the asset URL is written verbatim into CSS:
* `src: url(https://esm.sh/*@fontsource/...woff2)` contains a literal `/*`
* inside an unquoted `url()`, which several CSS parsers (notably the in-browser
* Tailwind v4 tokenizer) misread as the start of a CSS comment. The
* tokenizer then scans past the rule's closing `}`, leaving the `@font-face`
* rule unterminated and throwing "Missing closing } at font-face".
*
* Stripping the wildcard from asset URLs keeps the emitted CSS parseable by all
* CSS parsers. JS module URLs are left untouched (they are not passed through
* this helper) since they legitimately rely on the `*` prefix.
*/
export function stripAssetUrlWildcard(urlStr: string): string {
try {
const url = new URL(urlStr);
if (!url.pathname.startsWith("/*")) return urlStr;
url.pathname = url.pathname.replace(/^\/\*/, "/");
return url.toString();
} catch {
return urlStr;
}
}
/**
* Determine whether a chunk of JavaScript is an "empty" runtime module — i.e.
* it contains no executable code and no ES `import`/`export` statements once
* comments and whitespace are stripped. This is the signature of a types-only
* package whose compiled JS is intentionally empty.
*/
export function isEffectivelyEmptyModule(source: string): boolean {
const stripped = source
// Block comments (including jsDelivr/esm.sh banners and sourceMappingURL)
.replace(/\/\*[\s\S]*?\*\//g, "")
// Line comments (covers `//# sourceMappingURL=...`)
.replace(/^\s*\/\/.*$/gm, "")
// Directive prologues like `'use strict';` / `"use strict";`
.replace(/^\s*(['"])use strict\1\s*;?\s*$/gm, "")
.trim();
if (stripped.length === 0) return true;
// If there's any leftover content, only treat it as empty when it carries no
// imports, exports, or other meaningful tokens. A bare `export {};` counts as
// empty (it exports nothing), but anything else is a real module.
if (/^export\s*\{\s*\}\s*;?$/.test(stripped)) return true;
return false;
}
/**
* When esm.sh fails to build a module, attempt to recover by inspecting the
* package's actual runtime via jsDelivr's `+esm` endpoint. If that runtime is
* effectively empty (a types-only package), return an empty ES module string.
* Returns `undefined` when the package is not empty (so the caller should treat
* the original failure as fatal).
*/
export async function resolveEmptyModuleFallback(
esmURL: string,
nameVersionToPaths: Map<string, string[]>,
): Promise<string | undefined> {
let pkg: string | undefined;
let version: string | undefined;
try {
({ pkg, version } = extractPackageName(esmURL));
} catch {
return undefined;
}
if (!pkg) return undefined;
// Only attempt the empty-module recovery for JavaScript module requests.
// Asset/CSS/JSON failures are unrelated to the types-only-package problem and
// should remain fatal.
try {
const ext = extname(new URL(esmURL).pathname).slice(1).toLowerCase();
if (ext && !["js", "jsx", "mjs", "cjs", "ts", "tsx"].includes(ext)) {
return undefined;
}
} catch {
return undefined;
}
// The esm.sh URL for a transitive dependency often omits the version
// (e.g. `*@solana/rpc-parsed-types?target=esnext`). Recover it from the
// lockfile index when possible so the fallback fetch is deterministic.
if (!version) {
for (const key of nameVersionToPaths.keys()) {
const at = key.lastIndexOf("@");
if (at > 0 && key.slice(0, at) === pkg) {
version = key.slice(at + 1);
break;
}
}
}
const spec = version ? `${pkg}@${version}` : pkg;
const fallbackURL = `https://cdn.jsdelivr.net/npm/${spec}/+esm`;
try {
const res = await fetch(fallbackURL);
if (!res.ok) return undefined;
const text = await res.text();
if (isEffectivelyEmptyModule(text)) {
return "export {};\n";
}
} catch {
return undefined;
}
return undefined;
}
+140 -76
View File
@@ -3,6 +3,8 @@ import { join, dirname, extname } from "path-browserify";
import type { Loader, Plugin } from "esbuild-wasm";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { detectWorkersAndAssets, type WorkerMatch, type AssetMatch } from "./workerPlugin";
interface TsConfig {
compilerOptions?: {
baseUrl?: string;
@@ -21,10 +23,17 @@ interface FsPluginOptions {
cwd: string;
tsconfig?: TsConfig;
packageJson?: PackageJson;
/**
* Optional collectors populated when a source file contains
* `new Worker(new URL(...))` / `new SharedWorker(new URL(...))` /
* `new URL(..., import.meta.url)` patterns.
*/
collectWorkers?: WorkerMatch[];
collectAssets?: AssetMatch[];
}
export function fsPlugin(options: FsPluginOptions): Plugin {
const { fs, cwd, tsconfig, packageJson } = options;
const { fs, cwd, tsconfig, packageJson, collectWorkers, collectAssets } = options;
return {
name: "fs",
@@ -42,74 +51,17 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
return;
}
let resolved: string | undefined;
// Handle absolute paths
if (args.path.startsWith("/")) {
resolved = args.path;
}
// Handle @/ alias
else if (args.path.startsWith("@/")) {
resolved = join(cwd, "src", args.path.slice(2));
}
// Handle relative paths
else if (args.importer && (args.path.startsWith("./") || args.path.startsWith("../"))) {
// Remove fs: prefix from importer if present
const importerPath = args.importer.replace(/^fs:/, '');
resolved = join(dirname(importerPath), args.path);
}
// Handle bare imports (e.g., "react", "@scope/package")
else if (args.path.match(/^[^./]/)) {
// Check if this is a file: dependency
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
const allDeps = {
...packageJson?.dependencies,
...packageJson?.devDependencies,
...packageJson?.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
// Extract the file path (e.g., "file:./path" -> "./path")
const filePath = depVersion.slice(5); // Remove "file:" prefix
const packagePath = join(cwd, filePath);
// Get the subpath within the package (e.g., "package/subdir/file" -> "/subdir/file")
const subpath = args.path.slice(packageName.length);
resolved = join(packagePath, subpath);
} else {
return; // Let esmPlugin handle this
}
}
// Handle tsconfig baseUrl
else if (args.importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, args.path);
}
// Nothing matched, let other plugins handle it
else {
return;
}
if (!resolved) {
return;
}
const resolved = await resolveFromImporter(args.path, args.importer, {
fs,
cwd,
tsconfig,
packageJson,
});
// Vite query parameters https://vite.dev/guide/assets
const [cleaned, query] = resolved.split("?");
try {
resolved = await tryFileVariants(fs, cleaned);
} catch {
return; // Let other plugins handle this
}
if (!resolved) return;
return {
path: resolved + (typeof query === "string" ? "?" + query : ""),
path: resolved,
namespace: "fs",
};
});
@@ -138,8 +90,41 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
};
}
let contents = await fs.readFile(path, "utf8");
// Run worker/asset detection on source-code files. This only
// does any real work if the file contains `new URL(`; the
// prefilter inside `detectWorkersAndAssets` bails early
// otherwise.
if (
(collectWorkers || collectAssets) &&
["ts", "tsx", "js", "jsx", "mjs", "cjs"].includes(ext)
) {
const result = await detectWorkersAndAssets({
source: contents,
filePath: path,
ext,
resolveSpec: async (spec, importerPath) => {
const resolved = await resolveFromImporter(spec, importerPath, {
fs,
cwd,
tsconfig,
packageJson,
});
if (!resolved) return undefined;
// Strip any ?query that made it onto the resolved path.
return resolved.split("?")[0];
},
});
if (result.workers.length || result.assets.length) {
contents = result.code;
if (collectWorkers) collectWorkers.push(...result.workers);
if (collectAssets) collectAssets.push(...result.assets);
}
}
return {
contents: await fs.readFile(path, "utf8"),
contents,
loader: ext as Loader,
};
},
@@ -148,6 +133,85 @@ export function fsPlugin(options: FsPluginOptions): Plugin {
};
}
interface ResolveContext {
fs: JSRuntimeFS;
cwd: string;
tsconfig?: TsConfig;
packageJson?: PackageJson;
}
/**
* Resolve a module specifier against an importer. This mirrors the
* resolution rules used by the fs plugin's onResolve handler so it
* can be reused by the worker/asset detection pass.
*/
export async function resolveFromImporter(
path: string,
importer: string | undefined,
ctx: ResolveContext,
): Promise<string | undefined> {
const { fs, cwd, tsconfig, packageJson } = ctx;
let resolved: string | undefined;
// Handle absolute paths
if (path.startsWith("/")) {
resolved = path;
}
// Handle @/ alias
else if (path.startsWith("@/")) {
resolved = join(cwd, "src", path.slice(2));
}
// Handle relative paths
else if (importer && (path.startsWith("./") || path.startsWith("../"))) {
const importerPath = importer.replace(/^fs:/, '');
resolved = join(dirname(importerPath), path);
}
// Handle bare imports (e.g., "react", "@scope/package")
else if (path.match(/^[^./]/)) {
const packageName = path.startsWith("@")
? path.split("/").slice(0, 2).join("/")
: path.split("/")[0];
const allDeps = {
...packageJson?.dependencies,
...packageJson?.devDependencies,
...packageJson?.peerDependencies,
};
const depVersion = allDeps[packageName];
if (depVersion && depVersion.startsWith("file:")) {
const filePath = depVersion.slice(5);
const packagePath = join(cwd, filePath);
const subpath = path.slice(packageName.length);
resolved = join(packagePath, subpath);
} else {
return undefined;
}
}
// Handle tsconfig baseUrl
else if (importer && tsconfig?.compilerOptions?.baseUrl) {
resolved = join(cwd, tsconfig.compilerOptions.baseUrl, path);
}
else {
return undefined;
}
if (!resolved) return undefined;
// Vite query parameters https://vite.dev/guide/assets
const [cleaned, query] = resolved.split("?");
try {
resolved = await tryFileVariants(fs, cleaned);
} catch {
return undefined;
}
return resolved + (typeof query === "string" ? "?" + query : "");
}
async function tryFileVariants(
fs: JSRuntimeFS,
basePath: string,
@@ -167,23 +231,23 @@ async function tryFileVariants(
const packageJsonPath = join(basePath, "package.json");
const packageJsonText = await fs.readFile(packageJsonPath, "utf8");
const packageJson = JSON.parse(packageJsonText);
// Check for various entry point fields
const entryPoint = packageJson.exports?.['.']
|| packageJson.module
|| packageJson.main
|| packageJson.module
|| packageJson.main
|| 'index.js';
// Resolve the entry point
const entryPath = typeof entryPoint === 'string'
const entryPath = typeof entryPoint === 'string'
? join(basePath, entryPoint)
: join(basePath, 'index.js');
const entryStat = await statSafe(fs, entryPath);
if (entryStat.isFile()) {
return entryPath;
}
// Try with different extensions if the entry point doesn't exist
for (const ext of extensions) {
const entryWithExt = entryPath.replace(/\.[^.]+$/, '') + ext;
@@ -195,7 +259,7 @@ async function tryFileVariants(
} catch {
// package.json doesn't exist or is invalid, fall through to index files
}
// Fall back to trying index files
for (const ext of extensions) {
const indexFile = join(basePath, "index" + ext);
@@ -228,4 +292,4 @@ async function statSafe(fs: JSRuntimeFS, filePath: string): Promise<{ isFile():
isDirectory: () => false,
};
}
}
}
+35 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import { buildProject } from './index';
import { buildProject, updateCSPForEsmSh } from './index';
import { copyFiles } from '../copyFiles';
import type { JSRuntimeFS } from '../JSRuntime';
@@ -594,4 +594,38 @@ react@^18.0.0:
// Verify package.json was read
expect(mockFS.readFile).toHaveBeenCalledWith('/test/project/package.json', 'utf8');
});
});
describe('updateCSPForEsmSh', () => {
const esmUrl = 'https://esm.shakespeare.diy';
it('extends the standard ESM directives with the CDN', () => {
const csp = "default-src 'self'; script-src 'self'; img-src 'self'";
const result = updateCSPForEsmSh(csp, esmUrl);
expect(result).toContain(`script-src 'self' ${esmUrl}`);
expect(result).toContain(`img-src 'self' ${esmUrl}`);
});
it('does NOT extend worker-src by default', () => {
const csp = "script-src 'self'; worker-src 'self'";
const result = updateCSPForEsmSh(csp, esmUrl);
// worker-src should remain untouched (still 'self' only).
expect(result).toContain("worker-src 'self'");
expect(result).not.toMatch(new RegExp(`worker-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`));
});
it('extends worker-src and child-src when emittedWorkers is true', () => {
const csp = "script-src 'self'";
const result = updateCSPForEsmSh(csp, esmUrl, { emittedWorkers: true });
// The directives may be seeded with 'self' if absent; what matters
// is that the CDN is present in each.
expect(result).toMatch(new RegExp(`worker-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`));
expect(result).toMatch(new RegExp(`child-src[^;]*${esmUrl.replace(/[.]/g, '\\.')}`));
});
it('extends existing worker-src directive without seeding when already present', () => {
const csp = "script-src 'self'; worker-src 'self' blob:";
const result = updateCSPForEsmSh(csp, esmUrl, { emittedWorkers: true });
expect(result).toMatch(new RegExp(`worker-src 'self' blob: ${esmUrl.replace(/[.]/g, '\\.')}`));
});
});
+276 -12
View File
@@ -8,6 +8,7 @@ import { shakespearePlugin } from "./shakespearePlugin";
import { esmPlugin } from "./esmPlugin";
import { fsPlugin } from "./fsPlugin";
import { convertYarnLockToPackageLock } from "./yarnLockConverter";
import type { WorkerMatch, AssetMatch } from "./workerPlugin";
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { Plugin } from 'esbuild-wasm';
@@ -51,6 +52,37 @@ export interface BuildContext {
tsconfig?: TsConfig;
}
/** Tailwind CSS variant used by a project (or `null` if Tailwind is not enabled). */
export type TailwindVariant = "v3" | "v4" | null;
/**
* Detect which major version of Tailwind CSS a project uses by inspecting the
* `tailwindcss` entry in package.json (dependencies, devDependencies, or
* peerDependencies). Returns `null` when no Tailwind dependency is declared.
*
* The version string is matched loosely: any leading non-digit characters
* (such as `^`, `~`, `>=`, or `v`) are stripped before reading the major
* number. Ranges like `>=3.0.0 <5.0.0`, git URLs, or other non-standard
* specifiers fall through to `null`, which callers should treat as "skip
* Tailwind injection entirely".
*/
export function detectTailwindVariant(packageJson: PackageJson): TailwindVariant {
const spec =
packageJson.dependencies?.tailwindcss ??
packageJson.devDependencies?.tailwindcss ??
packageJson.peerDependencies?.tailwindcss;
if (!spec) return null;
const match = spec.match(/(\d+)/);
if (!match) return null;
const major = Number(match[1]);
if (major >= 4) return "v4";
if (major === 3) return "v3";
return null;
}
/**
* Read package.json, package-lock.json/yarn.lock, and tsconfig.json from project
* Exported for use by deployment adapters that need to bundle workers
@@ -112,6 +144,23 @@ export async function readBuildContext(
return { packageJson, packageLock, tsconfig };
}
export interface CreatePluginsOptions {
/**
* When provided, the fs plugin will scan source files for
* `new Worker(new URL(..., import.meta.url))` patterns and push
* matches here so the caller can build them as additional entry
* points.
*/
collectWorkers?: WorkerMatch[];
/**
* When provided, the fs plugin will scan source files for
* `new URL(..., import.meta.url)` patterns referencing non-source
* assets and push matches here so the caller can copy them into
* the output.
*/
collectAssets?: AssetMatch[];
}
/**
* Create the common esbuild plugins for both project and worker builds
* Exported for use by deployment adapters that need to bundle workers
@@ -122,10 +171,18 @@ export function createPlugins(
context: BuildContext,
esmUrl: string,
target?: string,
pluginOptions: CreatePluginsOptions = {},
): Plugin[] {
return [
shakespearePlugin({ esmUrl }),
fsPlugin({ fs, cwd: projectPath, tsconfig: context.tsconfig, packageJson: context.packageJson }),
fsPlugin({
fs,
cwd: projectPath,
tsconfig: context.tsconfig,
packageJson: context.packageJson,
collectWorkers: pluginOptions.collectWorkers,
collectAssets: pluginOptions.collectAssets,
}),
esmPlugin({ packageJson: context.packageJson, packageLock: context.packageLock, target, esmUrl }),
];
}
@@ -167,14 +224,27 @@ async function bundle(
}
}
// Enable Tailwind CSS if a config file is present
for (const path of ["tailwind.config.ts", "tailwind.config.js"]) {
if (await fileExists(fs, join(projectPath, path))) {
entryPoints.push(`shakespeare:${path}`);
break;
// Enable Tailwind CSS based on the version declared in package.json.
// v3 needs a synthetic entry that loads the Play CDN runtime and assigns
// the project's tailwind.config.{js,ts} to `window.tailwind.config`.
// v4 has no JS config (theming is CSS-based via `@theme`) and the
// `@tailwindcss/browser@4` runtime auto-scans the document, so the shim
// just needs to side-effect-import the runtime.
const tailwindVariant = detectTailwindVariant(context.packageJson);
if (tailwindVariant === "v3") {
for (const path of ["tailwind.config.ts", "tailwind.config.js"]) {
if (await fileExists(fs, join(projectPath, path))) {
entryPoints.push(`shakespeare:${path}`);
break;
}
}
} else if (tailwindVariant === "v4") {
entryPoints.push("shakespeare:tailwindcss@4");
}
const collectedWorkers: WorkerMatch[] = [];
const collectedAssets: AssetMatch[] = [];
const results = await esbuild.build({
entryPoints,
bundle: true,
@@ -188,7 +258,10 @@ async function bundle(
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: createPlugins(fs, projectPath, context, esmUrl, target),
plugins: createPlugins(fs, projectPath, context, esmUrl, target, {
collectWorkers: collectedWorkers,
collectAssets: collectedAssets,
}),
define: {
"import.meta.env": JSON.stringify({}),
},
@@ -222,12 +295,140 @@ async function bundle(
}
}
// Parse CSP and ensure ESM CDN is allowed for necessary directives
// Build each unique collected worker as its own ESM chunk, looping
// to pick up any nested workers / assets they themselves collect.
// Each iteration passes the same collector arrays so newly
// discovered entries feed the next iteration.
const placeholderToFilename = new Map<string, string>();
const workerQueue: WorkerMatch[] = [...collectedWorkers];
const seenWorkerPaths = new Set<string>();
while (workerQueue.length > 0) {
const nextBatch = workerQueue.splice(0, workerQueue.length);
for (const worker of nextBatch) {
if (seenWorkerPaths.has(worker.resolvedPath)) {
// Reuse the output from the prior build of this same worker.
const existing = findPlaceholderForPath(placeholderToFilename, worker.resolvedPath);
if (existing) {
placeholderToFilename.set(worker.placeholder, existing);
}
continue;
}
seenWorkerPaths.add(worker.resolvedPath);
const before = {
workers: collectedWorkers.length,
assets: collectedAssets.length,
};
const workerResult = await esbuild.build({
entryPoints: [worker.resolvedPath],
bundle: true,
write: false,
format: "esm",
target,
outdir: "/",
jsx: "automatic",
metafile: true,
sourcemap: true,
entryNames: "[name]-[hash]",
chunkNames: "[name]-[hash]",
assetNames: "[name]-[hash]",
plugins: createPlugins(fs, projectPath, context, esmUrl, target, {
collectWorkers: collectedWorkers,
collectAssets: collectedAssets,
}),
define: {
"import.meta.env": JSON.stringify({}),
},
});
let entryFilename: string | undefined;
for (const file of workerResult.outputFiles) {
const filename = file.path.slice(1);
dist[filename] = file.contents;
const outMeta = workerResult.metafile.outputs[filename];
if (outMeta?.entryPoint && !entryFilename && filename.endsWith(".js")) {
entryFilename = filename;
}
}
if (!entryFilename) {
// Fall back to the first .js output.
const firstJs = workerResult.outputFiles.find((f) => f.path.endsWith(".js"));
if (firstJs) entryFilename = firstJs.path.slice(1);
}
if (!entryFilename) {
throw new Error(`Failed to bundle worker: ${worker.resolvedPath}`);
}
// Record placeholder -> "./<filename>" so main-bundle rewrites
// produce URLs that resolve correctly against import.meta.url
// of the main bundle (which lives at the same origin/dir).
placeholderToFilename.set(worker.placeholder, "./" + entryFilename);
// Record the file path -> filename mapping in a secondary index
// via the placeholder (so the dedup branch above can find it).
placeholderToFilename.set(`@path:${worker.resolvedPath}`, entryFilename);
// New workers / assets discovered during this sub-build get
// queued.
if (collectedWorkers.length > before.workers) {
workerQueue.push(...collectedWorkers.slice(before.workers));
}
}
}
// Copy each unique collected asset into the output directory with
// a content-hashed filename.
const assetPathToFilename = new Map<string, string>();
for (const asset of collectedAssets) {
let outName = assetPathToFilename.get(asset.resolvedPath);
if (!outName) {
const bytes = await fs.readFile(asset.resolvedPath);
const data = bytes instanceof Uint8Array ? bytes : new TextEncoder().encode(String(bytes));
const hash = await shortContentHash(data);
const base = asset.resolvedPath.split("/").pop() ?? "asset";
const dot = base.lastIndexOf(".");
const stem = dot > 0 ? base.slice(0, dot) : base;
const ext = dot > 0 ? base.slice(dot) : "";
outName = `${stem}-${hash}${ext}`;
dist[outName] = data;
assetPathToFilename.set(asset.resolvedPath, outName);
}
placeholderToFilename.set(asset.placeholder, "./" + outName);
}
// Substitute placeholders in every JS output file.
if (placeholderToFilename.size > 0) {
const decoder = new TextDecoder();
const encoder = new TextEncoder();
for (const [filename, contents] of Object.entries(dist)) {
if (!filename.endsWith(".js")) continue;
let text = decoder.decode(contents);
let changed = false;
for (const [placeholder, replacement] of placeholderToFilename) {
if (placeholder.startsWith("@path:")) continue;
if (text.includes(placeholder)) {
text = text.split(placeholder).join(replacement.startsWith("./") ? replacement.slice(2) : replacement);
changed = true;
}
}
if (changed) {
dist[filename] = encoder.encode(text);
}
}
}
// Parse CSP and ensure ESM CDN is allowed for necessary directives.
// If any workers were emitted, also extend worker-src / child-src so
// the browser permits module workers and workers importing from the
// ESM CDN.
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
if (cspMeta) {
const cspContent = cspMeta.getAttribute("content");
if (cspContent) {
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl);
const updatedCSP = updateCSPForEsmSh(cspContent, esmUrl, {
emittedWorkers: collectedWorkers.length > 0,
});
cspMeta.setAttribute("content", updatedCSP);
}
}
@@ -238,6 +439,42 @@ async function bundle(
return dist;
}
function findPlaceholderForPath(
placeholderToFilename: Map<string, string>,
resolvedPath: string,
): string | undefined {
const key = `@path:${resolvedPath}`;
const filename = placeholderToFilename.get(key);
return filename ? "./" + filename : undefined;
}
async function shortContentHash(data: Uint8Array): Promise<string> {
// Use SubtleCrypto if available (browsers, modern Node via webcrypto
// global); fall back to a simple non-cryptographic hash for test
// environments that stub out crypto.
try {
const subtle = (globalThis as { crypto?: { subtle?: SubtleCrypto } }).crypto?.subtle;
if (subtle?.digest) {
const buf = await subtle.digest("SHA-256", data);
const bytes = new Uint8Array(buf);
let hex = "";
for (let i = 0; i < 8; i++) {
hex += bytes[i].toString(16).padStart(2, "0");
}
return hex;
}
} catch {
// fall through
}
// FNV-1a-ish fallback (good enough for filename uniqueness).
let h = 0x811c9dc5;
for (let i = 0; i < data.length; i++) {
h ^= data[i];
h = Math.imul(h, 0x01000193);
}
return (h >>> 0).toString(16).padStart(8, "0");
}
/**
* Build project and write output files to the filesystem
*/
@@ -328,15 +565,42 @@ async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
}
/** Updates CSP to allow ESM CDN for scripts, assets, fonts, and CSS */
export function updateCSPForEsmSh(csp: string, esmUrl: string): string {
export function updateCSPForEsmSh(
csp: string,
esmUrl: string,
options: { emittedWorkers?: boolean } = {},
): string {
const esmDirectives = [
'script-src', // For JavaScript modules
'img-src', // For images
'media-src', // For video/audio
'font-src', // For fonts
'style-src', // For CSS
'connect-src' // For fetch/XHR requests to ESM CDN
'connect-src', // For fetch/XHR requests to ESM CDN
];
return addDomainToCSP(csp, esmUrl, esmDirectives);
let updated = addDomainToCSP(csp, esmUrl, esmDirectives);
if (options.emittedWorkers) {
// Module workers load from the same origin; when they import from
// the ESM CDN, worker-src (and child-src for older browsers) must
// list the CDN as well. These directives may not exist in the
// project's CSP, so seed them before extending.
updated = ensureDirective(updated, 'worker-src');
updated = ensureDirective(updated, 'child-src');
updated = addDomainToCSP(updated, esmUrl, ['worker-src', 'child-src']);
}
return updated;
}
/**
* Ensure a CSP directive exists. If absent, seed it with `'self'` so
* subsequent `addDomainToCSP` calls have something to extend.
*/
function ensureDirective(csp: string, directive: string): string {
const re = new RegExp(`(^|;)\\s*${directive}\\s`);
if (re.test(csp)) return csp;
const trimmed = csp.trim().replace(/;\s*$/, '');
return trimmed ? `${trimmed}; ${directive} 'self'` : `${directive} 'self'`;
}
+21 -1
View File
@@ -14,7 +14,9 @@ export function shakespearePlugin(options: ShakespearePluginOptions): Plugin {
name: "shakespeare",
setup(build) {
// Handle Tailwind CSS configuration files
// Handle Tailwind CSS configuration files (v3).
// The synthetic entry loads the v3 Play CDN runtime and assigns the
// project's tailwind.config.{js,ts} to the global `tailwind.config`.
build.onResolve({ filter: /^shakespeare:tailwind\.config\.(js|ts)$/ }, (args) => {
return {
path: args.path,
@@ -34,6 +36,24 @@ export function shakespearePlugin(options: ShakespearePluginOptions): Plugin {
};
});
// Handle Tailwind CSS v4 runtime.
// v4 has no JS config (theming is done in CSS via `@theme`) and the
// `@tailwindcss/browser@4` runtime auto-detects `<style type="text/tailwindcss">`
// blocks in the document, so the shim just side-effect-imports the runtime.
build.onResolve({ filter: /^shakespeare:tailwindcss@4$/ }, (args) => {
return {
path: args.path,
namespace: "shakespeare-tailwind-v4",
};
});
build.onLoad({ filter: /.*/, namespace: "shakespeare-tailwind-v4" }, () => {
return {
contents: `import "${options.esmUrl}/@tailwindcss/browser@4";`,
loader: "js",
};
});
// Handle "sonner" imports with a dummy API
build.onResolve({ filter: /^sonner$/ }, (args) => {
return {
+286
View File
@@ -0,0 +1,286 @@
import { describe, it, expect, vi } from "vitest";
// Mock getEsbuild so we can unit-test detection without the real wasm.
// The mock's transform is loader-aware: for "ts"/"tsx"/"jsx" it strips
// obvious TS/JSX constructs enough for acorn to parse. In practice, if
// the input is already valid JS, we just pass it through.
vi.mock("@/lib/esbuild", () => ({
getEsbuild: vi.fn(async () => ({
transform: vi.fn(async (source: string) => ({ code: source })),
})),
}));
import { detectWorkersAndAssets } from "./workerPlugin";
const identityResolver = async (spec: string, importer: string): Promise<string | undefined> => {
// A trivial resolver that pretends any relative/@ spec resolves to
// an absolute path. Extension determines whether it's a source file.
if (spec.startsWith("./") || spec.startsWith("../")) {
// Pretend to resolve by dropping the leading segment.
return importer.replace(/[^/]+$/, "") + spec.replace(/^\.\/?/, "");
}
if (spec.startsWith("@/")) {
return "/project/src/" + spec.slice(2);
}
if (spec.startsWith("/")) {
return spec;
}
return undefined;
};
describe("detectWorkersAndAssets", () => {
it("returns source unchanged when file contains no `new URL(`", async () => {
const source = `
import React from 'react';
export const x = 1;
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.code).toBe(source);
expect(result.workers).toEqual([]);
expect(result.assets).toEqual([]);
});
it("detects a module Worker with @/ alias specifier", async () => {
const source = [
"const w = new Worker(",
" new URL('@/workers/my-worker.ts', import.meta.url),",
" { type: 'module' },",
");",
].join("\n");
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.workers[0].resolvedPath).toBe("/project/src/workers/my-worker.ts");
expect(result.workers[0].kind).toBe("Worker");
// Placeholder should appear in the rewritten code.
expect(result.code).toContain(result.workers[0].placeholder);
// Original spec string should be gone.
expect(result.code).not.toContain("@/workers/my-worker.ts");
// import.meta.url reference should be preserved.
expect(result.code).toContain("import.meta.url");
});
it("detects a SharedWorker", async () => {
const source = `
const w = new SharedWorker(
new URL('./w.ts', import.meta.url),
{ type: 'module' },
);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.workers[0].kind).toBe("SharedWorker");
});
it("errors on classic (non-module) worker", async () => {
const source = `
const w = new Worker(new URL('./w.ts', import.meta.url));
`;
await expect(
detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
}),
).rejects.toThrow(/type: 'module'/);
});
it("errors on non-literal worker specifier", async () => {
const source = `
const p = './dyn.ts';
const w = new Worker(new URL(p, import.meta.url), { type: 'module' });
`;
await expect(
detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
}),
).rejects.toThrow(/string literal/i);
});
it("errors when worker specifier does not resolve", async () => {
const source = `
const w = new Worker(new URL('./missing.ts', import.meta.url), { type: 'module' });
`;
await expect(
detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: async () => undefined,
}),
).rejects.toThrow(/could not resolve worker module/i);
});
it("detects plain new URL() asset and rewrites it", async () => {
const source = `
const u = new URL('./logo.svg', import.meta.url);
console.log(u);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.assets).toHaveLength(1);
expect(result.assets[0].resolvedPath).toBe("/project/src/logo.svg");
expect(result.code).toContain(result.assets[0].placeholder);
expect(result.code).not.toContain("./logo.svg");
});
it("does not rewrite plain new URL() when target is a source file", async () => {
const source = `
const u = new URL('./thing.ts', import.meta.url);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.assets).toEqual([]);
expect(result.code).toBe(source);
});
it("does not rewrite new URL() with a non-literal first argument", async () => {
const source = `
const p = './thing.svg';
const u = new URL(p, import.meta.url);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.assets).toEqual([]);
expect(result.workers).toEqual([]);
expect(result.code).toBe(source);
});
it("does not rewrite new URL() with an absolute https:// spec", async () => {
const source = `
const u = new URL('https://example.com/x.png', import.meta.url);
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.assets).toEqual([]);
expect(result.code).toBe(source);
});
it("does not double-rewrite the inner new URL() of a Worker", async () => {
const source = `
const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });
`;
// Resolver returns a non-source extension for './w.ts' would
// otherwise ambiguously pull the inner URL into the asset pass.
// Using ts extension makes it unambiguous: worker match only.
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.assets).toHaveLength(0);
});
it("handles both workers and assets in the same file", async () => {
const source = `
const img = new URL('./logo.png', import.meta.url);
const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.assets).toHaveLength(1);
expect(result.assets[0].resolvedPath).toBe("/project/src/logo.png");
expect(result.workers[0].resolvedPath).toBe("/project/src/w.ts");
// Both placeholders present.
expect(result.code).toContain(result.workers[0].placeholder);
expect(result.code).toContain(result.assets[0].placeholder);
});
it("does not match patterns inside string literals", async () => {
const source = [
"const s = \"new Worker(new URL('./w.ts', import.meta.url), { type: 'module' })\";",
].join("\n");
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toEqual([]);
expect(result.assets).toEqual([]);
expect(result.code).toBe(source);
});
it("does not match patterns inside line comments", async () => {
const source = [
"// const w = new Worker(new URL('./w.ts', import.meta.url), { type: 'module' });",
"export const x = 1;",
].join("\n");
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toEqual([]);
expect(result.code).toBe(source);
});
it("supports double-quoted specifiers", async () => {
const source = `
const w = new Worker(new URL("./w.ts", import.meta.url), { type: "module" });
`;
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
expect(result.code).toContain(result.workers[0].placeholder);
});
it("supports backtick-quoted specifiers with no interpolation", async () => {
const source = [
"const w = new Worker(new URL(`./w.ts`, import.meta.url), { type: 'module' });",
].join("\n");
const result = await detectWorkersAndAssets({
source,
filePath: "/project/src/a.ts",
ext: "ts",
resolveSpec: identityResolver,
});
expect(result.workers).toHaveLength(1);
});
});
+438
View File
@@ -0,0 +1,438 @@
// Detection and rewriting for the Vite/webpack-compatible worker and
// asset URL patterns:
//
// new Worker(new URL("<spec>", import.meta.url), { type: "module" })
// new SharedWorker(new URL("<spec>", import.meta.url), { type: "module" })
// new URL("<spec>", import.meta.url) // for non-source assets
//
// esbuild-wasm exposes no onTransform/onParse hook, so we can't reuse
// esbuild's internal AST. To avoid parsing every source file a second
// time, we prefilter with a cheap regex and only invoke acorn on files
// that contain a relevant construct. TS/JSX files are stripped via
// esbuild.transform before being handed to acorn so we don't need a
// TypeScript-aware parser.
import * as acorn from "acorn";
import jsx from "acorn-jsx";
import { getEsbuild } from "@/lib/esbuild";
const ParserWithJsx = acorn.Parser.extend(jsx());
// Cheap prefilter: bail out for the 99% of files that contain no
// `new URL(` call at all.
const PREFILTER = /\bnew\s+URL\s*\(/;
export interface WorkerMatch {
/** Unique placeholder token written into the source in place of the spec string. */
placeholder: string;
/** Resolved absolute path of the worker entry in the VFS. */
resolvedPath: string;
/** "Worker" or "SharedWorker". */
kind: "Worker" | "SharedWorker";
}
export interface AssetMatch {
/** Unique placeholder token written into the source in place of the spec string. */
placeholder: string;
/** Resolved absolute path of the asset in the VFS. */
resolvedPath: string;
}
export interface DetectResult {
/** The (possibly) rewritten source text. */
code: string;
workers: WorkerMatch[];
assets: AssetMatch[];
}
export interface DetectOptions {
/** The original source text as stored in the VFS. */
source: string;
/** The path of the file being processed, for diagnostics. */
filePath: string;
/** Extension of the source ("ts", "tsx", "js", "jsx", "mjs", "cjs"). */
ext: string;
/**
* Resolve a module specifier relative to `filePath` against the VFS.
* Returns the resolved absolute path, or undefined if no file exists.
*/
resolveSpec: (spec: string, importerPath: string) => Promise<string | undefined>;
}
/**
* Source-code extensions that must NOT be treated as plain asset URLs.
* These should go through a regular import or the Worker pattern.
*/
const SOURCE_EXTENSIONS = new Set([
"ts",
"tsx",
"js",
"jsx",
"mjs",
"cjs",
"css",
]);
let placeholderCounter = 0;
function nextPlaceholder(prefix: "WORKER" | "ASSET"): string {
placeholderCounter += 1;
return `__SHAKESPEARE_${prefix}_URL_${placeholderCounter.toString(36)}__`;
}
/**
* Scan a source file for Worker / SharedWorker / asset URL patterns.
* Returns the rewritten source along with the collected matches.
*
* Throws with a human-readable message when a problem is found that
* should fail the build (classic worker, non-literal specifier,
* unresolvable specifier).
*/
export async function detectWorkersAndAssets(
options: DetectOptions,
): Promise<DetectResult> {
const { source, filePath, ext, resolveSpec } = options;
// Fast path: no `new URL(` anywhere.
if (!PREFILTER.test(source)) {
return { code: source, workers: [], assets: [] };
}
// Strip TS/JSX so acorn can parse it. We only reach this branch for
// files that contain `new URL(`, which is rare, so the transform
// cost is paid for very few files per build.
let jsSource = source;
const needsStrip = ext === "ts" || ext === "tsx" || ext === "jsx";
if (needsStrip) {
try {
const esbuild = await getEsbuild();
const result = await esbuild.transform(source, {
loader: ext === "ts" ? "ts" : ext === "tsx" ? "tsx" : "jsx",
sourcemap: false,
sourcefile: filePath,
// Preserve the shape of the source as much as possible; we're
// only using the output to parse, not to emit.
target: "esnext",
});
jsSource = result.code;
} catch {
// If the transform itself fails, skip worker detection; esbuild's
// main pass will surface the syntax error with a proper location.
return { code: source, workers: [], assets: [] };
}
}
// Parse.
let ast: acorn.Node;
try {
ast = ParserWithJsx.parse(jsSource, {
ecmaVersion: "latest",
sourceType: "module",
allowHashBang: true,
allowAwaitOutsideFunction: true,
});
} catch {
// If acorn can't parse (possibly because of syntax esbuild supports
// that acorn doesn't), skip detection and let the main build
// surface any real error.
return { code: source, workers: [], assets: [] };
}
// Walk the AST to find NewExpression nodes we care about.
// We operate on the stripped jsSource for position information, but
// the returned `code` must be the ORIGINAL source with rewrites
// applied. Since replacements are string-literal values (the first
// argument of `new URL`), we search for those literals in the
// original source to do the rewrite. This avoids any dependence on
// post-TS-strip positions.
const workers: WorkerMatch[] = [];
const assets: AssetMatch[] = [];
// Map spec -> list of { kind: "worker" | "asset", placeholder, resolvedPath }
// collected during the AST walk. We rewrite afterwards so that each
// *occurrence* of the spec in the original source that parses back
// to the same construct gets its own placeholder.
interface PendingRewrite {
spec: string;
kind: "worker" | "asset";
workerKind?: "Worker" | "SharedWorker";
resolvedPath: string;
}
const pending: PendingRewrite[] = [];
const seenUrlNodes = new WeakSet<acorn.Node>();
const walk = async (node: acorn.Node | null | undefined): Promise<void> => {
if (!node || typeof node !== "object") return;
// Process this node first (so Worker sees its inner new URL before
// the asset pass does).
await visit(node);
// Recurse into all child nodes.
for (const key of Object.keys(node)) {
if (key === "type" || key === "start" || key === "end" || key === "loc") continue;
const value = (node as unknown as Record<string, unknown>)[key];
if (Array.isArray(value)) {
for (const child of value) {
if (child && typeof child === "object" && "type" in child) {
await walk(child as acorn.Node);
}
}
} else if (value && typeof value === "object" && "type" in value) {
await walk(value as acorn.Node);
}
}
};
const visit = async (node: acorn.Node): Promise<void> => {
if (node.type !== "NewExpression") return;
const newExpr = node as unknown as {
type: "NewExpression";
callee: { type: string; name?: string };
arguments: acorn.Node[];
start: number;
end: number;
};
const calleeName =
newExpr.callee.type === "Identifier" ? newExpr.callee.name : undefined;
if (calleeName === "Worker" || calleeName === "SharedWorker") {
// new Worker(new URL(<spec>, import.meta.url), <opts>?)
const [arg0, arg1] = newExpr.arguments;
if (!isNewUrlWithImportMeta(arg0)) {
// Not the Vite pattern — leave alone.
return;
}
const urlNode = arg0 as unknown as {
type: "NewExpression";
arguments: acorn.Node[];
};
const specNode = urlNode.arguments[0];
if (!isStringLiteral(specNode)) {
throw new Error(
`${filePath}: new ${calleeName}(new URL(...)) requires a string literal as the first argument to new URL(). Dynamic specifiers are not supported.`,
);
}
// Require { type: 'module' } as the second argument.
if (!hasTypeModuleOption(arg1)) {
throw new Error(
`${filePath}: new ${calleeName}(new URL(...)) must pass { type: 'module' } as its second argument. Shakespeare does not support classic workers.`,
);
}
const spec = readStringLiteral(specNode)!;
const resolvedPath = await resolveSpec(spec, filePath);
if (!resolvedPath) {
throw new Error(
`${filePath}: could not resolve worker module '${spec}'.`,
);
}
// Mark the inner `new URL(...)` as "consumed" so the asset pass
// below doesn't also rewrite it.
seenUrlNodes.add(arg0);
pending.push({
spec,
kind: "worker",
workerKind: calleeName,
resolvedPath,
});
return;
}
if (calleeName === "URL") {
if (seenUrlNodes.has(node)) return;
if (!isNewUrlWithImportMeta(node)) return;
const specNode = newExpr.arguments[0];
if (!isStringLiteral(specNode)) {
// Non-literal `new URL(...)` is legal and common for runtime
// URL construction. Don't touch it.
return;
}
const spec = readStringLiteral(specNode)!;
// Only rewrite specs that look like module-relative paths.
// Anything else (absolute https://, etc.) is almost certainly a
// runtime URL and not a bundle asset reference.
if (!isRelativeOrAliasSpec(spec)) return;
const resolvedPath = await resolveSpec(spec, filePath);
if (!resolvedPath) {
// Can't resolve — probably a runtime URL; leave alone.
return;
}
// Skip source files — these should go through normal imports or
// the Worker pattern.
const resolvedExt = resolvedPath.split(".").pop()?.toLowerCase() ?? "";
if (SOURCE_EXTENSIONS.has(resolvedExt)) {
// Emit a console warning but don't fail the build.
console.warn(
`${filePath}: new URL('${spec}', import.meta.url) references a source file. Shakespeare only rewrites non-source assets via this pattern. Use a regular import or new Worker() instead.`,
);
return;
}
pending.push({ spec, kind: "asset", resolvedPath });
}
};
await walk(ast);
if (pending.length === 0) {
return { code: source, workers: [], assets: [] };
}
// Now apply the rewrites to the ORIGINAL source by replacing the
// string-literal spec. Each `pending` entry consumes the first
// remaining occurrence of its literal form so multiple identical
// specs each get their own placeholder.
//
// Match a quoted literal whose content equals `spec`. We match
// single quotes, double quotes, or backticks (template literal
// without interpolation) to cover all reasonable TS/JS source
// styles.
let code = source;
for (const entry of pending) {
const placeholder = nextPlaceholder(entry.kind === "worker" ? "WORKER" : "ASSET");
const { literal, index } = findNextSpecLiteral(code, entry.spec);
if (literal === null || index < 0) {
// Shouldn't normally happen (we parsed it); be defensive.
throw new Error(
`${filePath}: internal error rewriting new URL('${entry.spec}', ...); could not locate the literal in source.`,
);
}
const before = code.slice(0, index);
const after = code.slice(index + literal.length);
// Preserve the quote style of the original literal.
const quote = literal[0];
code = before + quote + placeholder + quote + after;
if (entry.kind === "worker") {
workers.push({
placeholder,
resolvedPath: entry.resolvedPath,
kind: entry.workerKind!,
});
} else {
assets.push({ placeholder, resolvedPath: entry.resolvedPath });
}
}
return { code, workers, assets };
}
function isNewUrlWithImportMeta(node: acorn.Node | null | undefined): boolean {
if (!node || node.type !== "NewExpression") return false;
const n = node as unknown as {
callee: { type: string; name?: string };
arguments: acorn.Node[];
};
if (n.callee.type !== "Identifier" || n.callee.name !== "URL") return false;
if (n.arguments.length < 2) return false;
return isImportMetaUrl(n.arguments[1]);
}
function isImportMetaUrl(node: acorn.Node | undefined): boolean {
if (!node || node.type !== "MemberExpression") return false;
const m = node as unknown as {
object: { type: string; meta?: { name?: string }; property?: { name?: string } };
property: { type: string; name?: string };
computed: boolean;
};
if (m.computed) return false;
if (m.property.type !== "Identifier" || m.property.name !== "url") return false;
if (m.object.type !== "MetaProperty") return false;
if (m.object.meta?.name !== "import") return false;
if (m.object.property?.name !== "meta") return false;
return true;
}
function isStringLiteral(node: acorn.Node | undefined): boolean {
return readStringLiteral(node) !== undefined;
}
function readStringLiteral(node: acorn.Node | undefined): string | undefined {
if (!node) return undefined;
if (node.type === "Literal") {
const v = (node as unknown as { value: unknown }).value;
return typeof v === "string" ? v : undefined;
}
if (node.type === "TemplateLiteral") {
const tl = node as unknown as {
expressions: unknown[];
quasis: Array<{ value: { cooked?: string } }>;
};
if (tl.expressions.length === 0 && tl.quasis.length === 1 &&
typeof tl.quasis[0].value.cooked === "string") {
return tl.quasis[0].value.cooked;
}
}
return undefined;
}
function hasTypeModuleOption(node: acorn.Node | undefined): boolean {
if (!node || node.type !== "ObjectExpression") return false;
const obj = node as unknown as {
properties: Array<{
type: string;
key: { type: string; name?: string; value?: unknown };
value: { type: string; value?: unknown };
computed: boolean;
}>;
};
for (const prop of obj.properties) {
if (prop.type !== "Property" || prop.computed) continue;
let keyName: string | undefined;
if (prop.key.type === "Identifier") {
keyName = prop.key.name;
} else if (prop.key.type === "Literal" && typeof prop.key.value === "string") {
keyName = prop.key.value;
}
if (keyName !== "type") continue;
if (prop.value.type === "Literal" && prop.value.value === "module") {
return true;
}
}
return false;
}
function isRelativeOrAliasSpec(spec: string): boolean {
return (
spec.startsWith("./") ||
spec.startsWith("../") ||
spec.startsWith("/") ||
spec.startsWith("@/")
);
}
/**
* Find the next occurrence of a string literal with the given content
* in `source`. Searches for `'spec'`, `"spec"`, and `` `spec` ``. The
* simplest, correct way: search for each possible quoted form and
* pick the earliest occurrence.
*/
function findNextSpecLiteral(
source: string,
spec: string,
): { literal: string | null; index: number } {
// Build the three possible source-text forms of the literal.
const candidates = [
encodeAsLiteral(spec, "'"),
encodeAsLiteral(spec, '"'),
encodeAsLiteral(spec, "`"),
];
let bestIdx = -1;
let best: string | null = null;
for (const lit of candidates) {
const idx = source.indexOf(lit);
if (idx >= 0 && (bestIdx < 0 || idx < bestIdx)) {
bestIdx = idx;
best = lit;
}
}
return { literal: best, index: bestIdx };
}
function encodeAsLiteral(value: string, quote: "'" | '"' | "`"): string {
// We don't do full JS escape handling — the spec is the parsed
// (decoded) value of a string literal, so the common case is that
// the literal appears in source verbatim as quote + value + quote.
// Escaped characters in the original source (e.g. \n) would
// de-encode to different bytes and won't match here, which means we
// fall through to the "internal error" case. In practice worker
// specs are paths with no escapes, so this is fine.
return quote + value + quote;
}
+4 -4
View File
@@ -30,15 +30,15 @@ describe('CatCommand', () => {
it('should have correct command properties', () => {
expect(catCommand.name).toBe('cat');
expect(catCommand.description).toBe('Concatenate and display file contents');
expect(catCommand.usage).toBe('cat [file...]');
expect(catCommand.usage).toBe('cat [-nbsETAvu] [--] [file...]');
});
it('should return error when no arguments provided', async () => {
it('should return empty output when no arguments and no stdin', async () => {
const result = await catCommand.execute([], testCwd);
expect(result.exitCode).toBe(1);
expect(result.stderr).toContain('missing file operand');
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe('');
expect(result.stderr).toBe('');
});
it('should read and return file content', async () => {
+146 -55
View File
@@ -1,16 +1,29 @@
import { join } from "path-browserify";
import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { classifyFsError, parseOptions, resolvePath } from "./utils";
/**
* Implementation of the 'cat' command
* Concatenate and display file contents
* Implementation of the 'cat' command.
*
* Concatenate files and/or standard input to standard output.
*
* Supported options (POSIX + common GNU extensions):
* -n Number all output lines (1-based)
* -b Number non-empty output lines only
* -s Squeeze multiple blank lines into one
* -E Display $ at end of each line
* -T Display tabs as ^I
* -A Equivalent to -vET (minus control-char rendering for -v)
* -v Display non-printing characters as ^X or M-X
* -u POSIX: unbuffered (accepted, no-op)
* -- End of options
* - Read from standard input at this position
*/
export class CatCommand implements ShellCommand {
name = 'cat';
description = 'Concatenate and display file contents';
usage = 'cat [file...]';
usage = 'cat [-nbsETAvu] [--] [file...]';
private fs: JSRuntimeFS;
@@ -19,65 +32,143 @@ export class CatCommand implements ShellCommand {
}
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
// If input is provided (from pipe), return it
if (input !== undefined) {
return createSuccessResult(input);
const parsed = parseOptions(args, {
booleanShort: ['n', 'b', 's', 'E', 'T', 'A', 'v', 'u'],
});
if (parsed.unknown.length > 0) {
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`);
}
// If no arguments provided, show usage
if (args.length === 0) {
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
// -A implies -vET
if (parsed.flags.has('A')) {
parsed.flags.add('v');
parsed.flags.add('E');
parsed.flags.add('T');
}
try {
const outputs: string[] = [];
// If no file operands (and no explicit `-`), default to stdin when input is provided,
// otherwise POSIX `cat` with no args reads stdin — we mirror that for pipelines.
const operands = parsed.operands.length > 0 ? parsed.operands : ['-'];
for (const filePath of args) {
try {
// Handle both absolute and relative paths
let absolutePath: string;
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
// It's an absolute path - use it directly
absolutePath = filePath;
} else {
// It's a relative path - resolve it relative to the current working directory
absolutePath = join(cwd, filePath);
}
// Check if path exists and is a file
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
// Read file content
const content = await this.fs.readFile(absolutePath, 'utf8');
outputs.push(content);
} catch (error) {
// Handle file not found or permission errors
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${filePath}: Unknown error`);
}
let combined = '';
for (const filePath of operands) {
if (filePath === '-') {
if (input === undefined) {
// No piped input and an explicit `-`: POSIX says read stdin; in our
// non-interactive environment, treat as empty.
continue;
}
combined += input;
continue;
}
// Join all file contents
const result = outputs.join('');
return createSuccessResult(result);
try {
const absolutePath = resolvePath(filePath, cwd);
const stats = await this.fs.stat(absolutePath);
if (stats.isDirectory()) {
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
}
const content = await this.fs.readFile(absolutePath, 'utf8');
combined += content;
} catch (error) {
const { kind } = classifyFsError(error);
if (kind === 'ENOENT') {
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
}
if (kind === 'EACCES') {
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
}
return createErrorResult(`${this.name}: ${filePath}: ${error instanceof Error ? error.message : String(error)}`);
}
}
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
// If no processing options are set, return raw content fast-path.
if (
!parsed.flags.has('n') &&
!parsed.flags.has('b') &&
!parsed.flags.has('s') &&
!parsed.flags.has('E') &&
!parsed.flags.has('T') &&
!parsed.flags.has('v')
) {
return createSuccessResult(combined);
}
const output = this.applyFilters(combined, parsed.flags);
return createSuccessResult(output);
}
private applyFilters(content: string, flags: Set<string>): string {
const hadTrailingNewline = content.endsWith('\n');
const bodyLines = (hadTrailingNewline ? content.slice(0, -1) : content).split('\n');
// -s: squeeze consecutive blank lines
let lines = bodyLines;
if (flags.has('s')) {
const squeezed: string[] = [];
let prevBlank = false;
for (const line of lines) {
const isBlank = line === '';
if (isBlank && prevBlank) continue;
squeezed.push(line);
prevBlank = isBlank;
}
lines = squeezed;
}
// -v: render non-printing characters
if (flags.has('v')) {
lines = lines.map((l) => renderNonPrinting(l, flags.has('T')));
}
// -T: show tabs as ^I
if (flags.has('T')) {
lines = lines.map((l) => l.replace(/\t/g, '^I'));
}
// -E: end-of-line markers
if (flags.has('E')) {
lines = lines.map((l) => l + '$');
}
// -n / -b: line numbering (-b wins over -n)
if (flags.has('b')) {
let n = 0;
lines = lines.map((l) => {
// -b numbers nonblank lines. With -E, $ was appended; check original blankness.
const original = flags.has('E') ? l.slice(0, -1) : l;
if (original === '') return '\t' + l;
n++;
return String(n).padStart(6) + '\t' + l;
});
} else if (flags.has('n')) {
lines = lines.map((l, idx) => String(idx + 1).padStart(6) + '\t' + l);
}
return lines.join('\n') + (hadTrailingNewline ? '\n' : '');
}
}
function renderNonPrinting(line: string, skipTab: boolean): string {
let out = '';
for (const ch of line) {
const code = ch.charCodeAt(0);
if (skipTab && ch === '\t') {
out += ch;
continue;
}
if (code < 32 && ch !== '\t') {
out += '^' + String.fromCharCode(code + 64);
} else if (code === 127) {
out += '^?';
} else if (code >= 128 && code < 160) {
out += 'M-^' + String.fromCharCode(code - 128 + 64);
} else if (code >= 160 && code < 256) {
out += 'M-' + String.fromCharCode(code - 128);
} else {
out += ch;
}
}
}
return out;
}
+21 -2
View File
@@ -30,7 +30,7 @@ describe('CdCommand', () => {
it('should have correct command properties', () => {
expect(cdCommand.name).toBe('cd');
expect(cdCommand.description).toBe('Change directory');
expect(cdCommand.usage).toBe('cd [directory]');
expect(cdCommand.usage).toBe('cd [-LP] [directory | -]');
});
it('should change to specified directory', async () => {
@@ -70,9 +70,28 @@ describe('CdCommand', () => {
expect(result.newCwd).toBe('/test/current');
});
it('should stay in current directory when no arguments', async () => {
it('should go to home directory when no arguments', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
cdCommand.setHomeDir('/home/user');
const result = await cdCommand.execute([], testCwd);
expect(result.exitCode).toBe(0);
expect(result.newCwd).toBe('/home/user');
});
it('should support cd - to go to OLDPWD', async () => {
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// First cd to establish OLDPWD
await cdCommand.execute(['/other'], testCwd);
// Now cd - should go back to testCwd
const result = await cdCommand.execute(['-'], '/other');
expect(result.exitCode).toBe(0);
expect(result.newCwd).toBe(testCwd);
});
+101 -64
View File
@@ -3,87 +3,124 @@ import type { JSRuntimeFS } from "../JSRuntime";
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
import { createSuccessResult, createErrorResult } from "./ShellCommand";
import { isAbsolutePath } from "../security";
import { parseOptions } from "./utils";
/**
* Implementation of the 'cd' command
* Change directory
* Implementation of the 'cd' command.
*
* Supported options:
* -L Follow symbolic links (default; no-op in our VFS)
* -P Use the physical directory, without symlinks (no-op in our VFS)
*
* Supported forms:
* cd → $HOME (defaults to '/' when unset)
* cd - → previous directory (OLDPWD)
* cd ~ → $HOME
* cd ~/foo → $HOME/foo
* cd .. → parent
* cd /abs/path → absolute
* cd rel/path → relative to CWD
*/
export class CdCommand implements ShellCommand {
name = 'cd';
description = 'Change directory';
usage = 'cd [directory]';
usage = 'cd [-LP] [directory | -]';
private fs: JSRuntimeFS;
/** Tracked previous working directory for `cd -`. */
private oldPwd: string | undefined;
/** Default home dir when HOME env var is not available. */
private homeDir = '/';
constructor(fs: JSRuntimeFS) {
this.fs = fs;
}
/** Optional hook used by the executor to supply HOME. */
setHomeDir(home: string): void {
this.homeDir = home;
}
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
const parsed = parseOptions(args, {
booleanShort: ['L', 'P'],
});
if (parsed.unknown.length > 0) {
return createErrorResult(`${this.name}: invalid option -- '${parsed.unknown[0].replace(/^-+/, '')}'`);
}
if (parsed.operands.length > 1) {
return createErrorResult(`${this.name}: too many arguments`);
}
let targetPath: string;
if (parsed.operands.length === 0) {
// cd with no args → $HOME
targetPath = this.homeDir;
} else {
targetPath = parsed.operands[0];
}
// Handle `cd -`
if (targetPath === '-') {
if (!this.oldPwd) {
return createErrorResult(`${this.name}: OLDPWD not set`);
}
const previous = this.oldPwd;
// POSIX: cd - prints the new directory and then chdir's to it.
const check = await this.checkDir(previous);
if (check) return check;
this.oldPwd = cwd;
return createSuccessResult(previous + '\n', previous);
}
// Tilde expansion (tokenizer normally handles this, but handle leftovers).
if (targetPath === '~' || targetPath.startsWith('~/')) {
targetPath = this.homeDir + targetPath.slice(1);
}
let newCwd: string;
if (isAbsolutePath(targetPath)) {
newCwd = targetPath;
} else if (targetPath === '.') {
newCwd = cwd;
} else if (targetPath === '..') {
const parentPath = dirname(cwd);
newCwd = parentPath || '/';
} else {
newCwd = join(cwd, targetPath);
}
newCwd = resolve(newCwd);
const err = await this.checkDir(newCwd, targetPath);
if (err) return err;
this.oldPwd = cwd;
return createSuccessResult('', newCwd);
}
private async checkDir(path: string, display?: string): Promise<ShellCommandResult | null> {
const label = display ?? path;
try {
let targetPath: string;
if (args.length === 0) {
// cd with no arguments - stay in current directory for simplicity
return createSuccessResult('', cwd);
} else if (args.length === 1) {
targetPath = args[0];
} else {
return createErrorResult(`${this.name}: too many arguments`);
const stats = await this.fs.stat(path);
if (!stats.isDirectory()) {
return createErrorResult(`${this.name}: ${label}: Not a directory`);
}
// Handle both absolute and relative paths
let newCwd: string;
if (isAbsolutePath(targetPath)) {
// Absolute path - use it directly
newCwd = targetPath;
} else if (targetPath === '.') {
// Current directory
newCwd = cwd;
} else if (targetPath === '..') {
// Parent directory
const parentPath = dirname(cwd);
// Don't allow going above the filesystem root
if (parentPath === cwd) {
return createErrorResult(`${this.name}: cannot access parent directory: Permission denied`);
}
newCwd = parentPath;
} else {
// Relative path
newCwd = join(cwd, targetPath);
}
// Normalize the path
newCwd = resolve(newCwd);
// Check if the target directory exists and is a directory
try {
const stats = await this.fs.stat(newCwd);
if (!stats.isDirectory()) {
return createErrorResult(`${this.name}: ${targetPath}: Not a directory`);
}
} catch (error) {
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${targetPath}: No such file or directory`);
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${targetPath}: Permission denied`);
} else {
return createErrorResult(`${this.name}: ${targetPath}: ${error.message}`);
}
} else {
return createErrorResult(`${this.name}: ${targetPath}: Unknown error`);
}
}
// Return success with the new working directory
return createSuccessResult('', newCwd);
return null;
} catch (error) {
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
if (error instanceof Error) {
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
return createErrorResult(`${this.name}: ${label}: No such file or directory`);
}
if (error.message.includes('EACCES') || error.message.includes('permission')) {
return createErrorResult(`${this.name}: ${label}: Permission denied`);
}
return createErrorResult(`${this.name}: ${label}: ${error.message}`);
}
return createErrorResult(`${this.name}: ${label}: Unknown error`);
}
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ describe('CpCommand', () => {
it('should have correct command properties', () => {
expect(cpCommand.name).toBe('cp');
expect(cpCommand.description).toBe('Copy files and directories');
expect(cpCommand.usage).toBe('cp [-r] source... destination');
expect(cpCommand.usage).toBe('cp [-rRfinpavT] [--] source... destination');
});
it.skip('should copy a file', async () => {
Loaded 100 of 230 files, more files were not shown because too many files have changed in this diff. Show more