Imran Khan
← Back to blog
Compile a Fresh Web App to a Windows EXE with Deno
FreshDenoWindowsTypeScriptDesktop AppsLocal-firstDeployment

Compile a Fresh Web App to a Windows EXE with Deno

By ··13m read

Build a searchable Fresh project archive, compile it to a Windows EXE with Deno, and verify embedded assets, local JSON saves and restart recovery.

Fresh supplies the web application; Deno compiles its server, runtime and built assets into a Windows executable. Run the .exe, and it serves the interface to an ordinary browser on the same computer. The recipient does not need a separate Deno installation. Official Fresh compilation guide.

I used that combination to build Project Archive, a searchable personal catalogue with editing, tags and local JSON persistence. The executable served its embedded interface, accepted edits and recovered them after a new server process started, including a manual session with external networking disconnected. Getting there exposed two failures: the first package omitted its stylesheet, and the server later rejected a real browser form submission that the HTTP test harness had accepted.

Below are the tested build configuration, loopback launcher, persistence design and checks. The Windows download and full source accompany the walkthrough.

What Fresh and Deno each provide

Fresh handles the application’s routes, TSX rendering and production asset output. Search is a GET form; editing is a POST followed by a redirect to the catalogue. That gives this small tool an ordinary server-rendered web interface without client state synchronization. Fresh also supports islands for selective client interactivity, but this example tests SSR pages, forms and CSS, not island packaging or hydration. Fresh architecture.

Deno provides the executable compiler and embedded runtime. The browser supplies the display. Editable records live in a separate directory:

  • Windows executable: runtime, Fresh server, application and assets; replaced for a new release.
  • Browser tab: rendered interface and forms; refreshed by navigation and submissions.
  • Local data directory: versioned project records; updated after an accepted save.

The distinction matters during updates: replace the program without replacing the user’s archive. Compilation does not create a native window or an installer. The Tamagotchi project used Tauri for a desktop simulation; this experiment keeps the browser interface and distributes its local server.

Compile the Fresh application into a Windows EXE

The tested toolchain is Fresh 2.3.3, Deno 2.9.8 and Preact 10.29.1, checked on October 25, 2026. Use the downloaded deno.json and deno.lock together. Fresh release, Deno release.

This example deliberately uses Fresh’s legacy Builder API in dev.ts. It keeps this small programmatic application’s production build explicit and inspectable. Fresh labels that API as predating its Vite plugin; a current scaffold instead has vite.config.ts and client.ts. If you start from that scaffold, retain its Vite build configuration rather than copying this example’s dev.ts. The hidden-directory failure discussed later belongs to the legacy Builder and version tested here. Pinned Builder documentation, current getting-started guide.

The exact production and compile tasks

These are the tested task definitions from deno.json:

{
  "tasks": {
    "check": "deno check main.ts store_test.ts runtime_test.ts",
    "test": "deno test --allow-read --allow-write store_test.ts runtime_test.ts",
    "build": "deno run -A dev.ts build",
    "compile": "deno compile --target x86_64-pc-windows-msvc --output project-archive.exe --include _fresh --allow-net=127.0.0.1 --allow-read --allow-write --allow-env=LOCALAPPDATA,PROJECT_ARCHIVE_DATA_DIR,DENO_DEPLOYMENT_ID,GITHUB_SHA,CI_COMMIT_SHA --allow-run=C:\\Windows\\System32\\rundll32.exe launcher.ts"
  }
}

Run deno task build before deno task compile. The first task invokes the pinned Fresh Builder, which generates _fresh/server.js, _fresh/compiled-entry.js and the production assets. The second compiles launcher.ts for Windows x64, embedding the complete _fresh directory.

Fresh’s documented baseline compiles _fresh/compiled-entry.js. This example uses a wrapper around the same generated server handler so the application controls its listener and browser-opening behavior. Do not edit the generated entry files. Deno also documents deno compile . framework detection from 2.8; the explicit build-and-entry path above is the one executed here. Fresh compile flow, Deno framework detection.

The loopback launcher

Fresh’s generated entry starts Deno.serve; it does not open a browser. It reads PORT and HOSTNAME, whereas this wrapper fixes the address to 127.0.0.1 and validates a --port argument. Fresh 2.3.3 entry generation.

The launcher’s server and browser-opening code is:

// Fresh generates the imported server module during deno task build.
import server from "./_fresh/server.js";
import { observeBrowserOpener, resolveArchivePath } from "./runtime.ts";

const portArg = Deno.args.find((arg) => arg.startsWith("--port="));
const port = portArg ? Number(portArg.slice(7)) : 47831;
if (!Number.isSafeInteger(port) || port < 1024 || port > 65535) {
  throw new Error("Port must be an integer from 1024 to 65535.");
}
const url = `http://127.0.0.1:${port}/`;
const archivePath = resolveArchivePath();
Deno.serve({
  hostname: "127.0.0.1",
  port,
  onListen() {
    console.log(
      `Project Archive: ${url}\nData: ${archivePath}\nKeep this console open; Ctrl+C stops the server.`,
    );
    if (!Deno.args.includes("--no-open")) {
      try {
        const child = new Deno.Command("C:\\Windows\\System32\\rundll32.exe", {
          args: ["url.dll,FileProtocolHandler", url],
          stdout: "null",
          stderr: "null",
        }).spawn();
        child.unref();
        void observeBrowserOpener(child.status, url);
      } catch (error) {
        console.error(
          `Browser opener could not start. Open ${url} manually.`,
          error,
        );
      }
    }
  },
}, server.fetch);

Opening the browser is a launcher convenience, separate from serving the application. --no-open prints the URL for manual opening and controlled tests. Closing the tab leaves the server running; Ctrl+C in its console stops it.

The startup message prints the resolved archive.json path, including any directory override. The launcher also watches the URL handler’s exit status asynchronously: a nonzero exit reports the manual-opening URL even if spawning succeeded. A successful handler exit alone does not prove that a browser displayed the page. Deno child-process status.

What the compiled program may access

Deno embeds runtime permission choices at compile time. The build task’s -A applies to the developer’s build process; the compile task above gives the delivered program a different permission set. Deno compile flags.

  • Network: 127.0.0.1 for the local listener and requests.
  • Environment: five named variables; two select the data directory and Fresh’s build-ID dependency reads the other three.
  • Filesystem: broad read/write access for embedded assets and a configurable external data directory.
  • Subprocess: the explicit rundll32.exe path for asking Windows to open the local URL.

The environment values may vary without granting access to every variable. Filesystem access remains broad as an implementation choice for the relocatable store; a fixed deployment directory can use a narrower allowlist. The browser opener runs outside Deno’s sandbox, even with its executable name restricted. A distribution that requires manual opening can remove the opener and its --allow-run grant. Deno permissions and subprocess boundary.

A small archive with durable local edits

Each project has a title, notes, an optional HTTP(S) URL, tags, an ID and an update timestamp. Search checks those fields; tag links combine with the query. Fresh renders the results and edit form. The essential workflow has no remote identity provider, database, font or stylesheet.

Project Archive showing the edited Lumen Notes record filtered by search and the TypeScript tag, beside the project form
Actual browser capture after creating and editing the synthetic Lumen Notes record. Search and the TypeScript tag return one project.

The default data file is independent of the executable’s location:

%LOCALAPPDATA%\CriticalDeveloper\ProjectArchive\archive.json

PROJECT_ARCHIVE_DATA_DIR can select another absolute directory, which also lets tests use isolated synthetic records. This is server-managed JSON, separate from browser cache and localStorage.

A document records its schema version, revision and project array. Each edit submits the revision it was based on. The store queues writes, checks that revision, writes and synchronizes a temporary sibling file, then renames it over the destination. Only after replacement succeeds does the server advance its in-memory revision and acknowledge the save. A stale edit gets HTTP 409, and a filesystem lock prevents two cooperating archive processes from owning the same store.

The store supports 1,000 projects, titles of 120 characters, notes of 2,000 characters and ten tags of 32 characters each. It also checks the serialized archive’s 8 MiB UTF-8 byte limit before writing. The 64 KiB encoded form-body limit accommodates valid Unicode fields. These separate limits prevent a character-valid save from creating a file the next launch refuses.

Validation, conflict and persistence failures retain the submitted draft after request/token checks. Corrupt or unrecognized JSON produces an error and preserves the original file. To back up or restore, stop the server and copy archive.json; synchronized replacement is not a backup or a power-loss guarantee. The browser draft-recovery guide explores the corresponding distinction between working text and an accepted checkpoint.

An executable cartridge powers a small archive console while a separate open drawer holds project records
Conceptual illustration: replace the program cartridge while preserving the separate project-data drawer.

Keep the local HTTP boundary explicit

Loopback binding avoids exposing the listener on the LAN, but a hostile website can still attempt requests to a local service. The application validates the numeric Host, rejects cross-site browser requests, checks the exact Origin on writes and requires a random per-process form token. URL fields accept only HTTP(S) links without embedded credentials; rendered values are escaped and the page uses a restrictive Content Security Policy.

Those checks address browser-facing requests. Other software running as the same Windows user can access the plain-text archive or call the local service. This design is a single-user tool, not an encrypted vault or a shared network service.

Two failures that changed the test plan

The companion code and harness were developed with AI assistance and a separate code-review pass. The following observations came from executed commands and browser actions on Windows 11 Pro x64, build 26200.

The executable served HTML but lost its CSS

The first relocated binary returned the expected HTML, but /styles.css returned 404. Compilation had succeeded without a complete interface.

The build ran under this article’s managed .codex checkout. Fresh 2.3.3’s legacy Builder supplied a hidden-path exclusion to its static-file walk; the absolute hidden ancestor caused the stylesheet to be skipped. Building the same source in a normal temporary staging directory included it, and the isolated executable then returned the CSS successfully. Pinned static-file walker.

The reproduction instructions therefore use a normal directory such as C:\dev\project-archive. More importantly, the executable harness requests HTML and the actual stylesheet after moving the binary away from its source. --include _fresh cannot embed a file that never reached _fresh.

The HTTP harness passed, but a browser could not save

The first real form submission returned 403 Forbidden origin. Its page used Referrer-Policy: no-referrer; for navigation-mode HTML form POSTs, that policy can make the browser send Origin: null. The HTTP harness supplied Origin explicitly, so it missed the interaction. Referrer policy’s effect on Origin.

