Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
8 changes: 8 additions & 0 deletions apps/web/.dev.vars.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# The Worker's secrets for `pnpm dev:worker` / `pnpm preview` (wrangler dev
# reads .dev.vars). Copy to .dev.vars. Deployed, the service-role key is the
# Supabase root's output and the deploy stores it; never commit it.
SUPABASE_SERVICE_ROLE_KEY=
# Optional: Postmark inbound email (worker/functions/postmark).
POSTMARK_WEBHOOK_USER=
POSTMARK_WEBHOOK_PASSWORD=
POSTMARK_WEBHOOK_AUTHORIZED_IPS=
7 changes: 7 additions & 0 deletions apps/web/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
SKIP_PREFLIGHT_CHECK=true

VITE_SUPABASE_URL=http://127.0.0.1:54321
VITE_SB_PUBLISHABLE_KEY=sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH
VITE_IS_DEMO=false

VITE_ATTACHMENTS_BUCKET=attachments
5 changes: 5 additions & 0 deletions apps/web/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# local state wrangler and the PWA plugin write
.wrangler/
dev-dist/
.dev.vars
.env.local
238 changes: 238 additions & 0 deletions apps/web/CHANGELOG.md

Large diffs are not rendered by default.

21 changes: 21 additions & 0 deletions apps/web/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2024-present, Francois Zaninotto, Marmelab

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
54 changes: 54 additions & 0 deletions apps/web/build-env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// What a production build inlines: the Supabase project the browser talks to,
// read from the `vars` of the wrangler.jsonc beside this file — committed as
// the fixture render of wrangler.template.jsonc, and re-rendered from the
// environment's wiring document by every Orun lane before it builds
// (component.yaml) — so the bundle and the Worker get the same URL and key
// from one place. A VITE_* value already in the environment (or .env.local)
// wins, as it does upstream.
import fs from "node:fs";

export function stripJsonc(text: string): string {
let out = "";
for (let i = 0; i < text.length; i++) {
const c = text[i];
if (c === '"') {
let j = i + 1;
while (j < text.length && text[j] !== '"') j += text[j] === "\\" ? 2 : 1;
out += text.slice(i, j + 1);
i = j;
} else if (c === "/" && text[i + 1] === "/") {
while (i < text.length && text[i] !== "\n") i++;
out += "\n";
} else if (c === "/" && text[i + 1] === "*") {
i = text.indexOf("*/", i + 2);
if (i < 0) break;
i++;
} else {
out += c;
}
}
return out.replace(/,(\s*[}\]])/g, "$1");
}

const FROM_WRANGLER = {
VITE_SUPABASE_URL: "SUPABASE_URL",
VITE_SB_PUBLISHABLE_KEY: "SB_PUBLISHABLE_KEY",
} as const;

export function supabaseBuildEnv(
env: Record<string, string | undefined>,
wranglerConfig: string,
): Record<string, string> {
let vars: Record<string, unknown> = {};
try {
vars = JSON.parse(stripJsonc(fs.readFileSync(wranglerConfig, "utf8"))).vars ?? {};
} catch {
vars = {};
}
const out: Record<string, string> = {};
for (const [key, from] of Object.entries(FROM_WRANGLER)) {
const value = env[key] || vars[from];
if (typeof value === "string" && value.length > 0) out[key] = value;
}
return out;
}
70 changes: 70 additions & 0 deletions apps/web/component.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
apiVersion: sourceplane.io/v1
kind: Component

metadata:
name: web
description: The CRM — Marmelab's Atomic CRM single-page app as the Static Assets of a Cloudflare Worker whose own routes are the ported Supabase edge functions, per environment

spec:
type: cloudflare-workers-assets-turbo
lifecycle: production
owner: platform
docs:
overview: docs/overview.md
pages:
- { path: docs/architecture.md, role: architecture, title: Architecture }
- { path: docs/runbook.md, role: runbook, title: Runbook }
domain: product
path: apps/web
lane: isolated
change:
inputs:
- pnpm-lock.yaml
subscribe:
environments:
- name: dev
profile: verify
- name: stage
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
- name: prod
profile: verify
profileRules:
- profile: deploy
when:
triggerRef: github-push-main
parameters:
nodeVersion: "22"
pnpmVersion: "10.12.1"

