create-marcapony-app 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-marcapony-app",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Scaffold a Marcapony app \u2014 a Worker backed by the Marcapony API, ready for `marcapony app link` and `marcapony app deploy`",
5
5
  "type": "module",
6
6
  "license": "SEE LICENSE IN LICENSE.md",
@@ -14,7 +14,7 @@
14
14
  },
15
15
  "dependencies": {
16
16
  "hono": "^4.13.0",
17
- "marcapony-sdk": "^0.15.0",
17
+ "marcapony-sdk": "^0.16.0",
18
18
  "react": "^19.3.0",
19
19
  "react-dom": "^19.3.0"
20
20
  },
@@ -24,7 +24,7 @@
24
24
  "@types/react-dom": "^19.3.0",
25
25
  "@vitejs/plugin-react": "^5.2.0",
26
26
  "esbuild": "^0.28.0",
27
- "marcapony": "^0.17.0",
27
+ "marcapony": "^0.18.0",
28
28
  "typescript": "^5.9.0",
29
29
  "vite": "^7.3.0"
30
30
  }
@@ -1,6 +1,10 @@
1
1
  /**
2
2
  * Calls this app's own `/api` routes. The interface never talks to Marcapony
3
3
  * directly: the app key lives on the server and must stay there.
4
+ *
5
+ * Pass the path without a leading slash (`api('api/products')`). The app is
6
+ * served on its own host and also under a site's `/_apps/<slug>/` address, and
7
+ * only a relative path reaches this app's server in both.
4
8
  */