The fix sets same-origin in both the response header and HTML metadata. Local forms retain their real origin, while cross-origin navigation receives no referrer information. The strict Origin comparison remains in place.

After that change, the browser check could create Lumen Notes, edit its notes and tags, and find it by searching Lumen and selecting typescript. Restarting preserved the edited record. A constructed HTTP request and a browser-generated form submission test different parts of the delivery.

What the Windows tests establish

The automated harness copies only the executable into a new temporary directory, sets a system-only PATH, creates an empty DENO_DIR and uses an isolated data store. The host had no installed deno command; the portable compiler and source still existed elsewhere on disk. This checks independence from neighboring source/assets and normal runtime discovery, while a clean machine remains a separate acceptance test.

For the manual run, I used a PowerShell acceptance script to record the executable’s hash, local HTTP responses, saved file and server process changes while I tested the interface in Chrome.

On a narrow screen, focus the results table to scroll it horizontally.

CheckResult and scope
Isolated executable launchHTML and embedded stylesheet served without source or assets beside the binary
Create, edit, search and tagsManually verified in Chrome; automated form checks passed
Fresh-process restartEdited notes and tags remained; old form token rejected
Competing editsOne save accepted, stale revision rejected with 409
Host, Origin, token and body guardsUnwanted requests rejected; accepted records retained
Second process / corrupt storeLock prevented shared ownership; corrupt bytes preserved
Storage testsSeven passed, including failed replacement, UTF-8 size and revision exhaustion
Path and launcher diagnosticsSix tests passed for data-path selection and simulated opener success/failure
Executable harnessFourteen grouped checks passed; executable cache remained empty
Network-disconnected browser sessionI verified editing, search, tags and restart; the acceptance script recorded disabled networking and successful local responses
Default-browser auto-openingManually verified in Chrome
Clean Windows VM, other systems and endpoint policiesNot tested

Offline here means a running local server with no external service needed for its core workflow. Browser “Offline” emulation can block loopback HTTP too, and stopping the executable stops this application’s server. External project links can require internet access. Building can also need network access for packages and Deno’s target runtime.

In that manual session, I watched Chrome open automatically, disconnected external networking, and created, edited, searched and filtered a synthetic project. I then stopped and restarted the executable while still disconnected and reloaded the page. The edited notes and tags were still there.

The acceptance script separately verified that a new server process had started and that the archive’s revision 2 and file hash remained unchanged. At the edit and restart checkpoints, it recorded zero active network adapters and no connection profiles; local HTML and CSS still returned 200. The test record keeps my manual answers alongside those measurements, including the exact browser version and executable hash.

These results describe what this run verified on one Windows PC. The linked validation record contains the detailed methods, file hashes and remaining untested cases.

Download the Windows executable and source

Download Project Archive for Windows x64 · Download the complete source

The Windows ZIP contains the .exe, launch notes, component notices and checksum. The embedded runtime makes the extracted program roughly 103 MiB. Exact byte counts and SHA-256 values for the delivered executable and archives are in the checksum manifest and validation record.

After extracting the ZIP, run the ordinary launcher:

.\project-archive.exe

The default browser should open http://127.0.0.1:47831/. For manual opening or automated tests, use --no-open and copy that URL. The README documents --port if it is occupied. The optional opener assumes C:\Windows for its system executable path.

To rebuild, install Deno 2.9.8 on the build machine, extract the source into a normal directory such as C:\dev\project-archive, and run:

deno task check
deno task test
deno task build
deno check launcher.ts
deno task compile
.\project-archive.exe --no-open

With Node 22 or later on the test machine, exercise the finished artifact:

node verify-exe.mjs .\project-archive.exe

Node is a harness dependency, not an application runtime requirement. All runnable sources are included below; the download excludes dependencies, build output and user records.

The initial check task selects the application and test files explicitly, so it works before _fresh exists. The launcher imports generated output, so its separate check comes after the build. This order is tested from a fresh source extraction. Deno check.

Source files

12 files
app.tsx

Fresh routes, request guards and file-store ownership

181 lines · TypeScript JSXOpen fileDownload
import { App, staticFiles } from "fresh";
import { dirname, join } from "@std/path";
import { ArchiveStore, Conflict, InvalidInput } from "./store.ts";
import { ArchivePage } from "./ui.tsx";
import { resolveArchivePath } from "./runtime.ts";

export const app = new App();
const archivePath = resolveArchivePath();
const token = crypto.randomUUID();
let store: ArchiveStore | undefined;
let lock: Deno.FsFile | undefined;
let startupError: string | undefined;

async function openStore(): Promise<ArchiveStore> {
  if (startupError) throw new Error(startupError);
  if (store) return store;
  const base = dirname(archivePath);
  await Deno.mkdir(base, { recursive: true });
  const candidate = await Deno.open(join(base, "archive.lock"), {
    create: true,
    write: true,
  });
  try {
    if (!await candidate.tryLock(true)) throw new Error("Locked");
  } catch {
    candidate.close();
    throw new Error("Archive is already open in another process.");
  }
  lock = candidate;
  try {
    store = await ArchiveStore.open(archivePath);
  } catch (error) {
    lock.close();
    lock = undefined;
    startupError = error instanceof Error
      ? error.message
      : "Archive unavailable.";
    throw error;
  }
  return store;
}
let ready: Promise<ArchiveStore> | undefined;
function repository(): Promise<ArchiveStore> {
  return ready ??= openStore();
}

app.use(async (ctx) => {
  const url = new URL(ctx.req.url);
  if (
    url.hostname !== "127.0.0.1" || ctx.req.headers.get("host") !== url.host ||
    ctx.req.headers.get("sec-fetch-site") === "cross-site"
  ) return new Response("Forbidden host or site", { status: 403 });
  if (
    !["GET", "HEAD"].includes(ctx.req.method) &&
    ctx.req.headers.get("origin") !== url.origin
  ) {
    return new Response("Forbidden origin", { status: 403 });
  }
  const response = await ctx.next();
  response.headers.set("Cache-Control", "no-store");
  response.headers.set("X-Content-Type-Options", "nosniff");
  response.headers.set("Referrer-Policy", "same-origin");
  response.headers.set(
    "Content-Security-Policy",
    "default-src 'self'; style-src 'self'; script-src 'none'; img-src 'self' data:; base-uri 'none'; frame-ancestors 'none'; form-action 'self'",
  );
  return response;
});
app.use(staticFiles());
app.get("/", async (ctx) => {
  try {
    const archive = (await repository()).snapshot();
    const query = (ctx.url.searchParams.get("q") || "").slice(0, 200);
    const tag = (ctx.url.searchParams.get("tag") || "").slice(0, 32);
    const edit = archive.projects.find((item) =>
      item.id === ctx.url.searchParams.get("edit")
    );
    return ctx.render(
      <ArchivePage
        archive={archive}
        query={query}
        tag={tag}
        token={token}
        edit={edit}
        saved={ctx.url.searchParams.has("saved")}
      />,
    );
  } catch (error) {
    console.error(error);
    return new Response(
      "Archive unavailable. Check the console; existing data has not been reset.",
      { status: 503 },
    );
  }
});
app.post("/save", async (ctx) => {
  if (
    !(ctx.req.headers.get("content-type") || "").startsWith(
      "application/x-www-form-urlencoded",
    )
  ) {
    return new Response("Use a form-encoded request", { status: 415 });
  }
  const max = 65_536;
  const chunks: Uint8Array[] = [];
  let length = 0;
  for await (
    const chunk of ctx.req.body ?? new ReadableStream<Uint8Array>({
      start(c) {
        c.close();
      },
    })
  ) {
    length += chunk.length;
    if (length > max) return new Response("Request too large", { status: 413 });
    chunks.push(chunk);
  }
  const bytes = new Uint8Array(length);
  let offset = 0;
  for (const chunk of chunks) {
    bytes.set(chunk, offset);
    offset += chunk.length;
  }
  const form = new URLSearchParams(new TextDecoder().decode(bytes));
  if (form.get("token") !== token) {
    return new Response("Invalid form token; reload the page.", {
      status: 403,
    });
  }
  try {
    const revision = Number(form.get("revision"));
    if (
      !form.has("revision") || !Number.isSafeInteger(revision) || revision < 0
    ) throw new InvalidInput("Invalid revision.");
    await (await repository()).save(
      {
        title: form.get("title"),
        description: form.get("description"),
        url: form.get("url"),
        tags: (form.get("tags") || "").split(",").map((tag) => tag.trim())
          .filter(Boolean),
      },
      form.get("id") || "",
      revision,
    );
    return new Response(null, {
      status: 303,
      headers: { Location: "/?saved=1" },
    });
  } catch (error) {
    const conflict = error instanceof Conflict;
    const invalid = error instanceof InvalidInput;
    if (!conflict && !invalid) console.error(error);
    const message = conflict
      ? `${error.message} Your submitted draft is retained below. Copy it before opening the latest saved version.`
      : invalid
      ? error.message
      : "Save failed. Your draft is retained below; check the console before retrying.";
    const archive = store?.snapshot() ??
      { version: 1 as const, revision: 0, projects: [] };
    return ctx.render(
      <ArchivePage
        archive={archive}
        query=""
        tag=""
        token={token}
        revision={Number(form.get("revision")) || 0}
        error={message}
        edit={{
          id: form.get("id") || "",
          title: form.get("title") || "",
          description: form.get("description") || "",
          url: form.get("url") || "",
          tags: (form.get("tags") || "").split(","),
          updatedAt: new Date().toISOString(),
        }}
      />,
      { status: conflict ? 409 : invalid ? 400 : 503 },
    );
  }
});
ui.tsx

Search, tags, editing and recoverable form errors

343 lines · TypeScript JSXOpen fileDownload
import type { Archive, Project } from "./store.ts";

type ArchivePageProps = {
  archive: Archive;
  query: string;
  tag: string;
  token: string;
  edit?: Project;
  error?: string;
  saved?: boolean;
  revision?: number;
};

function archiveLink(query: string, tag = "") {
  const params = new URLSearchParams();
  if (query) params.set("q", query);
  if (tag) params.set("tag", tag);
  return params.size ? `/?${params}` : "/";
}

