Skip to content
Myr

Merge build/1411-web-import into main

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by oscabriel · committed by oscabriel · parents 7a90542, 81c99ad · Browse files · 22 files+1774 added−33 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

22 files+1774 added−33 removed

  • tests:+641 added−24 removed
  • other:+1133 added−9 removed

22 files+1774 added−33 removed

added:apps/web/e2e/import.e2e.ts+116 added
1/**2 * A web import, as a browser does it: signed in, `/import?url=<repo>`3 * fills the form (owner and name from the URL), Import runs it, the page4 * says "Importing…" while the platform clones, and lands on the project's5 * page, which names where it was imported from. Saved as6 * `e2e/out/import.png`.7 *8 * It runs only when `WEB_IMPORT_URL` names a tiny public repo to import9 * (an HTTPS clone URL) and `WEB_URL` a web's origin, and is skipped10 * otherwise. It signs in with `WEB_SESSION`, a session token for the11 * stage, or, without one, through the dev world's own `/auth/dev` as12 * `WEB_IMPORT_AS` (oscabriel unless given). `WEB_IMPORT_NAME` names the13 * project instead of the URL's last segment, so a second run does not meet14 * `ProjectExists`. It writes: each run makes a project.15 */16import { expect, test } from "@playwright/test";17import { Config, Effect, Option, Redacted } from "effect";1819const settings = Effect.runSync(20 Effect.gen(function* () {21 return {22 as: yield* Config.NonEmptyString("WEB_IMPORT_AS").pipe(23 Config.withDefault("oscabriel")24 ),25 name: yield* Config.option(Config.NonEmptyString("WEB_IMPORT_NAME")),26 repo: yield* Config.option(Config.NonEmptyString("WEB_IMPORT_URL")),27 session: yield* Config.option(Config.Redacted("WEB_SESSION")),28 web: Option.map(29 yield* Config.option(Config.NonEmptyString("WEB_URL")),30 (url) => url.replace(/\/+$/u, "")31 ),32 };33 })34);3536/** Where the screenshot goes: `e2e/out/import.png`. */37const out = decodeURIComponent(new URL("out/", import.meta.url).pathname);3839/** An import clones the repo: up to half a minute, and some margin. */40const IMPORTING = 90_000;4142test.describe("a web import", () => {43 test.skip(44 Option.isNone(settings.repo) || Option.isNone(settings.web),45 "WEB_IMPORT_URL and WEB_URL are not both set: name a tiny public repo and a web's origin to run this check"46 );4748 test.setTimeout(IMPORTING + 30_000);4950 test("imports a public repo from /import and lands on its project", ({51 context,52 page,53 }) =>54 Effect.runPromise(55 Effect.gen(function* () {56 const web = Option.getOrElse(settings.web, () => "");57 const repo = Option.getOrElse(settings.repo, () => "");5859 yield* Option.match(settings.session, {60 onNone: () =>61 Effect.promise(() =>62 page.goto(`${web}/auth/dev?handle=${settings.as}`)63 ),64 onSome: (token) =>65 Effect.promise(() =>66 context.addCookies([67 {68 name: "__Host-session",69 secure: true,70 url: web,71 value: Redacted.value(token),72 },73 ])74 ),75 });7677 yield* Effect.promise(() =>78 page.goto(`${web}/import?${new URLSearchParams({ url: repo })}`)79 );8081 const form = page.getByRole("form", { name: "Import a repo" });8283 yield* Effect.promise(() =>84 expect(form.getByLabel("Repo URL")).toHaveValue(repo)85 );8687 const { name } = settings;8889 if (Option.isSome(name)) {90 yield* Effect.promise(() => form.getByLabel("Name").fill(name.value));91 }9293 yield* Effect.promise(() =>94 form.getByRole("button", { name: "Import" }).click()95 );9697 yield* Effect.promise(() =>98 expect(form.getByRole("button", { name: "Importing…" })).toBeVisible()99 );100101 yield* Effect.promise(() =>102 page.waitForURL((url) => url.pathname !== "/import", {103 timeout: IMPORTING,104 })105 );106107 yield* Effect.promise(() =>108 expect(page.getByText(repo).first()).toBeVisible()109 );110111 yield* Effect.promise(() =>112 page.screenshot({ fullPage: true, path: `${out}import.png` })113 );114 })115 ));116});
added:apps/web/src/client/import.ts+41 added
modified:apps/web/src/features/home/home-page.tsx+6 added-1 removed
29 unmodified lines
30 answerPath,31 ASKS_PATH,32 askPath,33 HOME_PATH,34 IMPORT_PATH,35 personPath,36} from "../shared/paths.ts";37import { UnreachableNotice } from "../shared/pending.tsx";38import {
297 unmodified lines
336 <AskList asks={asks} />337 </RowGroup>338);339339/** Who is signed in, and the way to their record. */340/** Who is signed in, the way to their record, and the way to import a repo. */341const Record = ({ handle }: { readonly handle: Handle }) => (342 <>343 Signed in as <HandleLink handle={handle} />.{" "}344 <AppLink className={LINK} to={personPath(handle)}>345 Your record346 </AppLink>347 {" · "}348 <AppLink className={LINK} to={IMPORT_PATH}>349 Import a repo350 </AppLink>351 </>352);353354const SignedIn = ({
52 unmodified lines
added:apps/web/src/features/import/client-owner.tsx+66 added
added:apps/web/src/features/import/import-form.tsx+436 added
1/**2 * The import form: a signed-in person pastes a public repo's HTTPS URL,3 * may name a branch, picks the owner and the name, and presses Import. The4 * owner and the name follow the URL until the person changes them: the5 * URL's source namespace (`github.com/pallets`) when its host is one the6 * platform knows, else their handle; the URL's last segment as the name.7 * At a source namespace's address the owner is the address's, fixed.8 * Signed out, it says what would be imported and links to sign-in, coming9 * back to `here`. Props in, markup out: the route reads who is signed in,10 * sends the payload, and goes to the project once it is made.11 *12 * Nothing is imported until Import is pressed; nothing here asks a host13 * anything.14 */15import { Brand } from "@repo/brand";16import type {17 Handle,18 Owner,19 ShortName,20 SourceNamespace,21} from "@repo/protocol/ids";22import { Option } from "effect";23import { LogIn } from "lucide-react";24import { useId, useState } from "react";25import type { ReactNode } from "react";2627import { Button } from "../../components/ui/button.tsx";28import { Input } from "../../components/ui/input.tsx";29import { Spinner } from "../../components/ui/spinner.tsx";30import { signInHref } from "../auth/session-slot.tsx";31import { CommandLine } from "../shared/command.tsx";32import { ClientOwnerSelect } from "./client-owner.tsx";33import {34 importPayload,35 importSourceOf,36 ownerChoices,37 ownerOfNamespace,38 prefillFrom,39} from "./prefill.ts";40import type { ImportPayload } from "./prefill.ts";4142/** What the form starts with: a URL, and the owner and name it gives. */43export interface ImportPrefill {44 readonly url: string;45 readonly owner?: SourceNamespace | undefined;46 readonly name?: ShortName | undefined;47}4849/** Who is importing, and what became of the last press. */50export interface Importer {51 /** The handle signed in in this browser; none signed out. */52 readonly handle: Option.Option<Handle>;53 /** Whether the browser is still learning who is signed in. */54 readonly checking?: boolean | undefined;55 /** Whether an import is on its way: the button waits. */56 readonly busy?: boolean | undefined;57 /** Sends the payload; the route goes to the project once it is made. */58 readonly onImport?: ((payload: ImportPayload) => void) | undefined;59 /** What the last import came back with, when it was refused. */60 readonly refusal?: ReactNode | undefined;61}6263export interface ImportFormProps extends Importer {64 readonly prefill?: ImportPrefill | undefined;65 /** The owner the address fixes, at a source namespace's address. */66 readonly fixedOwner?: SourceNamespace | undefined;67 /** The page's own address, where sign-in comes back to. */68 readonly here: string;69}7071/** The import as a command, for a reader in a terminal. */72export const importCommand = (project = "<owner>/<name>", url = "<url>") =>73 `${Brand.cli} init --project ${project} --import ${url}`;7475const LINK = "decoration-rule font-medium underline hover:decoration-current";7677/** A field's label and the words under it. */78const LABEL = "text-ui font-medium";7980const HINT = "text-label text-muted-foreground font-normal";8182/**83 * A text field in mono: 16 px on a phone, so it does not zoom on focus, and84 * without ligatures, as code shows what was typed (`://` stays three).85 */86const MONO_FIELD =87 "tablet:h-9 tablet:text-mono h-11 font-mono text-base [font-feature-settings:'calt'_0,'liga'_0]";8889/** What Import says, by where the form stands: why it waits, or what it does. */90const IMPORT_WORDS = {91 busy: "Importing…",92 noName: "Name the project",93 noOwner: "No owner you may import under",94 noUrl: "Paste a repo's URL first",95 ready: "Import",96} as const;9798type FormState = keyof typeof IMPORT_WORDS;99100/** Where the form stands: importing, waiting on a field, or ready. */101const formState = ({102 branch,103 busy,104 owner,105 payload,106 url,107}: {108 readonly busy: boolean;109 readonly owner: Owner | undefined;110 readonly payload: Option.Option<ImportPayload>;111 readonly url: string;112 readonly branch: string;113}): FormState => {114 if (busy) {115 return "busy";116 }117118 if (Option.isNone(importSourceOf({ branch, url }))) {119 return "noUrl";120 }121122 if (owner === undefined) {123 return "noOwner";124 }125126 return Option.isSome(payload) ? "ready" : "noName";127};128129const SignInToImport = ({130 fixedOwner,131 here,132 prefill,133}: Pick<ImportFormProps, "fixedOwner" | "here" | "prefill">) => {134 const name = prefill?.name;135136 const project =137 fixedOwner === undefined || name === undefined138 ? undefined139 : `${fixedOwner}/${name}`;140141 return (142 <section143 aria-label="Sign in to import"144 className="flex max-w-[70ch] flex-col items-start gap-4"145 >146 {prefill === undefined || prefill.url === "" ? null : (147 <dl className="border-rule flex w-full flex-col border-y">148 <div className="flex flex-col gap-0.5 py-2.5">149 <dt className={HINT}>Repo URL</dt>150 <dd className="text-mono font-mono [overflow-wrap:anywhere]">151 <code>{prefill.url}</code>152 </dd>153 </div>154 {project === undefined ? null : (155 <div className="border-rule flex flex-col gap-0.5 border-t py-2.5">156 <dt className={HINT}>Project</dt>157 <dd className="text-mono font-mono [overflow-wrap:anywhere]">158 <code>{project}</code>159 </dd>160 </div>161 )}162 </dl>163 )}164 <p className="text-ui flex items-start gap-2">165 <LogIn166 aria-hidden="true"167 className="mt-0.5 size-4 shrink-0"168 strokeWidth={1.75}169 />170 <span>171 Importing is for signed-in people.{" "}172 <a className={LINK} href={signInHref(here)}>173 Sign in174 </a>{" "}175 to import it here, or import from a terminal:176 </span>177 </p>178 <CommandLine179 command={importCommand(180 project,181 prefill === undefined || prefill.url === "" ? undefined : prefill.url182 )}183 />184 </section>185 );186};187188/** The owner, fixed by the address: in sight, and in the form. */189const FixedOwner = ({190 hintId,191 owner,192}: {193 readonly hintId: string;194 readonly owner: SourceNamespace;195}) => (196 <>197 <p aria-describedby={hintId} className="text-want font-medium">198 {owner}199 </p>200 <input name="owner" type="hidden" value={owner} />201 </>202);203204/** What the hint under Owner says, by what may be chosen. */205const ownerHint = (fixed: boolean, choices: readonly Owner[]) => {206 if (fixed) {207 return "The address names it: the project keeps its source's account.";208 }209210 return choices.length > 1211 ? "The URL's own account, or your handle."212 : "Your handle: this URL's host is not one a project may be owned by.";213};214215/** Under Name: the project's address once the name is one, else what a name is. */216const NameHint = ({217 payload,218}: {219 readonly payload: Option.Option<ImportPayload>;220}) =>221 Option.match(payload, {222 onNone: () =>223 "Lowercase letters and digits, joined by single dots, dashes or underscores.",224 onSome: ({ project }) => (225 <>226 The project&apos;s address:{" "}227 <code className="text-mono text-foreground font-mono [overflow-wrap:anywhere]">228 /{project}229 </code>230 </>231 ),232 });233234const Form = ({235 busy = false,236 fixedOwner,237 handle,238 onImport,239 prefill,240 refusal,241}: Pick<242 ImportFormProps,243 "busy" | "fixedOwner" | "handle" | "onImport" | "prefill" | "refusal"244>) => {245 const id = useId();246 const [url, setUrl] = useState(prefill?.url ?? "");247 const [branch, setBranch] = useState("");248 const [chosen, setChosen] = useState<string | undefined>(prefill?.owner);249 const [typed, setTyped] = useState<string | undefined>(prefill?.name);250251 const choices =252 fixedOwner === undefined253 ? ownerChoices(handle, url)254 : Option.toArray(ownerOfNamespace(fixedOwner));255256 const owner = choices.find((choice) => choice === chosen) ?? choices[0];257258 const name: string =259 typed ?? Option.getOrElse(prefillFrom(url).name, () => "");260261 const payload =262 owner === undefined263 ? Option.none()264 : importPayload({ branch, name, owner, url });265266 const state = formState({ branch, busy, owner, payload, url });267268 return (269 <form270 aria-label="Import a repo"271 className="flex max-w-[70ch] flex-col gap-6"272 data-import=""273 onSubmit={(event) => {274 event.preventDefault();275276 if (!busy && Option.isSome(payload)) {277 onImport?.(payload.value);278 }279 }}280 >281 <div className="flex flex-col gap-1.5">282 <label className={LABEL} htmlFor={`${id}-url`}>283 Repo URL284 </label>285 <Input286 aria-describedby={`${id}-url-hint`}287 autoCapitalize="off"288 autoComplete="off"289 className={MONO_FIELD}290 id={`${id}-url`}291 inputMode="url"292 name="url"293 onChange={(event) => {294 setUrl(event.target.value);295 }}296 placeholder="https://github.com/pallets/click"297 // At a source namespace's address the URL is the address's own.298 readOnly={busy || fixedOwner !== undefined}299 required300 spellCheck={false}301 type="url"302 value={url}303 />304 <p className={HINT} id={`${id}-url-hint`}>305 {fixedOwner === undefined306 ? "Any public repo over HTTPS: GitHub, GitLab, Codeberg, Bitbucket or another host."307 : "Rebuilt from this page's address."}308 </p>309 </div>310311 <div className="flex flex-col gap-1.5">312 <label className={LABEL} htmlFor={`${id}-branch`}>313 Branch <span className={HINT}>(optional)</span>314 </label>315 <Input316 aria-describedby={`${id}-branch-hint`}317 autoCapitalize="off"318 autoComplete="off"319 className={`${MONO_FIELD} max-w-sm`}320 id={`${id}-branch`}321 name="branch"322 onChange={(event) => {323 setBranch(event.target.value);324 }}325 readOnly={busy}326 spellCheck={false}327 value={branch}328 />329 <p className={HINT} id={`${id}-branch-hint`}>330 Left empty, the repo&apos;s default branch.331 </p>332 </div>333334 <div className="flex flex-col gap-1.5">335 <span className={LABEL} id={`${id}-owner`}>336 Owner337 </span>338 {fixedOwner === undefined ? (339 <ClientOwnerSelect340 choices={choices}341 describedBy={`${id}-owner-hint`}342 labelledBy={`${id}-owner`}343 onChange={setChosen}344 value={owner}345 />346 ) : (347 <FixedOwner hintId={`${id}-owner-hint`} owner={fixedOwner} />348 )}349 <p className={HINT} id={`${id}-owner-hint`}>350 {ownerHint(fixedOwner !== undefined, choices)}351 </p>352 </div>353354 <div className="flex flex-col gap-1.5">355 <label className={LABEL} htmlFor={`${id}-name`}>356 Name357 </label>358 <Input359 aria-describedby={`${id}-name-hint`}360 autoCapitalize="off"361 autoComplete="off"362 className={`${MONO_FIELD} max-w-sm`}363 id={`${id}-name`}364 name="name"365 onChange={(event) => {366 setTyped(event.target.value);367 }}368 readOnly={busy}369 required370 spellCheck={false}371 value={name}372 />373 <p className={HINT} id={`${id}-name-hint`}>374 <NameHint payload={payload} />375 </p>376 </div>377378 {refusal}379380 <div className="flex flex-col gap-2">381 <Button382 // Waiting for a URL or a name, it says so at full strength, dashed383 // like any field still to fill, rather than sitting grey.384 className={`tablet:h-9 tablet:w-fit h-11 w-full min-w-28 px-4 ${state === "ready" || state === "busy" ? "" : "text-muted-foreground border-dashed disabled:opacity-100"}`}385 data-state={state}386 disabled={state !== "ready"}387 type="submit"388 variant={389 state === "ready" || state === "busy" ? "default" : "outline"390 }391 >392 {busy ? <Spinner /> : null}393 {IMPORT_WORDS[state]}394 </Button>395 <output aria-live="polite" className={HINT}>396 {busy397 ? "The platform is cloning the repo; an import takes up to half a minute. Stay on this page."398 : null}399 </output>400 </div>401 </form>402 );403};404405/** The form, the way to sign in, or the wait while the browser learns who is signed in. */406export const ImportForm = ({407 busy,408 checking = false,409 fixedOwner,410 handle,411 here,412 onImport,413 prefill,414 refusal,415}: ImportFormProps): ReactNode => {416 if (checking) {417 return (418 <output className="text-ui text-muted-foreground block">419 Checking who is signed in420 </output>421 );422 }423424 return Option.isSome(handle) ? (425 <Form426 busy={busy}427 fixedOwner={fixedOwner}428 handle={handle}429 onImport={onImport}430 prefill={prefill}431 refusal={refusal}432 />433 ) : (434 <SignInToImport fixedOwner={fixedOwner} here={here} prefill={prefill} />435 );436};
added:apps/web/src/features/import/import-offer.tsx+62 added
added:apps/web/src/features/import/import-page.tsx+66 added
added:apps/web/src/features/import/owner-select.tsx+56 added
added:apps/web/src/features/import/prefill.ts+111 added
1/**2 * What the import form reads from a pasted URL, and what it sends. Pure:3 * no view, no transport. The owner is the URL's source namespace4 * (`github.com/pallets`) when its host is one the platform knows; the name5 * is the URL's last segment, without `.git`, lowercased. Nothing here asks6 * a host anything: the platform clones the URL when Import is pressed.7 */8import type { InitProject } from "@repo/protocol/contracts";9import { ImportSource } from "@repo/protocol/domain/policy";10import {11 Owner,12 projectNameOf,13 ShortName,14 sourceNamespaceOf,15} from "@repo/protocol/ids";16import type { Handle, ProjectName, SourceNamespace } from "@repo/protocol/ids";17import { Array, Option, Schema } from "effect";1819/** What `initProject` takes, from its one schema. */20export type ImportPayload = typeof InitProject.payloadSchema.Type;2122/** What a URL prefills: the owner its host gives, and the name it ends in. */23export interface Prefill {24 readonly owner: Option.Option<SourceNamespace>;25 readonly name: Option.Option<ShortName>;26}2728// `https://<host>/<path>`: the path's last non-empty segment is the repo's.29const HTTPS_URL = /^https:\/\/[^/?#\s]+\/(?<path>[^?#\s]+)$/u;3031const decodeShortName = Schema.decodeUnknownOption(ShortName);3233const decodeOwner = Schema.decodeUnknownOption(Owner);3435const decodeSource = Schema.decodeUnknownOption(ImportSource);3637/** The name a URL ends in, without `.git` and lowercased; none when it is no name. */38const nameIn = (url: string): Option.Option<ShortName> => {39 const path = HTTPS_URL.exec(url.trim())?.groups?.path ?? "";40 const last = path.split("/").findLast((segment) => segment !== "") ?? "";4142 return decodeShortName(last.replace(/\.git$/u, "").toLowerCase());43};4445/** The owner and the name `url` prefills. */46export const prefillFrom = (url: string): Prefill => ({47 name: nameIn(url),48 owner: sourceNamespaceOf(url.trim()),49});5051/** A source namespace as an owner: every one is (a host is never a reserved word). */52export const ownerOfNamespace = (53 namespace: SourceNamespace54): Option.Option<Owner> => decodeOwner(namespace);5556/** A handle as an owner, lowercased; none for one no owner can spell. */57export const ownerOfHandle = (handle: Handle): Option.Option<Owner> =>58 decodeOwner(handle.toLowerCase());5960/**61 * The owners a person may import `url` under: the URL's source namespace62 * first when its host is one the platform knows (the default then), and63 * their own handle.64 */65export const ownerChoices = (66 handle: Option.Option<Handle>,67 url: string68): readonly Owner[] =>69 Array.dedupe([70 ...Option.toArray(Option.flatMap(prefillFrom(url).owner, ownerOfNamespace)),71 ...Option.toArray(Option.flatMap(handle, ownerOfHandle)),72 ]);7374/**75 * The URL a source namespace's project was imported from:76 * `github.com/pallets/click` is `https://github.com/pallets/click`.77 */78export const sourceUrlOf = (project: ProjectName) => `https://${project}`;7980/**81 * The source the form names, as `initProject` takes it: the URL and the82 * branch trimmed, the branch only when named. None for a URL the contract83 * would refuse (no public HTTPS URL).84 */85export const importSourceOf = (form: {86 readonly url: string;87 readonly branch: string;88}): Option.Option<ImportSource> => {89 const branch = form.branch.trim();90 const url = form.url.trim();9192 return decodeSource(branch === "" ? { url } : { branch, url });93};9495/**96 * The form's fields as `initProject`'s payload: its source, and the97 * project the owner and the name make. None when the contract would refuse98 * the name or the URL before the platform ever read it.99 */100export const importPayload = (form: {101 readonly url: string;102 readonly branch: string;103 readonly owner: Owner;104 readonly name: string;105}): Option.Option<ImportPayload> =>106 Option.flatMap(importSourceOf(form), (source) =>107 Option.map(decodeShortName(form.name.trim()), (short) => ({108 import: source,109 project: projectNameOf(form.owner, short),110 }))111 );
added:apps/web/src/features/import/use-importer.tsx+81 added
1/**2 * The import form's wiring, for the two pages that draw it (`/import` and3 * a source namespace's address nobody has made): who is signed in, read in4 * the browser; `importAtom`, sent only when Import is pressed; the move to5 * the project once it is made; and a refusal, drawn as the platform gave6 * it, under the form.7 */8import { useAtom, useAtomValue } from "@effect/atom-react";9import { ownerOf } from "@repo/protocol/ids";10import type { ProjectName } from "@repo/protocol/ids";11import { useLocation, useNavigate, useRouter } from "@tanstack/react-router";12import { Option } from "effect";13import { AsyncResult } from "effect/reactivity";14import { useEffect, useState } from "react";1516import { importAtom, importMade } from "../../client/import.ts";17import { hereOf } from "../auth/session-slot.tsx";18import { whoAtom } from "../auth/who.ts";19import { ProposalFailure } from "../proposal/failure.tsx";20import type { Importer } from "./import-form.tsx";2122/**23 * Where an import that made `made` goes from a page at `at`: nowhere when24 * it is the project this address names (its page reads it again), else to25 * the project's page.26 */27export const afterImport = (made: ProjectName, at?: ProjectName) =>28 made === at29 ? Option.none()30 : Option.some({31 params: { owner: ownerOf(made), project: made },32 to: "/$owner/$project" as const,33 });3435/**36 * Who is importing and what became of the last press. `at` is the project37 * this page's address names, if any: a project made there is read again38 * where it stands; any other is gone to.39 */40export const useImporter = (at?: ProjectName): Importer => {41 const navigate = useNavigate();42 const router = useRouter();43 const here = useLocation({ select: hereOf });44 const who = useAtomValue(whoAtom);45 const [imported, send] = useAtom(importAtom);46 // Set once this page sends: a project the atom still holds from an47 // earlier visit never moves the page.48 const [sent, setSent] = useState(false);49 const made = sent ? Option.getOrUndefined(importMade(imported)) : undefined;5051 useEffect(() => {52 if (made === undefined) {53 return;54 }5556 Option.match(afterImport(made, at), {57 // The loader read this address as no project: it reads it again.58 onNone: () => {59 void router.invalidate();60 },61 onSome: (to) => {62 void navigate(to);63 },64 });65 }, [at, made, navigate, router]);6667 return {68 busy: imported.waiting,69 checking: !AsyncResult.isSuccess(who),70 handle: AsyncResult.isSuccess(who) ? who.value : Option.none(),71 onImport: (payload) => {72 setSent(true);73 send(payload);74 },75 refusal: AsyncResult.isFailure(imported) ? (76 <div aria-live="polite">77 <ProposalFailure cause={imported.cause} doing="import it" here={here} />78 </div>79 ) : undefined,80 };81};
modified:apps/web/src/features/landing/landing-page.tsx+5 added-1 removed
16 unmodified lines
17import { SkipLink } from "../shared/layout.tsx";18import { AppLink } from "../shared/link.tsx";19import {20 ASKS_PATH,21 IMPORT_PATH,22 docsPath,23 HOME_PATH,24 projectPath,25} from "../shared/paths.ts";
346 unmodified lines
372 Code, asks, credit and the ledger of what a project holds back are373 public to everyone.374 </p>375 <Projects projects={projects} />375 <p className="text-ui">376 <p className="text-ui flex flex-wrap gap-x-4 gap-y-1">377 <AppLink className={LINK} to={ASKS_PATH}>378 All asks379 </AppLink>380 <AppLink className={LINK} to={IMPORT_PATH}>381 Import a repo382 </AppLink>383 </p>384 </Part>385 </main>386 <footer className="border-rule text-ui flex flex-wrap gap-x-5 gap-y-2 border-t py-6">
15 unmodified lines
modified:apps/web/src/features/shared/shell/overlays.tsx+12 added-2 removed
6 unmodified lines
7 * overlay belongs to the address it opened on).8 */9import { Brand } from "@repo/brand";10import { useRouter } from "@tanstack/react-router";11import { BookOpen, Bot, Keyboard } from "lucide-react";11import { BookOpen, Bot, FolderInput, Keyboard } from "lucide-react";12import { useRef } from "react";13import type { RefObject } from "react";1415import {
13 unmodified lines
29import { Sheet, SheetContent } from "../../../components/ui/sheet.tsx";30import { SessionSlot } from "../../auth/session-slot.tsx";31import { KeysHelp, useKeys } from "../keys.tsx";32import { AppLink } from "../link.tsx";33import { docsPath } from "../paths.ts";33import { docsPath, IMPORT_PATH } from "../paths.ts";34import { useCurrentProject, useProjectList, useShell } from "./context.ts";35import type { Overlay } from "./context.ts";36import {37 PostureMark,
225 unmodified lines
263 side={overlay === "projects" && atLeastTablet() ? "left" : "full"}264 title="Projects"265 >266 <ProjectSwitcher input={filter} onChosen={onClose} />267 <div className="border-rule border-t p-1">268 <AppLink className={RAIL_ROW} to={IMPORT_PATH}>269 <FolderInput270 aria-hidden="true"271 className="text-muted-foreground size-4 shrink-0"272 strokeWidth={1.75}273 />274 Import a repo275 </AppLink>276 </div>277 </SheetContent>278 </Sheet>279 <KeysDialog onClose={onClose} open={overlay === "keys"} />280 </>
4 unmodified lines
modified:apps/web/src/features/shared/paths.ts+3 added
14 unmodified lines
1516/** A signed-in reader's own page. */17export const HOME_PATH = "/home";1819/** The import page: a public repo made a project. */20export const IMPORT_PATH = "/import";2122/** The docs' index, or one of its pages. */23export const docsPath = (page?: string) =>24 page === undefined ? "/docs" : `/docs/${page}`;25
37 unmodified lines
modified:apps/web/src/routes/$owner/$project/index.tsx+20 added-1 removed
31 unmodified lines
32 markdownLink,33} from "../../../features/front/markdown.ts";34import { useStamps } from "../../../features/front/stamps.ts";35import {36 ImportOffer,37 offerFor,38} from "../../../features/import/import-offer.tsx";39import { useImporter } from "../../../features/import/use-importer.tsx";40import {41 ProjectView,42 heldBackOf,43 homeListing,44} from "../../../features/project/project-page.tsx";
248 unmodified lines
293 </SeededAtoms>294 );295};296297/** The import offer for `project`, wired. */298const Offer = ({ project }: { readonly project: ProjectName }) => {299 const importer = useImporter(project);300301 return <ImportOffer importer={importer} project={project} />;302};303304/**305 * No project at this address: at a source namespace's306 * (`/github.com/pallets/click`) the import offer, else the not-found.307 */308const Unknown = () => {309 const { project } = Route.useParams();310295 return <UnknownProjectView name={project} />;311 return Option.match(offerFor(project), {312 onNone: () => <UnknownProjectView name={project} />,313 onSome: (offered) => <Offer project={offered} />,314 });315};316317export const Route = createFileRoute("/$owner/$project/")({318 // TanStack infers each option from the ones before it.
19 unmodified lines
added:apps/web/src/routes/import.tsx+39 added
1import { createFileRoute, useLocation } from "@tanstack/react-router";2import { Predicate } from "effect";34import { hereOf } from "../features/auth/session-slot.tsx";5import { ImportView } from "../features/import/import-page.tsx";6import { useImporter } from "../features/import/use-importer.tsx";7import { pageHead } from "../features/shared/head.ts";8import { personalPage } from "../server/cache-headers.ts";910// `/import`: import a public repo as a project. Who is signed in is read11// in the browser (the server paints the page while it checks); an import12// made goes to the project's page, a refusal shows under the form.13// `?url=<https URL>` fills the form; nothing is imported until Import is14// pressed. A page about its reader, kept by no cache.1516/** A page about its reader, kept by no cache. */17export const importHeaders = () => personalPage;1819const ImportPage = () => {20 const { url } = Route.useSearch();21 const here = useLocation({ select: hereOf });22 const importer = useImporter();2324 return <ImportView {...importer} here={here} url={url} />;25};2627/** The address's search: the URL to fill the form with, when it is text. */28export const importSearch = ({29 url,30}: {31 readonly url?: unknown;32}): { readonly url?: string } => (Predicate.isString(url) ? { url } : {});3334export const Route = createFileRoute("/import")({35 validateSearch: importSearch,36 headers: importHeaders,37 head: () => pageHead({ title: "Import a repo" }),38 component: ImportPage,39});
modified:apps/web/src/server/addresses.ts+13 added-4 removed
9 unmodified lines
10 * - `projectParams` gives the project's pages its full name as `project`11 * (`oscabriel/datekit`), the name every read takes, and splits it again12 * when the router prints a link.13 * - `canonicalAddress` answers, before any page, a key a project kept from14 * before owners (`/datekit/…`) and a name spelled in another case15 * (`/OscaBriel/datekit/…`) with a 301 to the name's address, the rest of14 * before owners (`/datekit/…`), a name spelled in another case15 * (`/OscaBriel/datekit/…`) and one ending in `.git` with a 301 to the name's address, the rest of16 * the path and the query kept.17 */18import {19 ProjectName,
102 unmodified lines
122 status: 301,123 });124125/**126 * A name as spelled without a trailing `.git` on its last segment: an127 * address copied from a clone URL (`/github.com/pallets/click.git`) names128 * the project.129 */130const withoutGit = (spelled: string) => spelled.replace(/\.git$/iu, "");131132/**133 * The 301 a request needs to reach its project's address, if any: a key a134 * project kept from before owners (`/datekit/tree/main?x=1` to135 * `/oscabriel/datekit/tree/main?x=1`) and a name in another case129 * (`/OscaBriel/datekit` to `/oscabriel/datekit`). None for the web's own136 * (`/OscaBriel/datekit` to `/oscabriel/datekit`), and a name with a137 * trailing `.git` (`/github.com/pallets/click.git` to138 * `/github.com/pallets/click`). None for the web's own139 * pages and files, for an address already canonical, and for a name no140 * project could have, which its page says is unknown.141 */142export const canonicalAddress = (request: Request): Option.Option<Response> => {
9 unmodified lines
152 return Option.none();153 }154155 return Option.flatMap(projectAddressOf(segments), (address) =>147 Option.flatMap(decodeName(address.spelled), (name) =>156 Option.flatMap(decodeName(withoutGit(address.spelled)), (name) =>157 name === address.spelled158 ? Option.none()159 : Option.some(160 movedTo(
28 unmodified lines
added:apps/web/test/import.test.tsx+494 added
1/**2 * The import page, `/import`, rendered to HTML with `react-dom/server`: a3 * signed-in person pastes a public repo's HTTPS URL, may name a branch,4 * picks the owner (their handle, or the URL's source namespace when its5 * host is one the platform knows, which is the default then) and the name,6 * prefilled from the URL, and imports it through `initProject`. Signed out,7 * the page links to sign-in, coming back to it. A refusal reads as the8 * platform gave it. The page is about its reader, so no cache keeps it.9 */10import { RegistryContext } from "@effect/atom-react";11import { describe, expect, it } from "@effect/vitest";12import { Brand } from "@repo/brand";13import { Contracts, InitProject } from "@repo/protocol/contracts";14import { Handle, Owner, ProjectName } from "@repo/protocol/ids";15import {16 ImportFailed,17 NotYourNamespace,18 ProjectExists,19} from "@repo/protocol/refusal";20import { asPerson, unanswered } from "@repo/protocol/testing";21import { Cause, Effect, Exit, Layer, Option, Schema } from "effect";22import { Atom, AsyncResult, AtomRegistry, Reactivity } from "effect/reactivity";23import { RpcTest } from "effect/rpc";2425import { importAtom, importMade } from "../src/client/import.ts";26import type { Importer } from "../src/features/import/import-form.tsx";27import { ImportView } from "../src/features/import/import-page.tsx";28import {29 importPayload,30 ownerChoices,31 prefillFrom,32 sourceUrlOf,33} from "../src/features/import/prefill.ts";34import type { ImportPayload } from "../src/features/import/prefill.ts";35import {36 afterImport,37 useImporter,38} from "../src/features/import/use-importer.tsx";39import { ProposalFailure } from "../src/features/proposal/failure.tsx";40import { importHeaders, importSearch, Route } from "../src/routes/import.tsx";41import { ContractsClient, webContracts } from "../src/surfaces.ts";42import { markupOf, textIn } from "./markup.ts";43import { renderAt, routerAt } from "./render.tsx";4445const CLICK = "https://github.com/pallets/click";4647const oscabriel = Option.some(Handle.make("oscabriel"));4849const signedIn = (url = CLICK) =>50 markupOf(<ImportView handle={oscabriel} here="/import" url={url} />);5152/** An input's opening tag, by its `name`. */53const inputNamed = (markup: string, name: string) =>54 new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";5556/** Where a sign-in link in `markup` comes back to. */57const returnOf = (markup: string) => {58 const href = /href="(?<href>\/auth\/signin[^"]*)"/u59 .exec(markup)60 ?.groups?.href?.replaceAll("&amp;", "&");6162 return new URL(href ?? "/", "https://web.test").searchParams.get("return");63};6465describe("the import page", () => {66 it("is kept by no cache: its response is private and never stored", () => {67 expect(Route.options.headers).toBe(importHeaders);68 expect(importHeaders()).toStrictEqual({69 "Cache-Control": "private, no-store",70 });71 });7273 it("takes the URL to prefill from its address, and nothing else", () => {74 expect(Route.options.validateSearch).toBe(importSearch);75 expect(importSearch({ url: CLICK })).toStrictEqual({ url: CLICK });76 expect(importSearch({ url: 3 })).toStrictEqual({});77 });7879 it("signed out, shows no form and a sign-in link that comes back to /import", () => {80 const markup = markupOf(81 <ImportView handle={Option.none()} here="/import" />82 );8384 expect(markup).not.toContain("<form");85 expect(returnOf(markup)).toBe("/import");86 expect(textIn(markup)).toContain(`${Brand.cli} init --project`);87 });8889 it("says so while it learns who is signed in", () => {90 const markup = markupOf(91 <ImportView checking handle={Option.none()} here="/import" />92 );9394 expect(markup).not.toContain("<form");95 expect(textIn(markup)).toContain("Checking who is signed in");96 });9798 it("signed in, offers the URL, the branch, the owner and the name, prefilled from the URL", () => {99 const markup = signedIn();100101 expect(inputNamed(markup, "url")).toContain(`value="${CLICK}"`);102 expect(inputNamed(markup, "branch")).toContain('value=""');103 expect(inputNamed(markup, "owner")).toContain('value="github.com/pallets"');104 expect(inputNamed(markup, "name")).toContain('value="click"');105 expect(markup).toMatch(/<button[^>]*type="submit"[^>]*>Import<\/button>/u);106 });107108 it("waits on Import until the URL is one to import, and says so", () => {109 const markup = signedIn("");110111 expect(markup).toMatch(112 /<button(?=[^>]*disabled="")(?=[^>]*type="submit")[^>]*>Paste a repo&#x27;s URL first<\/button>/u113 );114 });115116 it("says what it is doing while the import runs", () => {117 const markup = markupOf(118 <ImportView busy handle={oscabriel} here="/import" url={CLICK} />119 );120121 expect(textIn(markup)).toContain("Importing…");122 expect(markup).toMatch(123 /<button(?=[^>]*disabled="")(?=[^>]*type="submit")/u124 );125 });126});127128describe(prefillFrom, () => {129 it("reads the source namespace and the name from a known host's URL", () => {130 expect(prefillFrom(CLICK)).toStrictEqual({131 name: Option.some("click"),132 owner: Option.some("github.com/pallets"),133 });134 });135136 it("strips .git, lowercases, and keeps a dot inside the name", () => {137 expect(prefillFrom("https://github.com/TJ/Commander.js.git")).toStrictEqual(138 { name: Option.some("commander.js"), owner: Option.some("github.com/tj") }139 );140 });141142 it("names no owner for a host the platform does not know, and still the name", () => {143 expect(prefillFrom("https://git.sr.ht/~sircmpwn/hare/")).toStrictEqual({144 name: Option.some("hare"),145 owner: Option.none(),146 });147 });148149 it("prefills nothing from what is not an HTTPS URL", () => {150 expect(prefillFrom("git@github.com:pallets/click.git")).toStrictEqual({151 name: Option.none(),152 owner: Option.none(),153 });154 expect(prefillFrom("")).toStrictEqual({155 name: Option.none(),156 owner: Option.none(),157 });158 });159});160161describe(ownerChoices, () => {162 it("puts the source namespace first when the host is on the list, then the handle", () => {163 expect(ownerChoices(oscabriel, CLICK)).toStrictEqual([164 "github.com/pallets",165 "oscabriel",166 ]);167 });168169 it("offers the handle alone when the host is not on the list", () => {170 expect(171 ownerChoices(oscabriel, "https://git.sr.ht/~sircmpwn/hare")172 ).toStrictEqual(["oscabriel"]);173 });174175 it("offers a handle in lowercase, as an owner is spelled", () => {176 expect(177 ownerChoices(Option.some(Handle.make("OscaBriel")), "")178 ).toStrictEqual(["oscabriel"]);179 });180});181182describe(importPayload, () => {183 const isPayload = Schema.is(InitProject.payloadSchema);184185 it("is initProject's payload: the project and the import, the branch when named", () => {186 const payload = importPayload({187 branch: " stable ",188 name: "click",189 owner: Owner.make("github.com/pallets"),190 url: ` ${CLICK} `,191 });192193 expect(payload).toStrictEqual(194 Option.some({195 import: { branch: "stable", url: CLICK },196 project: "github.com/pallets/click",197 })198 );199 expect(Option.exists(payload, isPayload)).toBeTruthy();200 });201202 it("carries no branch when none is named", () => {203 expect(204 importPayload({205 branch: "",206 name: "click",207 owner: Owner.make("oscabriel"),208 url: CLICK,209 })210 ).toStrictEqual(211 Option.some({ import: { url: CLICK }, project: "oscabriel/click" })212 );213 });214215 it("is none for a name or a URL the contract would not take", () => {216 expect(217 importPayload({218 branch: "",219 name: "Bad Name",220 owner: Owner.make("oscabriel"),221 url: CLICK,222 })223 ).toStrictEqual(Option.none());224 expect(225 importPayload({226 branch: "",227 name: "click",228 owner: Owner.make("oscabriel"),229 url: "http://github.com/pallets/click",230 })231 ).toStrictEqual(Option.none());232 });233});234235describe(sourceUrlOf, () => {236 it("rebuilds the URL a source namespace's project was imported from", () => {237 expect(sourceUrlOf(ProjectName.make("github.com/pallets/click"))).toBe(238 CLICK239 );240 });241});242243/** `initProject`'s answer: the project made. */244const made = (project: string) =>245 Schema.decodeSync(InitProject.successSchema)({246 project,247 remote: `https://platform.test/${project}.git`,248 });249250describe(importMade, () => {251 it("names the project an import made, once it answered", () => {252 expect(253 importMade(AsyncResult.success(made("github.com/pallets/click")))254 ).toStrictEqual(Option.some("github.com/pallets/click"));255 });256257 it("names none while an import runs, or after it was refused", () => {258 const earlier = AsyncResult.success(made("oscabriel/click"));259260 expect(importMade(AsyncResult.waiting(earlier))).toStrictEqual(261 Option.none()262 );263 expect(264 importMade(265 AsyncResult.fail(266 new ImportFailed({ next: "x", reason: "unreachable" }),267 { previousSuccess: Option.some(earlier) }268 )269 )270 ).toStrictEqual(Option.none());271 });272});273274describe("a refused import", () => {275 const click = ProjectName.make("github.com/pallets/click");276277 it.each([278 [279 "ImportFailed",280 new ImportFailed({281 next: `${Brand.cli} init`,282 reason: "the repo could not be read",283 }),284 ],285 [286 "ProjectExists",287 new ProjectExists({ next: `${Brand.cli} asks`, project: click }),288 ],289 [290 "NotYourNamespace",291 NotYourNamespace.of(292 ProjectName.make("github.com/someone/click"),293 Handle.make("oscabriel")294 ),295 ],296 ])("reads as the platform's %s, under the form", (tag, refusal) => {297 const markup = markupOf(298 <ImportView299 handle={oscabriel}300 here="/import"301 refusal={302 <ProposalFailure303 cause={Cause.fail(refusal)}304 doing="import it"305 here="/import"306 />307 }308 url={CLICK}309 />310 );311312 expect(markup).toContain(`data-refusal="${tag}"`);313 expect(markup).toContain("<form");314 });315});316317/**318 * The page as its route draws it, the hook's importer over `registry`,319 * handing each render's importer to `seen`, as the press would reach it.320 * A server's render always reads who is signed in as not yet known (the321 * page's first paint, `whoAtom`), so this one says, as the browser would322 * once it knows, that oscabriel is.323 */324const Page = ({325 seen,326}: {327 readonly seen?: ((importer: Importer) => void) | undefined;328}) => {329 const importer = useImporter();330331 seen?.(importer);332333 return (334 <ImportView335 {...importer}336 checking={false}337 handle={oscabriel}338 here="/import"339 url={CLICK}340 />341 );342};343344const PageOver = ({345 registry,346 seen,347}: {348 readonly registry: AtomRegistry.AtomRegistry;349 readonly seen?: (importer: Importer) => void;350}) => (351 <RegistryContext.Provider value={registry}>352 <Page seen={seen} />353 </RegistryContext.Provider>354);355356/**357 * A browser signed in as oscabriel, over a platform whose `initProject`358 * answers with `answer`, every payload it is sent kept in `sent`.359 */360const browserWith = (361 sent: ImportPayload[],362 answer: (363 payload: ImportPayload364 ) => Effect.Effect<365 typeof InitProject.successSchema.Type,366 typeof InitProject.errorSchema.Type367 >368) =>369 AtomRegistry.make({370 initialValues: [371 Atom.initialValue(372 ContractsClient.runtime.layer,373 Layer.effect(374 ContractsClient,375 RpcTest.makeClient(webContracts, { flatten: true })376 ).pipe(377 Layer.provide([378 Layer.mergeAll(379 unanswered,380 Contracts.toLayerHandler("initProject", (payload) => {381 sent.push(payload);382383 return answer(payload);384 })385 ),386 asPerson(Handle.make("oscabriel")),387 ]),388 Layer.provideMerge(Reactivity.layer)389 )390 ),391 ],392 });393394/** The form's fields as the page drew them: what pressing Import sends. */395const fieldsIn = (markup: string) => {396 const value = (name: string) =>397 /value="(?<value>[^"]*)"/u398 .exec(inputNamed(markup, name))399 ?.groups?.value?.replaceAll("&amp;", "&") ?? "";400401 return {402 branch: value("branch"),403 name: value("name"),404 owner: Owner.make(value("owner")),405 url: value("url"),406 };407};408409/** Presses Import on the page drawn over `registry`, and waits for the answer. */410const pressImport = (registry: AtomRegistry.AtomRegistry) =>411 Effect.gen(function* () {412 const importers: Importer[] = [];413414 const markup = yield* renderAt(415 `/import?url=${encodeURIComponent(CLICK)}`,416 <PageOver417 registry={registry}418 seen={(importer) => {419 importers.push(importer);420 }}421 />422 );423424 const payload = yield* Effect.fromOption(importPayload(fieldsIn(markup)));425426 // A page in the browser keeps the atom mounted while it waits; a427 // server's render keeps nothing.428 registry.mount(importAtom);429 importers.at(-1)?.onImport?.(payload);430431 return yield* Effect.exit(432 AtomRegistry.getResult(registry, importAtom, { suspendOnWaiting: true })433 );434 });435436describe("pressing Import", () => {437 it.live(438 "sends initProject the project and the import, then goes to the project's address",439 () =>440 Effect.gen(function* () {441 const sent: ImportPayload[] = [];442443 const registry = browserWith(sent, ({ project }) =>444 Effect.succeed(made(project))445 );446447 const answered = yield* pressImport(registry);448449 const to = yield* Effect.fromOption(450 Exit.match(answered, {451 onFailure: () => Option.none(),452 onSuccess: ({ project }) => afterImport(project),453 })454 );455456 const router = routerAt("/import");457458 yield* Effect.tryPromise(() => router.load());459460 expect(sent).toStrictEqual([461 { import: { url: CLICK }, project: "github.com/pallets/click" },462 ]);463 // Where the hook's `navigate` goes: a router with no window to464 // move only builds the location, as `navigate` does first.465 expect(router.buildLocation(to).publicHref).toBe(466 "/github.com/pallets/click"467 );468 })469 );470471 it.live("draws a refusal as the platform gave it, under the form", () =>472 Effect.gen(function* () {473 const registry = browserWith([], ({ project }) =>474 Effect.fail(NotYourNamespace.of(project, Handle.make("oscabriel")))475 );476477 yield* pressImport(registry);478479 const markup = yield* renderAt(480 "/import",481 <PageOver registry={registry} />482 );483484 expect(markup).toContain('data-refusal="NotYourNamespace"');485 expect(markup).toContain("<form");486 })487 );488489 it("stays where it is when the import made the project this address names", () => {490 const click = ProjectName.make("github.com/pallets/click");491492 expect(afterImport(click, click)).toStrictEqual(Option.none());493 });494});
modified:apps/web/test/legacy-redirect.test.ts+29 added
46 unmodified lines
47 Option.some([301, "/github.com/pallets/click/tree/main"])48 );49 });5051 it("is a 301 from a name with a trailing .git to the name, the rest and the query kept", () => {52 expect(movedTo("/github.com/pallets/click.git")).toStrictEqual(53 Option.some([301, "/github.com/pallets/click"])54 );55 expect(movedTo("/oscabriel/datekit.git")).toStrictEqual(56 Option.some([301, "/oscabriel/datekit"])57 );58 expect(59 movedTo("/github.com/pallets/click.git/tree/main?x=1")60 ).toStrictEqual(61 Option.some([301, "/github.com/pallets/click/tree/main?x=1"])62 );63 expect(movedTo("/GitHub.com/Pallets/Click.GIT")).toStrictEqual(64 Option.some([301, "/github.com/pallets/click"])65 );66 });6768 it("answers only a read with the .git 301", () => {69 expect(70 canonicalAddress(request("/github.com/pallets/click.git", "POST"))71 ).toStrictEqual(Option.none());72 expect(73 Option.map(74 canonicalAddress(request("/oscabriel/datekit.git", "HEAD")),75 (response) => response.status76 )77 ).toStrictEqual(Option.some(301));78 });7980 it("is kept by the edge, as a page that reads as nobody", () => {81 const answered = Option.getOrThrow(82 canonicalAddress(request("/datekit/tree/main?x=1"))83 );
44 unmodified lines
modified:apps/web/test/production-bundle.test.ts+6 added-4 removed
411 unmodified lines
412 })413 );414415 it.effect(416 "preloads on every page no grammar, nothing of the server's highlighting, and not the landing's view",416 "preloads on every page no grammar, nothing of the server's highlighting, and neither the landing's view nor the import page's",417 () =>418 Effect.gen(function* () {419 const output = yield* Built;420421 // Nor the landing's view: a route's head or loader that imported422 // it would carry the whole page into every page's preloads.421 // Nor the landing's view, nor the import page's: a route's head or422 // loader that imported one would carry the whole page into every423 // page's preloads.424 expect(425 rootPreloads(output).flatMap((chunk) =>426 (output.holding.get(`client${chunk}`) ?? []).filter(427 (module) =>428 GRAMMAR.test(module) ||429 module.includes("prerender") ||429 module.endsWith("features/landing/landing-page.tsx")430 module.endsWith("features/landing/landing-page.tsx") ||431 module.includes("features/import/")432 )433 )434 ).toStrictEqual([]);435
60 unmodified lines
modified:apps/web/test/project.test.tsx+92 added-1 removed
28 unmodified lines
29} from "@repo/protocol/ids";30import { UnknownRevision } from "@repo/protocol/refusal";31import { asTester, unanswered } from "@repo/protocol/testing";32import { isNotFound } from "@tanstack/react-router";33import { DateTime, Duration, Effect, Layer, Ref, Schema, Stream } from "effect";33import {34 DateTime,35 Duration,36 Effect,37 Layer,38 Option,39 Ref,40 Schema,41 Stream,42} from "effect";43import { FetchHttpClient } from "effect/http";44import { RpcClient, RpcSerialization, RpcTest } from "effect/rpc";4546import { recentLandings } from "../src/client/events.ts";47import type { DevWorldOptions } from "../src/dev/server.ts";48import { devServer } from "../src/dev/server.ts";49import { ledeOf } from "../src/features/front/head.ts";50import { stampStep } from "../src/features/front/stamps.ts";51import { ImportOffer, offerFor } from "../src/features/import/import-offer.tsx";52import { recentShown } from "../src/features/project/landings.tsx";53import { postureWord } from "../src/features/project/posture-label.ts";54import {55 ProjectView,
623 unmodified lines
679);680681const decodePage = Schema.decodeEffect(ProjectPageData);682683/** An input's opening tag, by its `name`. */684const inputNamed = (markup: string, name: string) =>685 new RegExp(`<input[^>]*name="${name}"[^>]*>`, "u").exec(markup)?.[0] ?? "";686687/** A fresh dev world seeds itself first, which a full test run can slow past 5 s. */688const seededWorld = { timeout: 30_000 };689690/** The page as the route draws it from what its loader read. */
244 unmodified lines
935 expect(markup).toMatch(/<a\b[^>]*href="\/asks"[^>]*>Open asks<\/a>/u);936 })937 );938939 it.effect(940 "keeps the one-sentence not-found, and no offer, for a person's address",941 () =>942 Effect.gen(function* () {943 const markup = yield* renderAt(944 "/oscabriel/no-such",945 <UnknownProjectView name="oscabriel/no-such" />946 );947948 expect(markup).toContain('data-refusal="UnknownProject"');949 expect(markup).not.toContain("<form");950 expect(offerFor("oscabriel/no-such")).toStrictEqual(Option.none());951 })952 );953954 it("says in a sentence that an address naming no possible project names none", () => {955 const markup = markupOf(<UnknownProjectView name="Not_A_Project" />);956957 expect(markup).not.toContain("data-refusal");
2 unmodified lines
960 );961 });962});963964describe(ImportOffer, () => {965 const click = ProjectName.make("github.com/pallets/click");966967 const offered = (handle: Option.Option<Handle>) =>968 renderAt(969 "/github.com/pallets/click",970 <ImportOffer importer={{ handle }} project={click} />971 );972973 it("is what a source namespace's address offers, and no other", () => {974 expect(offerFor("github.com/pallets/click")).toStrictEqual(975 Option.some(click)976 );977 expect(offerFor("oscabriel/no-such")).toStrictEqual(Option.none());978 expect(offerFor("Not_A_Project")).toStrictEqual(Option.none());979 });980981 it.effect(982 "draws the form prefilled from the address, the owner fixed and no refusal",983 () =>984 Effect.gen(function* () {985 const markup = yield* offered(Option.some(Handle.make("oscabriel")));986987 expect(inputNamed(markup, "url")).toContain(988 'value="https://github.com/pallets/click"'989 );990 expect(inputNamed(markup, "owner")).toMatch(991 /type="hidden"[^>]*value="github\.com\/pallets"|value="github\.com\/pallets"[^>]*type="hidden"/u992 );993 expect(inputNamed(markup, "name")).toContain('value="click"');994 expect(markup).not.toContain('data-slot="select-trigger"');995 expect(markup).not.toContain("data-refusal");996 })997 );998999 it.effect(1000 "keeps the URL the address rebuilds read-only, and the branch and the name editable",1001 () =>1002 Effect.gen(function* () {1003 const markup = yield* offered(Option.some(Handle.make("oscabriel")));10041005 expect(inputNamed(markup, "url")).toContain('readOnly=""');1006 expect(inputNamed(markup, "branch")).not.toContain("readOnly");1007 expect(inputNamed(markup, "name")).not.toContain("readOnly");1008 })1009 );10101011 it.effect(1012 "signed out, says what would be imported, with the sign-in link back to the address",1013 () =>1014 Effect.gen(function* () {1015 const markup = yield* offered(Option.none());10161017 expect(markup).not.toContain("<form");1018 expect(markup).toContain(1019 `href="/auth/signin?return=${encodeURIComponent("/github.com/pallets/click")}"`1020 );1021 expect(textIn(markup)).toContain("https://github.com/pallets/click");1022 })1023 );1024});10251026describe("the project's views", () => {1027 const sources: Readonly<Record<string, string>> = import.meta.glob(1028 "../src/features/project/**/*.{ts,tsx}",1029 { eager: true, import: "default", query: "?raw" }
7 unmodified lines
modified:apps/web/test/render.tsx+18 added-6 removed
2 unmodified lines
3 * draws the router's links (`AppLink`), reads the location or the route's4 * params needs around it, as the app's router gives it in the browser.5 *6 * The routes are the app's shape without its loaders: `/` (the landing,7 * outside the shell), `/asks`, `/home`, `/today`, `/docs`, `/docs/$page`,7 * outside the shell), `/asks`, `/home`, `/import`, `/today`, `/docs`, `/docs/$page`,8 * `/agents`, `/people/$handle` and `/$owner/$project` with its pages under9 * it, read through the app's own rewrite and params, so the shell finds the10 * project in `/oscabriel/datekit/ledger` and11 * `/github.com/pallets/click/tree/main`, and none in `/agents`.
43 unmodified lines
55 staticData: { shell: "bare" },56 }),57 createRoute({ getParentRoute: () => root, path: "asks" }),58 createRoute({ getParentRoute: () => root, path: "home" }),59 createRoute({ getParentRoute: () => root, path: "import" }),60 createRoute({ getParentRoute: () => root, path: "today" }),61 createRoute({ getParentRoute: () => root, path: "docs" }),62 createRoute({ getParentRoute: () => root, path: "docs/$page" }),63 createRoute({ getParentRoute: () => root, path: "agents" }),
10 unmodified lines
74 ]),75 ]);76};7777/** `view`'s static markup inside a router whose location is `url`. */78export const renderAt = (78/**79 * The app's router at `url`, in memory, drawing `view` whatever the80 * address: what a test navigates as a page would, and reads where it went.81 */82export const routerAt = (83 url: string,80 view: ReactNode,84 view: ReactNode = null,85 options: RenderOptions = {}82): Effect.Effect<string, Cause.UnknownError> => {83 const router = createRouter({86) =>87 createRouter({88 history: createMemoryHistory({ initialEntries: [url] }),89 rewrite: addressRewrite,90 routeTree: routesFor(view, options),91 });9293/** `view`'s static markup inside a router whose location is `url`. */94export const renderAt = (95 url: string,96 view: ReactNode,97 options: RenderOptions = {}98): Effect.Effect<string, Cause.UnknownError> => {99 const router = routerAt(url, view, options);100101 return Effect.tryPromise(() => router.load()).pipe(102 Effect.map(() => renderToStaticMarkup(<RouterProvider router={router} />))103 );104};
modified:apps/web/test/routes.test.ts+2 added-13 removed
37 unmodified lines
38]39 .filter((segment) => !notSegments.has(segment) && !segment.startsWith("$"))40 .toSorted();4142/**43 * Words reserved before the web serves a page at them: `import` is the44 * import page's address, reserved before the page lands, so no owner takes45 * it in the meantime.46 */47const RESERVED_BEFORE_THEIR_PAGE = ["import"];4842describe("the web's own paths", () => {43 it("are found: every page and file the web serves at its top", () => {44 expect(segments).toStrictEqual([45 ".well-known",
6 unmodified lines
52 "docs",53 "favicon.ico",54 "home",55 "icons",56 "import",57 "install.sh",58 "llms-full.txt",59 "llms.txt",60 "people",
11 unmodified lines
72 });7374 it("are the protocol's reserved names, where an owner could spell one", () => {75 expect(82 [83 ...segments.filter((segment) =>84 /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(segment)85 ),86 ...RESERVED_BEFORE_THEIR_PAGE,87 ].toSorted()76 segments.filter((segment) => /^[a-z0-9]+(?:-[a-z0-9]+)*$/u.test(segment))77 ).toStrictEqual([...reservedProjectNames]);78 });79});