workspaceDir: ../..
appDir: .

turboFilter: "@app/web"
wranglerConfig: wrangler.jsonc

# wrangler bundles the Worker from its source on deploy; the build is the
# single-page app.
workerEntrypoint: worker/index.ts
assetsDir: dist

workerName: atomic-crm-web
environmentAwareWorkerName: true

workersDevSubdomain: your-workers-subdomain

installCommand: pnpm install --frozen-lockfile
# Render wrangler.jsonc for this environment (dev from the fixture), then
# build the app — which inlines the project's URL and publishable key from
# that render (vite.config.ts) — then hand the Worker its secrets.
buildCommand: node ../../tooling/wire/live.mjs --template wrangler.template.jsonc --out wrangler.jsonc --components supabase,cloudflare-hyperdrive --env "${ORUN_ENVIRONMENT}" --fixture wiring.fixture.json --fixture-envs dev && pnpm exec turbo run build --filter=@app/web && node ../../tooling/wire/worker-secrets.mjs --secret SUPABASE_SERVICE_ROLE_KEY --secret POSTMARK_WEBHOOK_USER --secret POSTMARK_WEBHOOK_PASSWORD --secret POSTMARK_WEBHOOK_AUTHORIZED_IPS --worker "atomic-crm-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc

smokeCommand: "html=$(curl -sfL \"${DEPLOYED_URL}/\") && echo \"${html}\" | grep -q '<div id=\"root\">' && health=$(curl -sf \"${DEPLOYED_URL}/api/health\") && echo \"${health}\" | grep -q '\"ok\":true' && test \"$(curl -s -o /dev/null -w '%{http_code}' -X PATCH \"${DEPLOYED_URL}/functions/v1/update_password\")\" = 401"
labels:
team: platform
layer: delivery
surface: web
runtime: cloudflare
21 changes: 21 additions & 0 deletions apps/web/components.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "",
"css": "src/index.css",
"baseColor": "neutral",
"cssVariables": true,
"prefix": ""
},
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
"ui": "@/components/ui",
"lib": "@/lib",
"hooks": "@/hooks"
},
"iconLibrary": "lucide"
}
16 changes: 16 additions & 0 deletions apps/web/demo/App.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { CRM } from "@/components/crm/root/CRM";
import {
authProvider,
dataProvider,
} from "@/components/crm/providers/fakerest";
import { memoryStore } from "ra-core";

const App = () => (
<CRM
dataProvider={dataProvider}
authProvider={authProvider}
store={memoryStore()}
/>
);

export default App;
10 changes: 10 additions & 0 deletions apps/web/demo/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "../src/index.css";
import App from "./App.tsx";

createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>,
);
31 changes: 31 additions & 0 deletions apps/web/docs/architecture.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# web — architecture

One Worker per environment, `atomic-crm-web-<env>`.

```
browser ──▶ Static Assets (dist/: the React-Admin SPA, hash-routed)
│
├──▶ Supabase project: Auth, PostgREST (the data provider), Storage
│
└──▶ /functions/v1/<name> ──▶ this Worker (worker/index.ts)
├─ users, update_password, delete_note_attachments, postmark
│ └─▶ Supabase admin API (service-role key, a Worker secret)
└─ merge_contacts, mcp
└─▶ Postgres through Hyperdrive (HYPERDRIVE binding)
```

- **The SPA** is upstream's (`src/`), built by Vite. A build inlines the
project's URL and publishable key from the `vars` of the rendered
`wrangler.jsonc` (`build-env.ts`), so the bundle and the Worker always
name the same project.
- **The edge functions** are upstream's `supabase/functions`, in
`worker/functions`, nearly verbatim: `Deno.env.get` and `Deno.serve` come
from a two-function shim (`worker/functions/_shared/deno.ts`) and the
`jsr:`/`npm:` imports are npm packages. The Supabase client's `fetch` sends
`/functions/v1/*` to the page's own origin, so `supabase.functions.invoke`
reaches them unchanged.
- **Postgres** is reached per request (Kysely over `pg` for
`merge_contacts`, one client per query for the MCP server): a Worker may not
reuse a socket another request opened, and Hyperdrive is the pool.
- `run_worker_first` sends only `/functions/*` and `/api/*` to the Worker;
every other path is a file, or `index.html`.
20 changes: 20 additions & 0 deletions apps/web/docs/overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# web