export function ArchivePage(
  { archive, query, tag, token, edit, error, saved, revision }:
    ArchivePageProps,
) {
  const words = query.toLocaleLowerCase("en").trim();
  const projects = archive.projects.filter((project) =>
    (!tag || project.tags.includes(tag)) &&
    (!words ||
      [project.title, project.description, project.url, ...project.tags].join(
        " ",
      )
        .toLocaleLowerCase("en").includes(words))
  ).sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));
  const tags = [...new Set(archive.projects.flatMap((project) => project.tags))]
    .sort((a, b) => a.localeCompare(b));

  return (
    <html lang="en">
      <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <meta name="color-scheme" content="dark" />
        <meta name="referrer" content="same-origin" />
        <title>Project Archive — Local Edition</title>
        <link rel="stylesheet" href="/styles.css" />
      </head>
      <body>
        <a class="skip-link" href="#archive">Skip to projects</a>
        <div class="shell">
          <header class="masthead">
            <a class="brand" href="/" aria-label="Project Archive home">
              <svg
                viewBox="0 0 32 32"
                aria-hidden="true"
                width="32"
                height="32"
              >
                <path d="M4 8h24v19H4zM8 4h16v4M10 14h12M10 20h8" />
              </svg>
              <span>PROJECT ARCHIVE</span>
            </a>
            <span class="local-badge">
              <span /> LOCAL EDITION
            </span>
          </header>

          <main>
            <section class="intro" aria-labelledby="page-title">
              <div>
                <p class="eyebrow">YOUR WORK, WITHIN REACH</p>
                <h1 id="page-title">Keep the useful things.</h1>
                <p class="intro__text">
                  A personal index of projects, experiments and ideas worth
                  returning to. Search it. Refine it. Make something next.
                </p>
              </div>
              <div
                class="archive-count"
                aria-label={`${archive.projects.length} projects in archive`}
              >
                <span>{String(archive.projects.length).padStart(2, "0")}</span>
                <span>
                  PROJECTS<br />ON FILE
                </span>
              </div>
            </section>

            <div class="workspace">
              <section
                id="archive"
                class="collection"
                aria-labelledby="archive-title"
              >
                <div class="section-title">
                  <h2 id="archive-title">The collection</h2>
                  <span>{projects.length} SHOWN</span>
                </div>
                <form class="search" action="/" method="get" role="search">
                  <label for="query">Search projects</label>
                  <div class="search__field">
                    <svg
                      viewBox="0 0 24 24"
                      aria-hidden="true"
                      width="20"
                      height="20"
                    >
                      <circle cx="10" cy="10" r="6" />
                      <path d="m15 15 5 5" />
                    </svg>
                    <input
                      id="query"
                      name="q"
                      type="search"
                      value={query}
                      maxLength={200}
                      placeholder="Title, notes, link or tag…"
                    />
                    {tag && <input type="hidden" name="tag" value={tag} />}
                    <button type="submit">Search</button>
                  </div>
                </form>

                {(tags.length > 0 || tag) && (
                  <nav class="tag-filter" aria-label="Filter projects by tag">
                    <a
                      class={!tag
                        ? "tag-filter__item is-active"
                        : "tag-filter__item"}
                      href={archiveLink(query)}
                      aria-current={!tag ? "true" : undefined}
                    >
                      All projects
                    </a>
                    {tags.map((value) => (
                      <a
                        key={value}
                        class={tag === value
                          ? "tag-filter__item is-active"
                          : "tag-filter__item"}
                        href={archiveLink(query, value)}
                        aria-current={tag === value ? "true" : undefined}
                      >
                        {value}
                      </a>
                    ))}
                    {tag && !tags.includes(tag) && (
                      <span class="tag-filter__item is-active">{tag}</span>
                    )}
                  </nav>
                )}

                {projects.length === 0
                  ? (
                    <div class="empty-state">
                      <span class="empty-state__mark" aria-hidden="true">
                        [ + ]
                      </span>
                      <h3>
                        {archive.projects.length
                          ? "No projects in this view."
                          : "Every archive starts somewhere."}
                      </h3>
                      <p>
                        {archive.projects.length
                          ? "Try a different search or clear the filters to see your collection."
                          : "Add your first project using the form. A small experiment is a good place to begin."}
                      </p>
                      {archive.projects.length > 0 && (
                        <a href="/">Clear search and filters</a>
                      )}
                    </div>
                  )
                  : (
                    <ol class="projects">
                      {projects.map((project, index) => (
                        <li key={project.id}>
                          <article
                            class={edit?.id === project.id
                              ? "project is-editing"
                              : "project"}
                          >
                            <span class="project__number" aria-hidden="true">
                              {String(index + 1).padStart(2, "0")}
                            </span>
                            <div class="project__body">
                              <div class="project__heading">
                                <h3>{project.title}</h3>
                                <a
                                  class="edit-link"
                                  href={`/?edit=${
                                    encodeURIComponent(project.id)
                                  }#editor`}
                                  aria-label={`Edit ${project.title}`}
                                >
                                  Edit <span aria-hidden="true">↗</span>
                                </a>
                              </div>
                              <p class="project__description">
                                {project.description || "No notes yet."}
                              </p>
                              <div class="project__meta">
                                <div class="project__tags">
                                  {project.tags.map((value) => (
                                    <a
                                      key={value}
                                      href={archiveLink("", value)}
                                    >
                                      {value}
                                    </a>
                                  ))}
                                  {project.tags.length === 0 && (
                                    <span class="untagged">UNTAGGED</span>
                                  )}
                                </div>
                                <time dateTime={project.updatedAt}>
                                  {new Date(project.updatedAt)
                                    .toLocaleDateString("en-GB", {
                                      day: "2-digit",
                                      month: "short",
                                      year: "numeric",
                                      timeZone: "UTC",
                                    })}
                                </time>
                              </div>
                              {project.url && (
                                <a
                                  class="project__url"
                                  href={project.url}
                                  target="_blank"
                                  rel="noopener noreferrer"
                                >
                                  {project.url}
                                  <span aria-hidden="true">↗</span>
                                </a>
                              )}
                            </div>
                          </article>
                        </li>
                      ))}
                    </ol>
                  )}
              </section>

              <aside id="editor" class="editor" aria-labelledby="editor-title">
                <div class="editor__topline">
                  <span class="eyebrow">ARCHIVE DESK</span>
                  <span aria-hidden="true">+</span>
                </div>
                <h2 id="editor-title">
                  {edit ? "Refine a project." : "Add something good."}
                </h2>
                <p class="editor__intro">
                  {edit
                    ? "Keep the details useful for your future self."
                    : "A name, a few notes, a place to find it."}
                </p>
                {saved && (
                  <p class="notice notice--success" role="status">
                    Saved to your local archive.
                  </p>
                )}
                {error && (
                  <p class="notice notice--error" role="alert">{error}</p>
                )}
                <form class="editor-form" action="/save" method="post">
                  <input type="hidden" name="token" value={token} />
                  <input
                    type="hidden"
                    name="revision"
                    value={String(revision ?? archive.revision)}
                  />
                  <input type="hidden" name="id" value={edit?.id ?? ""} />
                  <label for="title">
                    Project name <span>REQUIRED</span>
                  </label>
                  <input
                    id="title"
                    name="title"
                    value={edit?.title ?? ""}
                    required
                    maxLength={120}
                    autoComplete="off"
                    placeholder="A name worth remembering"
                  />
                  <label for="description">Notes</label>
                  <textarea
                    id="description"
                    name="description"
                    rows={4}
                    maxLength={2000}
                    placeholder="What it does. Why it matters. What comes next."
                  >
                    {edit?.description ?? ""}
                  </textarea>
                  <label for="url">
                    Project link <span>OPTIONAL</span>
                  </label>
                  <input
                    id="url"
                    name="url"
                    type="url"
                    value={edit?.url ?? ""}
                    maxLength={2048}
                    placeholder="https://example.com"
                  />
                  <label for="tags">Tags</label>
                  <input
                    id="tags"
                    name="tags"
                    value={edit?.tags.join(", ") ?? ""}
                    maxLength={338}
                    placeholder="tool, experiment, weekend"
                    aria-describedby="tags-hint"
                  />
                  <p id="tags-hint" class="field-hint">
                    Separate with commas. Up to 10 tags, 32 characters each.
                  </p>
                  <button class="save-button" type="submit">
                    {edit ? "Save changes" : "Add to archive"}
                    <span aria-hidden="true">↗</span>
                  </button>
                  {edit && <a class="cancel-link" href="/">Cancel editing</a>}
                </form>
                <div class="storage-note">
                  <span class="storage-note__dot" aria-hidden="true" />
                  <p>
                    <strong>Stored on this computer.</strong>{" "}
                    Saves live in a local file, outside the executable. Keep the
                    archive server running while you work.
                  </p>
                </div>
              </aside>
            </div>
          </main>
          <footer class="footer">
            <span>SMALL TOOLS. LASTING WORK.</span>
            <span>Fresh / Deno · Local archive v1</span>
          </footer>
        </div>
      </body>
    </html>
  );
}
store.ts

Validated JSON persistence and revision control

194 lines · TypeScriptOpen fileDownload
import { dirname } from "@std/path";

export interface Project {
  id: string;
  title: string;
  description: string;
  url: string;
  tags: string[];
  updatedAt: string;
}
export interface Archive {
  version: 1;
  revision: number;
  projects: Project[];
}
export class Conflict extends Error {}
export class InvalidInput extends Error {}
export const MAX_ARCHIVE_BYTES = 8 * 1024 * 1024;

function text(
  value: unknown,
  name: string,
  max: number,
  required = false,
): string {
  if (
    typeof value !== "string" || value.length > max ||
    (required && !value.trim())
  ) {
    throw new InvalidInput(`Invalid ${name}.`);
  }
  return value.trim();
}

export function projectInput(
  value: Record<string, unknown>,
): Omit<Project, "id" | "updatedAt"> {
  const title = text(value.title, "title", 120, true);
  const description = text(value.description, "description", 2000);
  const url = text(value.url, "URL", 2048);
  if (url) {
    let parsed: URL;
    try {
      parsed = new URL(url);
    } catch {
      throw new InvalidInput("Use an absolute HTTP(S) URL.");
    }
    if (
      !["http:", "https:"].includes(parsed.protocol) || parsed.username ||
      parsed.password
    ) {
      throw new InvalidInput("Use an HTTP(S) URL without credentials.");
    }
  }
  if (!Array.isArray(value.tags) || value.tags.length > 10) {
    throw new InvalidInput("Use at most 10 tags.");
  }
  const tags = [
    ...new Set(
      value.tags.map((tag) => text(tag, "tag", 32, true).toLowerCase()),
    ),
  ];
  return { title, description, url, tags };
}