5
9
  export class ApiError extends Error {
6
10
  readonly status: number
@@ -63,7 +63,7 @@ export function applySiteTheme(
63
63
 
64
64
  export function followSiteTheme(): void {
65
65
  if (window.parent !== window) return
66
- api<SiteTheme | null>('/api/site-theme')
66
+ api<SiteTheme | null>('api/site-theme')
67
67
  .then((theme) => {
68
68
  if (theme) applySiteTheme(theme)
69
69
  })
@@ -3,6 +3,11 @@ import react from '@vitejs/plugin-react'
3
3
 
4
4
  export default defineConfig({
5
5
  plugins: [react()],
6
+ // Relative asset URLs, so the app works on its own host and under a site's
7
+ // `/_apps/<slug>/` address. Call your own server with `api/...`, not `/api/...`.
8
+ // This holds for pages at the app root: with a client router use hash routing
9
+ // or flat paths, because a nested path breaks `./assets/...` under the mount.
10
+ base: './',
6
11
  build: {
7
12
  // `marcapony.json` uploads this directory as the app's static assets.
8
13
  outDir: 'dist/client',
@@ -25,6 +25,13 @@ On the site, the app takes the website's colours, radius and font:
25
25
  variables `src/ui/styles.css` uses. Inside the customer portal the portal's
26
26
  own theme (`src/ui/portal-theme.ts`) applies instead.
27
27
 
28
+ The interface calls its own routes with relative paths (`api/products`, not
29
+ `/api/products`), and `vite.config.ts` sets `base: './'`. The app is served on
30
+ its own host and under the site's `/_apps/<slug>/` address, and only relative
31
+ URLs work in both. Keep new calls and asset references relative. That holds for
32
+ pages at the app root: an app that adds a client router should use hash routing
33
+ or keep flat paths, because a nested path breaks `./assets/...` under the mount.
34
+
28
35
  ## What to change first
29
36
 
30
37
  1. Replace the products example in `src/server/index.ts` and `src/ui/App.tsx`
@@ -22,7 +22,7 @@ export function App() {
22
22
  const [error, setError] = useState<string | null>(null)
23
23
 
24
24
  useEffect(() => {
25
- fetch('/api/products')
25
+ fetch('api/products')
26
26
  .then(async (res) => {
27
27
  const body = (await res.json()) as { products?: Product[]; error?: string }
28
28
  if (!res.ok) throw new Error(body.error ?? `Request failed with status ${res.status}`)
@@ -28,13 +28,13 @@ export function App() {
28
28
  const [notice, setNotice] = useState<string | null>(null)
29
29
 
30
30
  const loadReservations = useCallback(() => {
31
- api<{ reservations: Reservation[] }>('/api/reservations')
31
+ api<{ reservations: Reservation[] }>('api/reservations')
32
32
  .then((body) => setReservations(body.reservations))
33
33
  .catch((err: unknown) => setError(errorMessage(err)))
34
34
  }, [])
35
35
 
36
36
  useEffect(() => {
37
- api<Me>('/api/me')
37
+ api<Me>('api/me')
38
38
  .then((body) => {
39
39
  setMe(body)
40
40
  if (body.canView) loadReservations()
@@ -67,7 +67,7 @@ export function App() {
67
67
  setError(null)
68
68
  try {
69
69
  const body = await api<{ simulated: boolean }>(
70
- `/api/reservations/${encodeURIComponent(id)}/cancel`,
70
+ `api/reservations/${encodeURIComponent(id)}/cancel`,
71
71
  { method: 'POST' },
72
72
  )
73
73
  setNotice(
@@ -139,7 +139,7 @@ function BookingForm({ onBooked }: { onBooked: () => void }) {
139
139
  setError(null)
140
140
  setMessage(null)
141
141
  try {
142
- const body = await api<{ simulated: boolean }>('/api/reservations', {
142
+ const body = await api<{ simulated: boolean }>('api/reservations', {
143
143
  body: { requestId, date, time, notes },
144
144
  })
145
145
  setMessage(
@@ -125,7 +125,7 @@ export function App() {
125
125
  const widget = useRef<HTMLDivElement>(null)
126
126
 
127
127
  useEffect(() => {
128
- api<Character>('/api/character')
128
+ api<Character>('api/character')
129
129
  .then(setCharacter)
130
130
  .catch((err: unknown) => setError(errorMessage(err)))
131
131
  }, [])
@@ -134,7 +134,7 @@ export function App() {
134
134
  sessionStorage.setItem(STORAGE_KEY, JSON.stringify(saved))
135
135
  }, [saved])
136
136
 
137
- const base = character ? `/api/chat/${encodeURIComponent(character.slug)}` : ''
137
+ const base = character ? `api/chat/${encodeURIComponent(character.slug)}` : ''
138
138
 
139
139
  /** The saved conversation, or a new one when there is none or `fresh` is set. */
140
140
  async function conversationId(fresh = false): Promise<string> {
@@ -24,6 +24,7 @@ address (the one `bun run deploy` prints).
24
24
  | Route | What it does |
25
25
  | ---------------- | ---------------------------------------------------------------- |
26
26
  | `GET /api/health` | Answers `{ "ok": true }` |
27
+ | `GET /api/me` | `{ "signedIn": true, "email" }` or `{ "signedIn": false }` |
27
28
  | `GET /api/score` | The signed-in customer's best score, or `{ "best": null }` |
28
29
  | `PUT /api/score` | Saves `{ score }` when it beats the best; 401 if nobody is signed in |
29
30
 
@@ -44,6 +45,17 @@ The server never sees a password, a code or the session. It asks
44
45
  `identityOf(...)` who the request is from, and the platform limits
45
46
  `me.records` to that customer.
46
47
 
48
+ ## Running under the site mount
49
+
50
+ The app is also served under the business's site at `/_apps/<slug>/`. There
51
+ only the hosted sign-in page exists: the e-mail code routes and sign-out are
52
+ not served, so the game offers the "Sign in" link, which comes back to the page
53
+ the visitor was on (the default `returnTo`), and learns who signed in from
54
+ `GET /api/me`. Signing out is not offered under the site mount; a visitor signs
55
+ out on the app's own address. A visitor the business has not given the app to
56
+ looks signed out there: the server gets no identity for them, so each sign-in
57
+ round trip ends at the same prompt.
58
+
47
59
  ## What to change first
48
60
 
49
61
  1. The game in `src/ui/App.tsx`. The browser reports the score here, so a
@@ -28,6 +28,16 @@ const MAX_SCORE = 500
28
28
  app.get('/api/health', (c) => c.json({ ok: true }))
29
29
  app.get('/api/site-theme', (c) => siteThemeResponse(c.env))
30
30
 
31
+ /**
32
+ * Who this request is from, for an interface that cannot ask Marcapony's own
33
+ * sign-in routes (they are not served under a site's `/_apps/<slug>` address).
34
+ */
35
+ app.get('/api/me', async (c) => {
36
+ const who = await identityOf(marcaponyFromEnv(c.env), c.env, c.req.raw)
37
+ if (!who || who.kind !== 'customer') return c.json({ signedIn: false })
38
+ return c.json({ signedIn: true, email: who.email })
39
+ })
40
+
31
41
  app.get('/api/score', async (c) => {
32
42
  const mp = marcaponyFromEnv(c.env)
33
43
  const who = await identityOf(mp, c.env, c.req.raw)
@@ -1,9 +1,19 @@
1
1
  import { useCallback, useEffect, useState } from 'react'
2
- import { auth, type SignedInState, type SignInOptions } from 'marcapony-sdk/browser'
2
+ import { createBrowserAuth, type SignedInState, type SignInOptions } from 'marcapony-sdk/browser'
3
3
  import { api, errorMessage } from './api'
4
4
 
5
5
  const ROUND_SECONDS = 5
6
6
 
7
+ /**
8
+ * Where the app is mounted: `/_apps/<slug>` on a site's address, nothing on the
9
+ * app's own host. Only `auth.signInUrl()` works under a site's address.
10
+ */
11
+ const mount = /^\/_apps\/[^/]+/.exec(location.pathname)?.[0] ?? ''
12
+ const auth = createBrowserAuth({ base: mount })
13
+
14
+ /** What a visitor gets under a site's address, where only the hosted sign-in page exists. */
15
+ const HOSTED_ONLY: SignInOptions = { emailCode: false, signUp: 'hosted', google: false }
16
+
7
17
  /**
8
18
  * Sign-in inside the app. `auth` calls routes Marcapony serves on the app's
9
19
  * own address, so there is no key here and the app never sees a password or
@@ -105,9 +115,7 @@ function SignIn({ offer, onSignedIn }: { offer: SignInOptions; onSignedIn: () =>
105
115
  {error ? <p className="error">{error}</p> : null}
106
116
  <p>
107
117
  {/* Password, Google and registration live on the full sign-in page. */}
108
- <a href={auth.signInUrl({ returnTo: '/' })}>
109
- {offer.emailCode ? 'Other ways to sign in' : 'Sign in'}
110
- </a>
118
+ <a href={auth.signInUrl()}>{offer.emailCode ? 'Other ways to sign in' : 'Sign in'}</a>
111
119
  {offer.signUp === 'hosted' ? (
112
120
  <span className="muted"> (new accounts start there)</span>
113
121
  ) : null}
@@ -126,15 +134,32 @@ export function App() {
126
134
  const [error, setError] = useState<string | null>(null)
127
135
 
128
136
  const refresh = useCallback(async () => {
129
- try {
130
- const state = await auth.me()
131
- setWho(state)
132
- if (!state.signedIn) setOffer(await auth.options())
133
- } catch {
134
- setWho(null)
137
+ if (mount !== '') {
138
+ // `me()` and `options()` are not served under a site's address: ask this
139
+ // app's own server who is signed in, and offer the hosted sign-in page.
140
+ try {
141
+ const me = await api<{ signedIn: boolean; email?: string }>('api/me')
142
+ if (me.signedIn && me.email) {
143
+ setWho({ signedIn: true, email: me.email, name: null, access: true })
144
+ } else {
145
+ setWho({ signedIn: false })
146
+ setOffer(HOSTED_ONLY)
147
+ }
148
+ } catch {
149
+ setWho({ signedIn: false })
150
+ setOffer(HOSTED_ONLY)
151
+ }
152
+ } else {
153
+ try {
154
+ const state = await auth.me()
155
+ setWho(state)
156
+ if (!state.signedIn) setOffer(await auth.options())
157
+ } catch {
158
+ setWho(null)
159
+ }
135
160
  }
136
161
  try {
137
- setBest((await api<{ best: number | null }>('/api/score')).best)
162
+ setBest((await api<{ best: number | null }>('api/score')).best)
138
163
  } catch (err) {
139
164
  setError(errorMessage(err))
140
165
  }
@@ -156,7 +181,7 @@ export function App() {
156
181
 
157
182
  useEffect(() => {
158
183
  if (!finished || !who?.signedIn || !who.access) return
159
- api<{ best: number }>('/api/score', { method: 'PUT', body: { score } })
184
+ api<{ best: number }>('api/score', { method: 'PUT', body: { score } })
160
185
  .then((saved) => setBest(saved.best))
161
186
  .catch((err: unknown) => setError(errorMessage(err)))
162
187
  }, [finished, who, score])
@@ -212,9 +237,11 @@ export function App() {
212
237
  {who?.signedIn && who.access ? (
213
238
  <p className="actions">
214
239
  <span className="muted">Signed in as {who.name ?? who.email}</span>
215
- <button type="button" onClick={() => void signOut()}>
216
- Sign out
217
- </button>
240
+ {mount === '' ? (
241
+ <button type="button" onClick={() => void signOut()}>
242
+ Sign out
243
+ </button>
244
+ ) : null}
218
245
  </p>
219
246
  ) : null}
220
247
  {who && !who.signedIn && offer ? (
@@ -68,7 +68,7 @@ export function App() {
68
68
 
69
69
  useEffect(() => {
70
70
  const query = category ? `?category=${encodeURIComponent(category)}` : ''
71
- api<Catalog>(`/api/catalog${query}`)
71
+ api<Catalog>(`api/catalog${query}`)
72
72
  .then((body) => {
73
73
  setCatalog(body)
74
74
  setKnown((previous) => ({
@@ -109,7 +109,7 @@ export function App() {
109
109
  setBusy(true)
110
110
  setError(null)
111
111
  try {
112
- const body = await api<CheckoutResult>('/api/checkout', {
112
+ const body = await api<CheckoutResult>('api/checkout', {
113
113
  body: {
114
114
  attemptId,
115
115
  items: lines.map(({ productId, quantity }) => ({ productId, quantity })),
@@ -54,7 +54,7 @@ export function App() {
54
54
  const load = useCallback((day: string) => {
55
55
  setReservations(null)
56
56
  api<{ reservations: Reservation[]; truncated: boolean }>(
57
- `/api/reservations?date=${encodeURIComponent(day)}`,
57
+ `api/reservations?date=${encodeURIComponent(day)}`,
58
58
  )
59
59
  .then((body) => {
60
60
  setReservations(body.reservations)
@@ -64,7 +64,7 @@ export function App() {
64
64
  }, [])
65
65
 
66
66
  useEffect(() => {
67
- api<Me>('/api/me')
67
+ api<Me>('api/me')
68
68
  .then(setMe)
69
69
  .catch((err: unknown) => {
70
70
  if (err instanceof ApiError && (err.status === 401 || err.status === 403)) {
@@ -91,7 +91,7 @@ export function App() {
91
91
  setMessage(null)
92
92
  try {
93
93
  const body = await api<{ simulated: boolean }>(
94
- `/api/reservations/${encodeURIComponent(reservation.id)}/status`,
94
+ `api/reservations/${encodeURIComponent(reservation.id)}/status`,
95
95
  { body: { status, rejectionReason } },
96
96
  )
97
97
  setMessage(