The CRM — Marmelab's Atomic CRM single-page app as the Static Assets of a Cloudflare Worker whose own routes are the ported Supabase edge functions, per environment

A Cloudflare Worker with Static Assets, deployed per environment by its CI lane.

| | |
| ------------ | ------------------------------------------------------------------------------------------------------------------ |
| Type | `cloudflare-workers-assets-turbo` |
| Source | `apps/web` |
| Package | `@app/web` |
| Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` |

## Depends on

- (none)

## Depended on by

- (none)
15 changes: 15 additions & 0 deletions apps/web/docs/runbook.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# web — runbook

| Symptom | Check | Fix |
|---|---|---|
| The deploy's smoke test fails on `/` | `curl -s https://<worker>/ \| grep 'id="root"'` | the build did not produce `dist/`: read the lane's `build-app` step |
| `/api/health` says `"supabase": false` | the rendered `wrangler.jsonc` `vars` | the Supabase root has not applied for this environment, or its `WIRING_SUPABASE` secret is missing: re-run the `supabase` lane |
| `/api/health` says `"admin": false`; inviting a user or resetting a password fails | `wrangler secret list --name atomic-crm-web-<env>` | the deploy found no `SUPABASE_SERVICE_ROLE_KEY`: re-run the `supabase` lane, then this one |
| `/api/health` says `"database": false`; merging contacts fails | the `hyperdrive` block of the rendered config | re-run `cloudflare-hyperdrive`, then this lane |
| Sign-in works but every list is empty | the browser console: PostgREST 401/42501 | the schema is not applied: re-run `db-migrate` |
| `/functions/v1/postmark` answers 503 | — | inbound email is optional: store `POSTMARK_WEBHOOK_USER`, `POSTMARK_WEBHOOK_PASSWORD` and `POSTMARK_WEBHOOK_AUTHORIZED_IPS` as Orun secrets and redeploy |

Local: `pnpm --filter @app/web preview` builds the app and serves it with the
Worker under `wrangler dev` on :8787 (secrets from `.dev.vars`, see
`.dev.vars.example`); `pnpm --filter @app/web dev:demo` runs upstream's
FakeRest demo with no Supabase at all.
74 changes: 74 additions & 0 deletions apps/web/eslint.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// For more info, see https://github.com/storybookjs/eslint-plugin-storybook#configuration-flat-config-format
import js from "@eslint/js";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import globals from "globals";
import tseslint from "typescript-eslint";

export default tseslint.config(
{ ignores: ["dist", "dev-dist", ".wrangler", "node_modules"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx,mjs}"],
ignores: ["**/node_modules/**", "**/dist/**", "**/.astro/**"],
languageOptions: {
ecmaVersion: 2020,
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
"@typescript-eslint/no-unused-vars": [
"error",
{
varsIgnorePattern: "^_",
argsIgnorePattern: "^_",
},
],
"no-console": ["error", { allow: ["warn", "error"] }],
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/consistent-type-imports": "warn",
},
},
{
files: ["**/*.{ts,tsx}"],
languageOptions: {
globals: globals.browser,
},
},
{
// Node scripts and Claude Code hooks. TypeScript files rely on the
// compiler for undefined identifiers; plain JS needs no-undef back on.
files: ["**/*.mjs"],
languageOptions: {
globals: globals.node,
},
rules: {
"no-undef": "error",
},
},
{
files: [
"src/components/admin/*.{ts,tsx}",
"src/hooks/*.{ts,tsx}",
"src/lib/*.{ts,tsx}",
],
rules: {
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/consistent-type-imports": "off",
},
},
{
files: ["src/components/ui/*.{ts,tsx}"],
rules: {
"react-refresh/only-export-components": "off",
"@typescript-eslint/consistent-type-imports": "off",
},
},
);
Loading
Loading