function validate(value: unknown): Archive {
  if (!value || typeof value !== "object") {
    throw new Error("Archive is not an object.");
  }
  const data = value as Archive;
  if (
    data.version !== 1 || !Number.isSafeInteger(data.revision) ||
    data.revision < 0 ||
    !Array.isArray(data.projects) || data.projects.length > 1000
  ) throw new Error("Unsupported archive schema.");
  const ids = new Set<string>();
  for (const item of data.projects) {
    const id = text(item.id, "id", 36, true);
    if (!/^[a-f0-9-]{36}$/.test(id) || ids.has(id)) {
      throw new Error("Invalid or duplicate project ID.");
    }
    ids.add(id);
    if (
      typeof item.updatedAt !== "string" ||
      !Number.isFinite(Date.parse(item.updatedAt))
    ) throw new Error("Invalid timestamp.");
    projectInput(item as unknown as Record<string, unknown>);
  }
  return data;
}

export class ArchiveStore {
  #data: Archive;
  #tail = Promise.resolve();
  private constructor(readonly path: string, data: Archive) {
    this.#data = data;
  }
  static async open(path: string): Promise<ArchiveStore> {
    let data: Archive;
    try {
      const info = await Deno.stat(path);
      if (info.size > MAX_ARCHIVE_BYTES) {
        throw new Error("Archive exceeds 8 MiB.");
      }
      data = validate(JSON.parse(await Deno.readTextFile(path)));
    } catch (error) {
      if (!(error instanceof Deno.errors.NotFound)) {
        throw new Error(
          `Archive could not be loaded; original file preserved: ${path}`,
          { cause: error },
        );
      }
      data = { version: 1, revision: 0, projects: [] };
    }
    return new ArchiveStore(path, data);
  }
  snapshot(): Archive {
    return structuredClone(this.#data);
  }
  async save(
    input: Record<string, unknown>,
    id: string,
    revision: number,
  ): Promise<void> {
    const next = this.#tail.then(async () => {
      if (revision !== this.#data.revision) {
        throw new Conflict(
          "Another save changed the archive. Reload and review before saving again.",
        );
      }
      if (revision === Number.MAX_SAFE_INTEGER) {
        throw new InvalidInput(
          "Archive revision is exhausted; export and migrate before saving.",
        );
      }
      if (id && !this.#data.projects.some((item) => item.id === id)) {
        throw new InvalidInput("Project no longer exists.");
      }
      if (!id && this.#data.projects.length >= 1000) {
        throw new InvalidInput("Archive limit is 1,000 projects.");
      }
      const project = {
        ...projectInput(input),
        id: id || crypto.randomUUID(),
        updatedAt: new Date().toISOString(),
      };
      const data: Archive = {
        version: 1,
        revision: revision + 1,
        projects: id
          ? this.#data.projects.map((item) => item.id === id ? project : item)
          : [...this.#data.projects, project],
      };
      const bytes = new TextEncoder().encode(
        JSON.stringify(data, null, 2) + "\n",
      );
      if (bytes.length > MAX_ARCHIVE_BYTES) {
        throw new InvalidInput(
          "Archive exceeds 8 MiB; shorten existing records before adding more.",
        );
      }
      await Deno.mkdir(dirname(this.path), { recursive: true });
      const temp = await Deno.makeTempFile({
        dir: dirname(this.path),
        prefix: ".archive-",
        suffix: ".tmp",
      });
      try {
        const file = await Deno.open(temp, { write: true, truncate: true });
        try {
          let written = 0;
          while (written < bytes.length) {
            written += await file.write(bytes.subarray(written));
          }
          await file.sync();
        } finally {
          file.close();
        }
        await Deno.rename(temp, this.path);
        this.#data = data;
      } finally {
        try {
          await Deno.remove(temp);
        } catch (error) {
          if (!(error instanceof Deno.errors.NotFound)) {
            console.error("Temporary-file cleanup failed", error);
          }
        }
      }
    });
    this.#tail = next.catch(() => {});
    return await next;
  }
}
runtime.ts

Shared data-path resolution and browser-opener diagnostics

36 lines · TypeScriptOpen fileDownload
import { isAbsolute, join } from "@std/path";

export function resolveArchivePath(
  readEnv: (name: string) => string | undefined = (name) => Deno.env.get(name),
): string {
  const override = readEnv("PROJECT_ARCHIVE_DATA_DIR");
  const localAppData = override ? undefined : readEnv("LOCALAPPDATA");
  const directory = override ||
    (localAppData && join(localAppData, "CriticalDeveloper", "ProjectArchive"));
  if (!directory || !isAbsolute(directory)) {
    throw new Error(
      "Set LOCALAPPDATA or an absolute PROJECT_ARCHIVE_DATA_DIR.",
    );
  }
  return join(directory, "archive.json");
}

export async function observeBrowserOpener(
  status: Promise<{ success: boolean; code: number }>,
  url: string,
  report: (message: string) => void = console.error,
): Promise<void> {
  try {
    const result = await status;
    if (!result.success) {
      report(
        `Windows browser opener exited with code ${result.code}. Open ${url} manually.`,
      );
    }
  } catch (error) {
    const detail = error instanceof Error ? error.message : String(error);
    report(
      `Could not observe the Windows browser opener: ${detail}. Open ${url} manually.`,
    );
  }
}
launcher.ts

Loopback listener and optional browser opener

36 lines · TypeScriptOpen fileDownload
// Fresh generates the imported server module during deno task build.
import server from "./_fresh/server.js";
import { observeBrowserOpener, resolveArchivePath } from "./runtime.ts";

const portArg = Deno.args.find((arg) => arg.startsWith("--port="));
const port = portArg ? Number(portArg.slice(7)) : 47831;
if (!Number.isSafeInteger(port) || port < 1024 || port > 65535) {
  throw new Error("Port must be an integer from 1024 to 65535.");
}
const url = `http://127.0.0.1:${port}/`;
const archivePath = resolveArchivePath();
Deno.serve({
  hostname: "127.0.0.1",
  port,
  onListen() {
    console.log(
      `Project Archive: ${url}\nData: ${archivePath}\nKeep this console open; Ctrl+C stops the server.`,
    );
    if (!Deno.args.includes("--no-open")) {
      try {
        const child = new Deno.Command("C:\\Windows\\System32\\rundll32.exe", {
          args: ["url.dll,FileProtocolHandler", url],
          stdout: "null",
          stderr: "null",
        }).spawn();
        child.unref();
        void observeBrowserOpener(child.status, url);
      } catch (error) {
        console.error(
          `Browser opener could not start. Open ${url} manually.`,
          error,
        );
      }
    }
  },
}, server.fetch);
main.ts

Application export for the Fresh build

1 line · TypeScriptOpen fileDownload
export { app } from "./app.tsx";
dev.ts

Pinned legacy Fresh Builder entry

7 lines · TypeScriptOpen fileDownload
import { Builder } from "fresh/dev";
const builder = new Builder();
if (Deno.args.includes("build")) await builder.build();
else {await builder.listen(() => import("./main.ts"), {
    hostname: "127.0.0.1",
    port: 47831,
  });}
deno.json

Pinned imports, tasks and compile permissions

37 lines · JSONOpen fileDownload
{
  "nodeModulesDir": "auto",
  "imports": {
    "fresh": "jsr:@fresh/core@2.3.3",
    "preact": "npm:preact@10.29.1",
    "@std/path": "jsr:@std/path@1.1.6"
  },
  "compilerOptions": {
    "lib": ["dom", "dom.iterable", "deno.ns"],
    "jsx": "precompile",
    "jsxImportSource": "preact",
    "jsxPrecompileSkipElements": [
      "a",
      "img",
      "source",
      "body",
      "html",
      "head",
      "title",
      "meta",
      "script",
      "link",
      "style",
      "base",
      "noscript",
      "template"
    ]
  },
  "tasks": {
    "check": "deno check main.ts store_test.ts runtime_test.ts",
    "test": "deno test --allow-read --allow-write store_test.ts runtime_test.ts",
    "build": "deno run -A dev.ts build",
    "dev": "deno run -A dev.ts",
    "compile": "deno compile --target x86_64-pc-windows-msvc --output project-archive.exe --include _fresh --allow-net=127.0.0.1 --allow-read --allow-write --allow-env=LOCALAPPDATA,PROJECT_ARCHIVE_DATA_DIR,DENO_DEPLOYMENT_ID,GITHUB_SHA,CI_COMMIT_SHA --allow-run=C:\\Windows\\System32\\rundll32.exe launcher.ts"
  },
  "exclude": ["_fresh", "node_modules"]
}
store_test.ts

Seven storage regressions

187 lines · TypeScriptOpen fileDownload
import {
  ArchiveStore,
  Conflict,
  InvalidInput,
  MAX_ARCHIVE_BYTES,
  projectInput,
} from "./store.ts";
import { join } from "@std/path";

function assert(value: unknown, message = "Assertion failed"): asserts value {
  if (!value) throw new Error(message);
}
const input = {
  title: "Offline archive",
  description: "A synthetic project.",
  url: "https://example.com/archive",
  tags: ["local", "tools"],
};

Deno.test("save, replace and reopen preserve one record and increment revision", async () => {
  const dir = await Deno.makeTempDir();
  try {
    const path = join(dir, "archive.json");
    const store = await ArchiveStore.open(path);
    await store.save(input, "", 0);
    const id = store.snapshot().projects[0].id;
    await store.save({ ...input, title: "Edited offline" }, id, 1);
    const reopened = (await ArchiveStore.open(path)).snapshot();
    assert(reopened.revision === 2 && reopened.projects.length === 1);
    assert(reopened.projects[0].title === "Edited offline");
    assert(
      [...Deno.readDirSync(dir)].every((entry) => !entry.name.endsWith(".tmp")),
    );
  } finally {
    await Deno.remove(dir, { recursive: true });
  }
});
Deno.test("two saves at one revision allow one winner and reject stale writer", async () => {
  const dir = await Deno.makeTempDir();
  try {
    const store = await ArchiveStore.open(join(dir, "archive.json"));
    const results = await Promise.allSettled([
      store.save(input, "", 0),
      store.save(input, "", 0),
    ]);
    assert(
      results.filter((result) => result.status === "fulfilled").length === 1,
    );
    assert(
      results.some((result) =>
        result.status === "rejected" && result.reason instanceof Conflict
      ),
    );
    assert(store.snapshot().projects.length === 1);
  } finally {
    await Deno.remove(dir, { recursive: true });
  }
});
Deno.test("corrupt archive is rejected without overwriting the original", async () => {
  const dir = await Deno.makeTempDir();
  try {
    const path = join(dir, "archive.json");
    await Deno.writeTextFile(path, "{corrupt");
    let failed = false;
    try {
      await ArchiveStore.open(path);
    } catch {
      failed = true;
    }
    assert(failed);
    assert(await Deno.readTextFile(path) === "{corrupt");
  } finally {
    await Deno.remove(dir, { recursive: true });
  }
});
Deno.test("disk write failure leaves in-memory saved revision unchanged", async () => {
  const dir = await Deno.makeTempDir();
  try {
    const path = join(dir, "archive.json");
    const store = await ArchiveStore.open(path);
    await Deno.mkdir(path);
    let failed = false;
    try {
      await store.save(input, "", 0);
    } catch {
      failed = true;
    }
    assert(failed && store.snapshot().revision === 0);
  } finally {
    await Deno.remove(dir, { recursive: true });
  }
});
Deno.test("invalid URL, excessive tags and empty title rejected; valid tags normalized", () => {
  for (
    const bad of [{ ...input, url: "javascript:alert(1)" }, {
      ...input,
      tags: Array(11).fill("x"),
    }, { ...input, title: " " }]
  ) {
    let error: unknown;
    try {
      projectInput(bad);
    } catch (caught) {
      error = caught;
    }
    assert(error instanceof InvalidInput);
  }
  assert(
    projectInput({ ...input, tags: ["Tools", "tools"] }).tags.join() ===
      "tools",
  );
});

Deno.test("UTF-8 byte cap rejects a save before replacing a readable archive", async () => {
  const dir = await Deno.makeTempDir();
  try {
    const path = join(dir, "archive.json");
    const full = {
      title: "界".repeat(120),
      description: "界".repeat(2000),
      url: "https://example.com/" + "界".repeat(2020),
      tags: Array.from({ length: 10 }, (_, i) => String(i) + "界".repeat(31)),
    };
    const sample = {
      ...full,
      id: crypto.randomUUID(),
      updatedAt: new Date().toISOString(),
    };
    const recordBytes =
      new TextEncoder().encode(JSON.stringify(sample, null, 2)).length + 160;
    const count = Math.floor(MAX_ARCHIVE_BYTES / recordBytes);
    const data = {
      version: 1,
      revision: 0,
      projects: Array.from(
        { length: count },
        () => ({ ...sample, id: crypto.randomUUID() }),
      ),
    };
    let serialized = JSON.stringify(data, null, 2) + "\n";
    while (
      new TextEncoder().encode(serialized).length <
        MAX_ARCHIVE_BYTES - recordBytes + 200
    ) {
      data.projects.push({ ...sample, id: crypto.randomUUID() });
      serialized = JSON.stringify(data, null, 2) + "\n";
    }
    assert(new TextEncoder().encode(serialized).length <= MAX_ARCHIVE_BYTES);
    await Deno.writeTextFile(path, serialized);
    const store = await ArchiveStore.open(path);
    let failed = false;
    try {
      await store.save(full, "", 0);
    } catch (error) {
      failed = error instanceof InvalidInput;
    }
    assert(failed && store.snapshot().revision === 0);
    assert(await Deno.readTextFile(path) === serialized);
    assert((await ArchiveStore.open(path)).snapshot().revision === 0);
  } finally {
    await Deno.remove(dir, { recursive: true });
  }
});
Deno.test("exhausted revision is never incremented to an unreadable integer", async () => {
  const dir = await Deno.makeTempDir();
  try {
    const path = join(dir, "archive.json");
    await Deno.writeTextFile(
      path,
      JSON.stringify({
        version: 1,
        revision: Number.MAX_SAFE_INTEGER,
        projects: [],
      }),
    );
    const store = await ArchiveStore.open(path);
    let failed = false;
    try {
      await store.save(input, "", Number.MAX_SAFE_INTEGER);
    } catch (error) {
      failed = error instanceof InvalidInput;
    }
    assert(failed && store.snapshot().revision === Number.MAX_SAFE_INTEGER);
  } finally {
    await Deno.remove(dir, { recursive: true });
  }
});
runtime_test.ts

Six path and opener-status checks

96 lines · TypeScriptOpen fileDownload
import { join } from "@std/path";
import { observeBrowserOpener, resolveArchivePath } from "./runtime.ts";

function assert(value: unknown, message = "Assertion failed"): asserts value {
  if (!value) throw new Error(message);
}
function environment(values: Record<string, string | undefined>) {
  return (name: string) => values[name];
}
const fixtureRoot = Deno.build.os === "windows"
  ? "C:\\Archive fixtures"
  : "/tmp/archive fixtures";

Deno.test("archive override is absolute, normalized and wins over LOCALAPPDATA", () => {
  const reads: string[] = [];
  const result = resolveArchivePath((name) => {
    reads.push(name);
    return environment({
      PROJECT_ARCHIVE_DATA_DIR: `${fixtureRoot}/unused/../Personal projects`,
      LOCALAPPDATA: "invalid relative fallback",
    })(name);
  });
  assert(result === join(fixtureRoot, "Personal projects", "archive.json"));
  assert(reads.join() === "PROJECT_ARCHIVE_DATA_DIR");
});

Deno.test("missing or empty override resolves the per-user default archive file", () => {
  for (const override of [undefined, ""]) {
    const result = resolveArchivePath(environment({
      PROJECT_ARCHIVE_DATA_DIR: override,
      LOCALAPPDATA: fixtureRoot,
    }));
    assert(
      result ===
        join(
          fixtureRoot,
          "CriticalDeveloper",
          "ProjectArchive",
          "archive.json",
        ),
    );
  }
});

Deno.test("missing and relative data directories fail before a misleading path is printed", () => {
  for (
    const values of [{}, { PROJECT_ARCHIVE_DATA_DIR: "relative/archive" }, {
      LOCALAPPDATA: "relative/profile",
    }]
  ) {
    let error: unknown;
    try {
      resolveArchivePath(environment(values));
    } catch (caught) {
      error = caught;
    }
    assert(error instanceof Error);
    assert(error.message.includes("absolute PROJECT_ARCHIVE_DATA_DIR"));
  }
});

Deno.test("successful opener status produces no claim that a browser loaded", async () => {
  const messages: string[] = [];
  await observeBrowserOpener(
    Promise.resolve({ success: true, code: 0 }),
    "http://127.0.0.1:47831/",
    (message) => messages.push(message),
  );
  assert(messages.length === 0);
});

Deno.test("failed opener exit reports its code and a manual URL fallback", async () => {
  const messages: string[] = [];
  const url = "http://127.0.0.1:47831/";
  await observeBrowserOpener(
    Promise.resolve({ success: false, code: 31 }),
    url,
    (message) => messages.push(message),
  );
  assert(messages.length === 1);
  assert(messages[0].includes("31") && messages[0].includes(url));
  assert(messages[0].includes("manually"));
});

Deno.test("rejected opener status is handled with useful diagnostic and manual URL", async () => {
  const messages: string[] = [];
  const url = "http://127.0.0.1:47831/";
  await observeBrowserOpener(
    Promise.reject(new Error("status channel unavailable")),
    url,
    (message) => messages.push(message),
  );
  assert(messages.length === 1);
  assert(messages[0].includes("status channel unavailable"));
  assert(messages[0].includes(url) && messages[0].includes("manually"));
});
verify-exe.mjs

Isolated Windows executable checks

158 lines · JavaScriptOpen fileDownload
import { spawn } from "node:child_process";
import { mkdtemp, copyFile, mkdir, readFile, writeFile, readdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import assert from "node:assert/strict";
import { request } from "node:http";

// Runs on Windows with Node 22+; Deno is deliberately absent from child PATH.
const exeSource = resolve(process.argv[2] || "project-archive.exe");
const root = await mkdtemp(join(tmpdir(), "fresh-archive-exe-"));
const runDir = join(root, "run");
const dataDir = join(root, "data with spaces");
const cacheDir = join(root, "empty-cache");
await Promise.all([mkdir(runDir), mkdir(dataDir), mkdir(cacheDir)]);
const exe = join(runDir, "project-archive.exe");
await copyFile(exeSource, exe);
const base = "http://127.0.0.1:47832";
const children = new Set();
const childOutput = new Map();
let logs = "";
const env = { ...process.env, PATH: "C:\\Windows\\System32;C:\\Windows", DENO_DIR: cacheDir,
  PROJECT_ARCHIVE_DATA_DIR: dataDir };
function launch(port = 47832, overrides = {}) {
  const child = spawn(exe, ["--no-open", `--port=${port}`], { cwd: runDir, env: { ...env, ...overrides }, windowsHide: true });
  children.add(child);
  childOutput.set(child, "");
  const collect = (chunk) => { logs += chunk; childOutput.set(child, childOutput.get(child) + chunk); };
  child.stdout.on("data", collect);
  child.stderr.on("data", collect);
  return child;
}
async function startupPath(child, expectedPath) {
  for (let i = 0; i < 100; i++) {
    if (childOutput.get(child).replace(/\r\n/g, "\n").includes(`Data: ${expectedPath}\n`)) return;
    await new Promise((done) => setTimeout(done, 20));
  }
  assert.fail(`Startup did not print its resolved archive path: ${childOutput.get(child)}`);
}
async function stop(child) {
  if (child.exitCode !== null) return;
  child.kill();
  await new Promise((done) => child.once("exit", done));
  children.delete(child);
}
async function ready(url = base, status = 200) {
  for (let i = 0; i < 100; i++) {
    try { const result = await fetch(url); if (result.status === status) return result; await result.text(); }
    catch { /* start-up race */ }
    await new Promise((done) => setTimeout(done, 100));
  }
  throw new Error(`Server did not return ${status}: ${logs}`);
}
function tokenAndRevision(html) {
  return { token: html.match(/name="token"[^>]*value="([^"]+)"/)[1],
    revision: html.match(/name="revision"[^>]*value="([^"]+)"/)[1] };
}
async function post(values, headers = {}) {
  return await fetch(`${base}/save`, { method: "POST", redirect: "manual",
    headers: { "Content-Type": "application/x-www-form-urlencoded", Origin: base, ...headers },
    body: new URLSearchParams(values) });
}
async function rawGet(headers) {
  return await new Promise((done, fail) => {
    const req = request(base, { headers }, (res) => { res.resume(); res.once("end", () => done(res.statusCode)); });
    req.once("error", fail); req.end();
  });
}
const passed = [];
try {
  let child = launch();
  const initial = await ready();
  let html = await initial.text();
  await startupPath(child, join(dataDir, "archive.json"));
  assert(html.includes("Keep the useful things."));
  assert(initial.headers.get("content-security-policy").includes("script-src 'none'"));
  assert.deepEqual(await readdir(runDir), ["project-archive.exe"]);
  passed.push("Isolated EXE serves HTML and prints its actual override archive path with spaces; system-only PATH, empty cache and no sidecar assets");
  const css = await fetch(`${base}/styles.css`);
  assert.equal(css.status, 200); assert((await css.text()).includes("--mint"));
  passed.push("Embedded stylesheet returns HTTP 200");
  assert.equal(await rawGet({ Host: "attacker.example" }), 403);
  assert.equal(await rawGet({ "Sec-Fetch-Site": "cross-site" }), 403);
  passed.push("Bad Host and cross-site request rejected");
  let fields = tokenAndRevision(html);
  const values = { ...fields, id: "", title: "Offline project", description: "Synthetic record", url: "https://example.com", tags: "local,archive" };
  assert.equal((await post(values, { Origin: "https://attacker.example" })).status, 403);
  assert.equal((await post({ ...values, token: "wrong" })).status, 403);
  assert.equal((await post(values, { Origin: "" })).status, 403);
  passed.push("Foreign/missing Origin and invalid form token rejected");
  assert.equal((await post(values)).status, 303);
  let data = JSON.parse(await readFile(join(dataDir, "archive.json"), "utf8"));
  const id = data.projects[0].id;
  assert.equal(data.revision, 1); assert.equal(data.projects[0].title, "Offline project");
  passed.push("Create writes versioned local JSON");
  html = await (await fetch(base)).text(); fields = tokenAndRevision(html);
  const raceTitles = ["Edited with local persistence", "Other writer"];
  const races = await Promise.all(raceTitles.map((title) => post({ ...values, ...fields, id, title })));
  assert.deepEqual(races.map((r) => r.status).sort(), [303, 409]);
  const winner = races.findIndex((r) => r.status === 303);
  const savedTitle = raceTitles[winner];
  const rejected = races.find((r) => r.status === 409);
  assert((await rejected.text()).includes(raceTitles[1 - winner]));
  passed.push("Concurrent same-revision updates produce one 303 and one 409 with draft retained");
  assert((await (await fetch(`${base}/?q=${encodeURIComponent(savedTitle)}&tag=local`)).text()).includes(savedTitle));
  const noResults = await (await fetch(`${base}/?q=not-present`)).text();
  assert(noResults.includes("No projects in this view."));
  passed.push("GET search and tag filter render match and empty states");
  html = await (await fetch(base)).text(); fields = tokenAndRevision(html);
  const invalid = await post({ ...values, ...fields, id, url: "javascript:alert(1)" });
  assert.equal(invalid.status, 400); assert((await invalid.text()).includes("Offline project"));
  assert.equal((await post({ ...values, ...fields, description: "x".repeat(66000) })).status, 413);
  passed.push("Invalid URL returns 400 with draft; excessive body returns 413");
  const second = launch(47833);
  await ready("http://127.0.0.1:47833", 503);
  await stop(second);
  passed.push("Second process using same archive is denied by the file lock");
  await stop(child);
  child = launch();
  html = await (await ready()).text();
  assert(html.includes(savedTitle));
  data = JSON.parse(await readFile(join(dataDir, "archive.json"), "utf8"));
  assert.equal(data.projects.length, 1); assert.equal(data.revision, 2);
  assert.deepEqual(data.projects[0].tags, ["local", "archive"]);
  passed.push("Saved edited record and tags survive a new process");
  assert.equal((await post({ ...values, revision: 2, id })).status, 403);
  passed.push("Previous-process form token rejected after restart");
  fields = tokenAndRevision(html);
  assert.equal((await post({ ...fields, id: "", title: "界".repeat(120), description: "界".repeat(2000),
    url: "https://example.com/" + "界".repeat(2020),
    tags: Array.from({ length: 10 }, (_, i) => String(i) + "界".repeat(31)).join(",") })).status, 303);
  passed.push("Near-limit Unicode form fields fit the bounded 64 KiB encoded request");
  await stop(child);
  const corruptDir = join(root, "corrupt"); await mkdir(corruptDir);
  await writeFile(join(corruptDir, "archive.json"), "{broken");
  child = launch(47832, { PROJECT_ARCHIVE_DATA_DIR: corruptDir });
  await ready(base, 503);
  assert.equal(await readFile(join(corruptDir, "archive.json"), "utf8"), "{broken");
  passed.push("Corrupt JSON fails closed with HTTP 503 and original bytes unchanged");
  await stop(child);
  assert.deepEqual(await readdir(cacheDir), []);
  const defaultBase = join(root, "default-localappdata");
  const defaultDataPath = join(defaultBase, "CriticalDeveloper", "ProjectArchive", "archive.json");
  child = launch(47833, { LOCALAPPDATA: defaultBase, PROJECT_ARCHIVE_DATA_DIR: undefined });
  const defaultUrl = "http://127.0.0.1:47833";
  const defaultHtml = await (await ready(defaultUrl)).text();
  await startupPath(child, defaultDataPath);
  const defaultFields = tokenAndRevision(defaultHtml);
  const defaultSave = await fetch(`${defaultUrl}/save`, { method: "POST", redirect: "manual",
    headers: { "Content-Type": "application/x-www-form-urlencoded", Origin: defaultUrl },
    body: new URLSearchParams({ ...values, ...defaultFields, title: "Default app-data path", id: "" }) });
  assert.equal(defaultSave.status, 303);
  assert.equal(JSON.parse(await readFile(defaultDataPath, "utf8")).projects[0].title, "Default app-data path");
  await stop(child);
  assert.deepEqual(await readdir(cacheDir), []);
  passed.push("Default LOCALAPPDATA startup path and saved file agree; DENO_DIR remains empty after all runs");
  console.log(JSON.stringify({ root, passed, total: passed.length, platform: process.platform, arch: process.arch,
    limitation: "System-only PATH is not a clean Windows VM. Wi-Fi was not disconnected; no real network-outage test was executed." }, null, 2));
} finally { await Promise.all([...children].map(stop)); }
README.md

Setup, limits, backup and recovery notes

167 lines · MarkdownOpen fileDownload
# Project Archive — Fresh Windows executable lab

An original, single-user example accompanying the CriticalDeveloper article. All
records used in validation are synthetic. It is a personal index, not a file
attachment manager, multi-user database, or synchronized service.

## Run the packaged Windows x64 build

Extract `project-archive-windows-x64.zip`, then run `project-archive.exe` as your
ordinary Windows account. Deno is not required by the executable. Your existing
default browser is asked to open `http://127.0.0.1:47831/`. If opening it fails,
copy that URL yourself. The console stays open: Ctrl+C stops the server. Closing
the browser tab does not stop it. The build is unsigned; this lab has not tested
SmartScreen or enterprise allowlisting behavior.
The console prints the actual resolved `archive.json` path, including a custom
`PROJECT_ARCHIVE_DATA_DIR`. It also reports a nonzero asynchronous Windows opener
exit with the manual URL. A successful opener exit does not prove the browser
loaded the page.

PowerShell options:

```powershell
.\project-archive.exe --no-open
.\project-archive.exe --no-open --port=47835
```

The default data file is
`%LOCALAPPDATA%\CriticalDeveloper\ProjectArchive\archive.json`. To use a separate
archive, set an **absolute** directory before starting:

```powershell
$env:PROJECT_ARCHIVE_DATA_DIR = 'C:\Users\YOUR-NAME\Documents\ProjectArchive'
.\project-archive.exe
```

The app only binds to IPv4 loopback (`127.0.0.1`); it is not a LAN server. Search
and editing are server-rendered GET/POST forms and need no browser JavaScript.
An HTTP(S) project link may leave the local application and require the Internet.

## Build from source

Pinned tools: Deno **2.9.8**, Fresh **2.3.3**, Preact **10.29.1**. The included
`deno.lock` pins transitive resolution. Use a normal directory such as
`C:\dev\project-archive`, **without a hidden (`.`-prefixed) ancestor**. In this
lab Fresh 2.3.3's legacy Builder skipped static CSS while building inside a
`.codex` worktree. Compilation still succeeded, so verify the stylesheet too.

With Deno 2.9.8 installed on the **build machine**, from the source folder:

```powershell
deno task check
deno task test
deno task build
deno check launcher.ts
deno task compile
.\project-archive.exe --no-open
```

The legacy Fresh Builder is chosen deliberately here to pin an executed,
minimal build pipeline. `_fresh/compiled-entry.js` is generated by Fresh and
supports `PORT`/`HOSTNAME`. Our `launcher.ts` instead imports the generated
`_fresh/server.js` fetch handler so it can hard-code loopback and optionally open
the browser. Its compiler command still includes the complete `_fresh` output.
Do not hand-edit those generated files.

`deno task check` validates the application and tests before `_fresh` exists.
The launcher imports the generated server, so it is checked explicitly only
**after** the build; compilation also typechecks it. This order was executed from
a fresh extraction with no `_fresh` or `node_modules` directory. `runtime.ts`
shares the data-path resolver between the app and launch diagnostics and observes
the opener status; `runtime_test.ts` uses fakes without opening a browser.

Build/compile can need network access to fetch dependencies and Deno's target
runtime. The resulting executable includes the runtime and built assets. This
does not package Windows or a browser. Other targets require their own builds and
runtime tests; this artifact is Windows x64 only. Hashes of local rebuilds can
differ because the build contains generated identifiers.

## Verification

`deno task test` executes seven storage cases: replace/reopen, stale concurrent
writer, corrupt JSON preservation, failed replacement, input validation, UTF-8
archive byte cap, and revision exhaustion. It also executes six runtime tests for
default/override/invalid paths and successful/nonzero/rejected opener status.

With Node 22+ available on the **test machine**, after compiling:

```powershell
node verify-exe.mjs .\project-archive.exe
```

The harness copies only the EXE into a new temp folder, creates an empty
`DENO_DIR`, launches with system-only `PATH`, and performs 14 grouped checks.
They cover HTML/CSS serving, create/edit/search/tags, Host/Origin/token rejection,
request bounds including Unicode, concurrent stale revision, a second process
file lock, saved-data restart, old-token rejection, corrupt-file preservation,
and agreement between the printed default/override path and the saved file.
All harness child processes use `--no-open` and are stopped. Temp evidence folders
are retained for inspection; the harness never modifies a real archive.

Observed on this Windows x64 host: all seven storage tests, six runtime tests and all 14 executable
checks passed. The host had no `deno` command on PATH before a portable compiler
was downloaded outside the source tree. This is **not a clean Windows VM test**.
The automated harness uses `--no-open` and does not change host networking.

A separate user-operated acceptance session on **25 October 2026** exercised the
ordinary launch of the preceding build (`599E3881…0031C4`) from Windows ZIP
`567FAA1E…CC46B` on the same Windows PC. The user reported that default Chrome
156.0.8078.47 opened automatically, and browser create/edit/search/tag filtering
worked while the network connection was disconnected and after a process
restart. Automatic checks recorded HTML/CSS responses of 200, zero UP adapters
and no connection profiles during the disconnected stages, an unchanged saved
JSON hash at revision 2, distinct owned processes and final server cleanup.
Browser/version and interaction observations are user reports; the HTTP, file,
process and network snapshots are machine-collected evidence. The adapter
metadata does not establish a Wi-Fi-specific driver test, so the result is
described as a network-disconnected session. It is not a clean-VM test.

The companion `manual-acceptance-2026-10-25.json` preserves the sanitized record.
The current diagnostic follow-up observes the opener's asynchronous exit and
prints the same resolved path used by persistence. It changes the executable
hash; the original manual observation remains bound to its recorded EXE/ZIP and
is not relabeled as a run of this later build. The follow-up's clean build,
fake-only diagnostic tests and 14 executable checks are recorded separately.
No new default-browser or disconnected-network session is claimed for it.
The app has no remote UI assets/API calls, and its compiled network grant is
limited to `127.0.0.1`.

## Persistence and security boundaries

One file lock prevents two cooperating app processes from opening the same data
directory. An in-process queue and revision compare prevent stale browser tabs
from overwriting newer saves. A save writes and syncs a temporary sibling file,
then renames it over the prior JSON. The in-memory saved revision advances only
after replacement succeeds. This is not a power-loss durability guarantee or a
backup. Close the app before copying `archive.json` for backup or restore. An
invalid/corrupt file fails closed; it is not silently reset. Repair or restore a
copy before restarting. The JSON is not encrypted.

The schema permits 1,000 projects, ten tags each, and an 8 MiB serialized archive.
Forms are bounded to 64 KiB to accommodate URL-encoded Unicode. Validation,
conflict and persistence errors after the request/token checks retain the submitted
draft in the returned page. Rejections for an invalid origin/token, unsupported
content type or oversized request return a short error instead. After a conflict, copy your draft
and open the current saved record before retrying; the original stale revision
continues to be rejected.

Loopback binding is paired with exact numeric Host checking, rejection of
cross-site browser requests, exact Origin checking on writes, a random
per-process form token, output escaping, URL scheme validation, no CORS, no
client JavaScript and a restrictive CSP. These controls do not authenticate
other processes running as your Windows account. Do not expose this app through
a reverse proxy or port-forward it.

The compiled grants allow local file reads/writes, network only to loopback,
and environment reads for exactly `LOCALAPPDATA`, `PROJECT_ARCHIVE_DATA_DIR`,
`DENO_DEPLOYMENT_ID`, `GITHUB_SHA` and `CI_COMMIT_SHA`. The first two select the
data directory; Fresh's imported `@fresh/build-id` reads the latter three during
module initialization. A configurable directory does not require access to all
environment variables. The compile task permits process launch only for
`C:\Windows\System32\rundll32.exe`. Opening the default browser uses that Windows
binary with `url.dll,FileProtocolHandler` and the fixed local URL. Deno cannot
restrict subprocess arguments; once that process is launched it is outside the
Deno sandbox. `--no-open` skips launching it; a stricter distribution can remove
the opener code and `--allow-run` entirely. A Windows installation elsewhere may
need manual opening. No auto-update, installer, tray integration, encryption,
signing, cloud sync, attachment handling, or broad OS compatibility is claimed.

Keep the dependency lockfile beside deno.json, and the stylesheet in static/:

Source files

1 file
styles.css

Local responsive stylesheet

744 lines · CSSOpen fileDownload
:root {
  font-family: Inter,"Segoe UI",Arial,sans-serif;
  color: #f0f2ed;
  background: #090d10;
  font-synthesis: none;
  color-scheme: dark;
  --muted: #a4b4bc;
  --mint: #8ae6d5;
  --line: #2a363c;
}
* {
  box-sizing: border-box;
}
html {
  scroll-behavior: smooth;
}
body {
  margin: 0;
}
a {
  color: inherit;
  text-underline-offset: 4px;
}
button,
input,
textarea {
  font: inherit;
}
button,
a,
input,
textarea {
  -webkit-tap-highlight-color: transparent;
}
button {
  cursor: pointer;
}
a:focus-visible,
button:focus-visible,
input:focus-visible,
textarea:focus-visible {
  outline: 2px solid var(--mint);
  outline-offset: 4px;
}
a:hover {
  color: var(--mint);
}
button:hover {
  filter: brightness(1.12);
}
.skip-link {
  position: absolute;
  top: -100px;
  left: 24px;
  padding: 12px;
  background: var(--mint);
  color: #102522;
  z-index: 2;
}
.skip-link:focus {
  top: 12px;
}
.shell {
  max-width: 1440px;
  margin: auto;
  padding: 0 64px;
}
.masthead {
  height: 102px;
  border-bottom: 1px solid var(--line);
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 24px;
}
.brand {
  display: flex;
  align-items: center;
  gap: 14px;
  text-decoration: none;
  font-size: 13px;
  font-weight: 700;
  letter-spacing: .13em;
}
.brand svg {
  stroke: var(--mint);
  fill: none;
  stroke-width: 1.4;
}
.local-badge {
  font-family: Consolas,"Courier New",monospace;
  font-size: 11px;
  letter-spacing: .13em;
  color: var(--muted);
  display: flex;
  align-items: center;
  gap: 9px;
}
.local-badge > span {
  width: 6px;
  height: 6px;
  border-radius: 50%;
  background: var(--mint);
  box-shadow: 0 0 13px #8ae6d533;
}
.intro {
  padding: 75px 0 66px;
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  gap: 36px;
}
.eyebrow {
  font-family: Consolas,"Courier New",monospace;
  color: var(--mint);
  font-size: 10px;
  font-weight: 500;
  letter-spacing: .17em;
  margin: 0 0 22px;
}
h1,
h2,
h3,
p {
  margin-top: 0;
}
h1 {
  font-size: clamp(36px,4.1vw,58px);
  letter-spacing: -.055em;
  font-weight: 500;
  line-height: 1.1;
  margin-bottom: 22px;
}
.intro__text {
  max-width: 575px;
  color: var(--muted);
  font-size: 15px;
  line-height: 1.8;
  margin-bottom: 0;
}
.archive-count {
  display: flex;
  align-items: center;
  gap: 18px;
  padding-bottom: 7px;
}
.archive-count > span:first-child {
  font-size: 67px;
  line-height: 1;
  font-weight: 300;
  letter-spacing: -.07em;
  color: var(--mint);
}
.archive-count > span:last-child {
  font-family: Consolas,"Courier New",monospace;
  color: var(--muted);
  font-size: 10px;
  line-height: 1.7;
  letter-spacing: .12em;
}
.workspace {
  display: grid;
  grid-template-columns: minmax(0,1fr) 348px;
  gap: 56px;
  padding-bottom: 76px;
}
.section-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 0 24px;
  gap: 16px;
}
.section-title h2 {
  font-size: 18px;
  font-weight: 500;
  letter-spacing: -.02em;
  margin: 0;
}
.section-title > span {
  color: var(--muted);
  font: 10px Consolas,"Courier New",monospace;
  letter-spacing: .12em;
}
.search > label {
  position: absolute;
  width: 1px;
  height: 1px;
  overflow: hidden;
  clip-path: inset(50%);
  white-space: nowrap;
}
.search__field {
  border: 1px solid var(--line);
  background: #10171b;
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px 8px 8px 17px;
}
.search__field svg {
  fill: none;
  stroke: #8b9da7;
  stroke-width: 1.5;
  flex-shrink: 0;
}
.search__field input {
  min-width: 0;
  width: 100%;
  border: 0;
  background: transparent;
  padding: 11px 0;
  font-size: 13px;
  outline-offset: 1px;
}
.search__field input::placeholder {
  color: #8a9ca6;
}
.search__field button {
  background: #263a3b;
  color: #d3eee7;
  border: 1px solid #3c5956;
  padding: 11px 15px;
  font-size: 11px;
  font-weight: 600;
}
.tag-filter {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin: 19px 0 26px;
}
.tag-filter__item {
  font-size: 10px;
  line-height: 1.4;
  text-decoration: none;
  color: #a4b4bc;
  border: 1px solid transparent;
  padding: 7px 10px;
  overflow-wrap: anywhere;
}
.tag-filter__item.is-active {
  color: #b8f0e3;
  background: #18332f;
  border-color: #32534c;
}
.projects {
  padding: 0;
  list-style: none;
  margin: 26px 0 0;
}
.project {
  padding: 27px 0 28px;
  border-top: 1px solid var(--line);
  display: flex;
  gap: 23px;
}
.project.is-editing {
  border-top-color: var(--mint);
}
.project__number {
  color: #758c96;
  font: 10px Consolas,"Courier New",monospace;
  padding-top: 6px;
  min-width: 16px;
}
.project__body {
  min-width: 0;
  flex: 1;
}
.project__heading {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  gap: 20px;
}
.project h3 {
  font-size: 22px;
  letter-spacing: -.035em;
  font-weight: 500;
  line-height: 1.3;
  margin: 0 0 12px;
  overflow-wrap: anywhere;
}
.edit-link {
  font-size: 10px;
  text-decoration: none;
  color: var(--muted);
  white-space: nowrap;
}
.edit-link span {
  margin-left: 7px;
}
.project__description {
  font-size: 13px;
  line-height: 1.85;
  color: #afbdc4;
  white-space: pre-wrap;
  overflow-wrap: anywhere;
  margin-bottom: 19px;
}
.project__meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 14px;
  flex-wrap: wrap;
}
.project__tags {
  display: flex;
  flex-wrap: wrap;
  gap: 7px;
  min-width: 0;
}
.project__tags a {
  padding: 4px 8px;
  color: #b4c7ce;
  background: #152127;
  font: 10px Consolas,"Courier New",monospace;
  text-decoration: none;
  overflow-wrap: anywhere;
}
.project__meta time {
  font: 10px Consolas,"Courier New",monospace;
  white-space: nowrap;
  color: #8ba0aa;
}
.untagged {
  font: 9px Consolas,"Courier New",monospace;
  letter-spacing: .12em;
  color: #758c96;
  padding: 4px 0;
}
.project__url {
  display: flex;
  align-items: center;
  gap: 12px;
  width: fit-content;
  max-width: 100%;
  font-size: 11px;
  line-height: 1.7;
  text-decoration: none;
  color: #8ca9ab;
  margin-top: 16px;
  overflow-wrap: anywhere;
  word-break: break-word;
}
.project__url span {
  color: var(--mint);
  flex-shrink: 0;
}
.editor {
  background: #121c20;
  border: 1px solid #2a3b40;
  padding: 27px 25px;
  align-self: start;
  scroll-margin-top: 20px;
}
.editor__topline {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.editor__topline .eyebrow {
  margin-bottom: 20px;
  font-size: 9px;
}
.editor__topline > span:last-child {
  font-size: 24px;
  line-height: 1;
  color: #5d7b7b;
  align-self: flex-start;
  margin-top: -5px;
}
.editor h2 {
  font-size: 27px;
  letter-spacing: -.045em;
  font-weight: 500;
  line-height: 1.2;
  margin-bottom: 12px;
}
.editor__intro {
  font-size: 12px;
  color: var(--muted);
  line-height: 1.8;
  margin-bottom: 27px;
}
.editor-form {
  display: flex;
  flex-direction: column;
}
.editor-form label {
  font-size: 11px;
  margin: 0 0 9px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
}
.editor-form label > span {
  font: 8px Consolas,"Courier New",monospace;
  letter-spacing: .1em;
  color: #8da1aa;
}
.editor-form input:not([type=hidden]),
.editor-form textarea {
  width: 100%;
  min-width: 0;
  background: #0b1317;
  color: #e4edea;
  border: 1px solid #30434b;
  border-radius: 0;
  padding: 12px 11px;
  font-size: 12px;
  line-height: 1.6;
  margin-bottom: 22px;
}
.editor-form textarea {
  resize: vertical;
  min-height: 111px;
}
.editor-form input::placeholder,
.editor-form textarea::placeholder {
  color: #8c9fa8;
  opacity: 1;
}
.editor-form input#tags {
  margin-bottom: 9px;
}
.field-hint {
  font-size: 10px;
  line-height: 1.7;
  color: #9cafb7;
  margin-bottom: 24px;
}
.save-button {
  background: var(--mint);
  color: #0c2622;
  border: 1px solid var(--mint);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 14px 15px;
  font-size: 12px;
  font-weight: 650;
  text-align: left;
}
.save-button > span {
  font-size: 17px;
  font-weight: 400;
}
.cancel-link {
  align-self: center;
  margin-top: 16px;
  font-size: 11px;
  color: #a6bac2;
}
.storage-note {
  border-top: 1px solid #2a3b40;
  margin-top: 26px;
  padding-top: 19px;
  display: flex;
  gap: 10px;
  align-items: flex-start;
}
.storage-note__dot {
  width: 5px;
  height: 5px;
  min-width: 5px;
  border-radius: 50%;
  background: var(--mint);
  margin-top: 7px;
}
.storage-note p {
  font-size: 10px;
  line-height: 1.9;
  color: #9db0b9;
  margin: 0;
}
.storage-note strong {
  font-weight: 500;
  color: #c8d7d9;
}
.notice {
  font-size: 12px;
  line-height: 1.7;
  border: 1px solid;
  padding: 12px;
  margin: 0 0 22px;
  overflow-wrap: anywhere;
}
.notice--success {
  color: #b7f5df;
  background: #183b30;
  border-color: #37634e;
}
.notice--error {
  color: #f4c3b6;
  background: #392923;
  border-color: #795347;
}
.empty-state {
  border: 1px solid var(--line);
  padding: 54px 28px;
  text-align: center;
  margin-top: 26px;
}
.empty-state__mark {
  display: block;
  font: 25px Consolas,"Courier New",monospace;
  letter-spacing: .2em;
  color: #6ca89d;
  margin-bottom: 24px;
}
.empty-state h3 {
  font-size: 21px;
  letter-spacing: -.035em;
  font-weight: 500;
  margin-bottom: 13px;
}
.empty-state p {
  font-size: 13px;
  line-height: 1.8;
  color: var(--muted);
  max-width: 340px;
  margin: 0 auto 18px;
}
.empty-state a {
  font-size: 12px;
  color: var(--mint);
}
.footer {
  display: flex;
  justify-content: space-between;
  gap: 18px;
  border-top: 1px solid var(--line);
  padding: 25px 0 34px;
  font: 9px Consolas,"Courier New",monospace;
  letter-spacing: .09em;
  color: #8b9fa9;
}
.collection {
  min-width: 0;
  scroll-margin-top: 20px;
}
@media (min-width:1500px) {
  .shell {
    padding: 0 72px;
  }
  .workspace {
    gap: 72px;
    grid-template-columns: minmax(0,1fr) 360px;
  }
  .intro {
    padding-top: 90px;
    padding-bottom: 76px;
  }
}
@media (max-width:1060px) {
  .shell {
    padding: 0 34px;
  }
  .workspace {
    grid-template-columns: minmax(0,1fr) 320px;
    gap: 30px;
  }
  .editor {
    padding: 25px 21px;
  }
  .intro {
    padding-top: 56px;
    padding-bottom: 52px;
  }
  .archive-count {
    gap: 12px;
  }
  .archive-count > span:first-child {
    font-size: 52px;
  }
  .intro__text {
    max-width: 470px;
  }
  .project {
    gap: 16px;
  }
  .project h3 {
    font-size: 20px;
  }
}
@media (max-width:820px) {
  .workspace {
    grid-template-columns: 1fr;
    gap: 42px;
  }
  .editor {
    max-width: none;
    padding: 27px;
  }
  .intro {
    align-items: center;
    gap: 20px;
  }
  .archive-count {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  .archive-count > span:last-child {
    font-size: 9px;
  }
  .editor-form textarea {
    min-height: 120px;
  }
  .editor-form input:not([type=hidden]),
  .editor-form textarea {
    font-size: 16px;
  }
  .editor__intro {
    font-size: 13px;
  }
  .storage-note p {
    font-size: 11px;
  }
  .workspace {
    padding-bottom: 48px;
  }
}
@media (max-width:520px) {
  .shell {
    padding: 0 20px;
  }
  .masthead {
    height: 80px;
    gap: 14px;
  }
  .brand {
    font-size: 10px;
    letter-spacing: .09em;
    gap: 9px;
  }
  .brand svg {
    width: 26px;
    height: 26px;
  }
  .local-badge {
    font-size: 8px;
    letter-spacing: .04em;
    gap: 6px;
    white-space: nowrap;
  }
  .local-badge > span {
    width: 4px;
    height: 4px;
  }
  .intro {
    padding: 43px 0 37px;
    display: block;
  }
  .intro .eyebrow {
    font-size: 9px;
    margin-bottom: 18px;
  }
  h1 {
    font-size: 37px;
    max-width: 320px;
  }
  .intro__text {
    font-size: 13px;
    line-height: 1.85;
  }
  .archive-count {
    flex-direction: row;
    align-items: center;
    gap: 12px;
    margin-top: 24px;
    padding: 0;
  }
  .archive-count > span:first-child {
    font-size: 36px;
    letter-spacing: -.05em;
  }
  .archive-count > span:last-child {
    font-size: 8px;
    line-height: 1.5;
  }
  .archive-count br {
    display: none;
  }
  .section-title {
    margin-bottom: 19px;
  }
  .section-title h2 {
    font-size: 17px;
  }
  .search__field {
    gap: 9px;
    padding-left: 12px;
  }
  .search__field input {
    font-size: 16px;
  }
  .search__field button {
    padding: 11px 12px;
  }
  .project {
    gap: 11px;
    padding: 24px 0;
  }
  .project__heading {
    gap: 12px;
  }
  .project h3 {
    font-size: 21px;
  }
  .project__number {
    font-size: 9px;
    padding-top: 7px;
  }
  .project__description {
    font-size: 12px;
  }
  .project__url {
    font-size: 10px;
  }
  .editor {
    padding: 24px 20px;
  }
  .editor h2 {
    font-size: 27px;
  }
  .footer {
    flex-direction: column;
    gap: 12px;
    font-size: 8px;
  }
  .empty-state {
    padding: 40px 22px;
  }
}
@media (prefers-reduced-motion:reduce) {
  html {
    scroll-behavior: auto;
  }
}

When this distribution model fits

This is useful for a personal catalogue, report explorer or small internal utility that needs local file access and a familiar web interface. A native shell better suits a product built around tray behavior or a controlled desktop window; a hosted application better suits shared access and centralized updates.

The preview is unsigned. Windows may warn about an unfamiliar executable, and signing does not guarantee that reputation warnings disappear. An organizational release still needs its usual signing, distribution and update process. Microsoft SmartScreen, SignTool.

The concrete finding is that a compiled Fresh application served its embedded interface and preserved accepted edits across a new process. The missing stylesheet showed why compilation alone was insufficient; the rejected form showed why HTTP-only checks were insufficient. For this local-tool pattern, packaging works when the delivered binary, browser workflow and external data store are tested together.