create-marcapony-app 0.1.1 → 0.2.1

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.
Files changed (35) hide show
  1. package/README.md +27 -23
  2. package/dist/index.d.ts +28 -3
  3. package/dist/index.js +102 -20
  4. package/package.json +5 -4
  5. package/template/base/.dev.vars.example +7 -0
  6. package/template/{_package.json → base/_package.json} +14 -11
  7. package/template/{marcapony.json → base/marcapony.json} +1 -1
  8. package/template/{scripts → base/scripts}/dev.ts +19 -2
  9. package/template/base/src/server/marcapony.ts +71 -0
  10. package/template/base/src/ui/api.ts +34 -0
  11. package/template/base/src/ui/styles.css +115 -0
  12. package/template/blank/README.md +48 -0
  13. package/template/{src → blank/src}/server/index.ts +9 -7
  14. package/template/booking/README.md +58 -0
  15. package/template/booking/marcapony.json +26 -0
  16. package/template/booking/src/server/index.ts +112 -0
  17. package/template/booking/src/ui/App.tsx +188 -0
  18. package/template/shop/README.md +66 -0
  19. package/template/shop/marcapony.json +12 -0
  20. package/template/shop/src/server/index.ts +205 -0
  21. package/template/shop/src/ui/App.tsx +214 -0
  22. package/template/team-tool/README.md +59 -0
  23. package/template/team-tool/marcapony.json +25 -0
  24. package/template/team-tool/src/server/index.ts +115 -0
  25. package/template/team-tool/src/ui/App.tsx +179 -0
  26. package/template/.dev.vars.example +0 -5
  27. package/template/README.md +0 -57
  28. package/template/src/server/marcapony.ts +0 -28
  29. package/template/src/ui/styles.css +0 -45
  30. /package/template/{_gitignore → base/_gitignore} +0 -0
  31. /package/template/{index.html → base/index.html} +0 -0
  32. /package/template/{src → base/src}/ui/main.tsx +0 -0
  33. /package/template/{tsconfig.json → base/tsconfig.json} +0 -0
  34. /package/template/{vite.config.ts → base/vite.config.ts} +0 -0
  35. /package/template/{src → blank/src}/ui/App.tsx +0 -0
package/README.md CHANGED
@@ -1,50 +1,54 @@
1
1
  # create-marcapony-app
2
2
 
3
- Creates a new Marcapony app — a small web app with its own backend, already
4
- connected to your Marcapony account.
3
+ Creates a new Marcapony app: a small web app with its own backend, connected to
4
+ your Marcapony account and hosted by Marcapony.
5
5
 
6
6
  ```sh
7
- npx create-marcapony-app my-app
7
+ npx create-marcapony-app my-app --template booking
8
8
  cd my-app
9
9
  bun install
10
- npx marcapony app link
10
+ bun run link
11
11
  bun run dev
12
12
  ```
13
13
 
14
14
  When it is ready:
15
15
 
16
16
  ```sh
17
- npx marcapony app deploy
17
+ bun run deploy
18
18
  ```
19
19
 
20
- Marcapony hosts it. There is nothing to set up and no other account to sign up
21
- for.
20
+ `bun run link` and `bun run deploy` run the Marcapony CLI that the new project
21
+ pins in its `devDependencies`. `bun run link` also writes an `AGENTS.md` listing
22
+ exactly what the app is allowed to do, so an AI assistant can pick the project
23
+ up and build on it.
22
24
 
23
- ## What you get
25
+ ## Templates
24
26
 
25
- | Path | What it is |
26
- | ------------------------- | ------------------------------------------- |
27
- | `src/server/index.ts` | Your backend. Handles `/api/*` |
28
- | `src/server/marcapony.ts` | The only place that talks to Marcapony |
29
- | `src/ui/` | Your interface |
30
- | `marcapony.json` | How Marcapony builds and publishes your app |
27
+ | Template | What it is | Runs in |
28
+ | ----------- | ------------------------------------------------------------------ | --------------- |
29
+ | `blank` | A starting point that lists your products (the default) | Your site |
30
+ | `booking` | Signed-in customers see, book and cancel their appointments | Customer portal |
31
+ | `shop` | Products, a cart and a checkout that sends the buyer to pay | Your site |
32
+ | `team-tool` | Your team approves, rejects and completes the day's reservations | Dashboard |
31
33
 
32
- `npx marcapony app link` puts your app key in place and writes an `AGENTS.md`
33
- listing exactly what this app is allowed to do — so an AI assistant can pick the
34
- project up and start building on it.
34
+ Each template's `README.md` says which placement, data access, scopes and
35
+ permissions to choose when you create the app under **My Apps** in the
36
+ dashboard, which routes it exposes and what to change first.
35
37
 
36
38
  ## Options
37
39
 
38
- | Flag | Meaning |
39
- | --------- | ----------------------------------------------------- |
40
- | `--force` | Write into the directory even if it already has files |
41
- | `-h` | Help |
40
+ | Flag | Meaning |
41
+ | ----------------------- | ---------------------------------------------------------- |
42
+ | `--template`, `-t` | Which template to use; asked in a terminal, else `blank` |
43
+ | `--force` | Write into a directory that already has files; never overwrites a file that is there |
44
+ | `-h`, `--help` | Help |
42
45
 
43
46
  Run without a directory name and it asks for one.
44
47
 
45
- Requires Node 20 or newer, or Bun. No runtime dependencies.
48
+ The scaffolder runs on Node 20 or newer and has no runtime dependencies. The app
49
+ it creates needs [Bun](https://bun.sh).
46
50
 
47
51
  ## License
48
52
 
49
- Proprietary tool, unrestricted output — the app it creates is yours to license
53
+ Proprietary tool, unrestricted output: the app it creates is yours to license
50
54
  and ship however you like. See [LICENSE.md](./LICENSE.md).
package/dist/index.d.ts CHANGED
@@ -1,4 +1,21 @@
1
1
  #!/usr/bin/env node
2
+ export declare const TEMPLATES: readonly [{
3
+ readonly name: "blank";
4
+ readonly summary: "A starting point that lists your products";
5
+ }, {
6
+ readonly name: "booking";
7
+ readonly summary: "Customers book and cancel appointments in the portal";
8
+ }, {
9
+ readonly name: "shop";
10
+ readonly summary: "Products, a cart and checkout with a payment link";
11
+ }, {
12
+ readonly name: "team-tool";
13
+ readonly summary: "Your team approves and updates today's reservations";
14
+ }];
15
+ export type TemplateName = (typeof TEMPLATES)[number]['name'];
16
+ export declare const DEFAULT_TEMPLATE: TemplateName;
17
+ export declare function isTemplateName(value: string): value is TemplateName;
18
+ export declare function unknownTemplateMessage(name: string): string;
2
19
  /**
3
20
  * npm refuses to load a package whose name breaks its rules, and the name here
4
21
  * comes from a directory the user typed. Keep the recognizable part, drop the
@@ -8,13 +25,15 @@ export declare function sanitizePackageName(input: string): string;
8
25
  export declare function templateTargetName(name: string): string;
9
26
  export interface ParsedArgs {
10
27
  dir?: string;
28
+ /** As typed; validated by `run`. An empty string means the flag had no value. */
29
+ template?: string;
11
30
  force: boolean;
12
31
  help: boolean;
13
32
  }
14
33
  export declare function parseArgs(argv: string[]): ParsedArgs;
15
- export declare const HELP = "create-marcapony-app \u2014 scaffold a Marcapony app\n\nUsage\n npx create-marcapony-app [directory] [--force]\n\nOptions\n --force Write into the directory even if it already has files\n -h Show this help\n\nNext, in the new directory:\n npx marcapony app link get this app's key\n bun run dev run it locally\n npx marcapony app deploy put it live\n";
16
- export declare function nextSteps(dir: string): string;
17
- /** Resolve `template/` relative to the compiled entry, not the cwd. */
34
+ export declare const HELP: string;
35
+ export declare function nextSteps(dir: string, template?: TemplateName): string;
36
+ /** Resolve `template/` (the directory holding `base/` and every overlay) relative to the compiled entry, not the cwd. */
18
37
  export declare function templateRoot(moduleUrl: string): string;
19
38
  /**
20
39
  * Copy the template, never overwriting a file that is already there.
@@ -26,5 +45,11 @@ export declare function templateRoot(moduleUrl: string): string;
26
45
  * only what is missing is both safer and the more useful meaning of --force.
27
46
  */
28
47
  export declare function copyTemplate(from: string, to: string): void;
48
+ /**
49
+ * Scaffold one template: its overlay first, then the base. `copyTemplate` never
50
+ * overwrites, so an overlay file wins over the base file of the same name, and
51
+ * neither ever replaces a file that was already in the target.
52
+ */
53
+ export declare function scaffoldTemplate(root: string, template: TemplateName, to: string): void;
29
54
  export declare function applyPackageName(dir: string, name: string): void;
30
55
  export declare function run(argv: string[], moduleUrl: string): Promise<number>;
package/dist/index.js CHANGED
@@ -1,16 +1,32 @@
1
1
  #!/usr/bin/env node
2
- import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync, } from 'node:fs';
2
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
3
  import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { createInterface } from 'node:readline/promises';
6
6
  /**
7
- * `create-marcapony-app` — copies the template in `template/` into a new
8
- * directory and points its package.json at the chosen name. Deliberately does
7
+ * `create-marcapony-app` — copies a template from `template/` into a new
8
+ * directory and points its package.json at the chosen name. Every template is
9
+ * the shared `template/base/` plus its own overlay (`template/<name>/`), whose
10
+ * files replace or add to the base. Deliberately does
9
11
  * no key handling and no deploy: `marcapony app link` mints the key and
10
12
  * `marcapony app deploy` ships the project, and both work on any project, not
11
13
  * just a scaffolded one.
12
14
  */
13
15
  const DEFAULT_DIR = 'marcapony-app';
16
+ export const TEMPLATES = [
17
+ { name: 'blank', summary: 'A starting point that lists your products' },
18
+ { name: 'booking', summary: 'Customers book and cancel appointments in the portal' },
19
+ { name: 'shop', summary: 'Products, a cart and checkout with a payment link' },
20
+ { name: 'team-tool', summary: "Your team approves and updates today's reservations" },
21
+ ];
22
+ export const DEFAULT_TEMPLATE = 'blank';
23
+ const BASE_DIR = 'base';
24
+ export function isTemplateName(value) {
25
+ return TEMPLATES.some((template) => template.name === value);
26
+ }
27
+ export function unknownTemplateMessage(name) {
28
+ return `Unknown template "${name}". Choose one of: ${TEMPLATES.map((t) => t.name).join(', ')}.\n`;
29
+ }
14
30
  /**
15
31
  * npm refuses to load a package whose name breaks its rules, and the name here
16
32
  * comes from a directory the user typed. Keep the recognizable part, drop the
@@ -41,11 +57,24 @@ export function templateTargetName(name) {
41
57
  }
42
58
  export function parseArgs(argv) {
43
59
  const out = { force: false, help: false };
44
- for (const arg of argv) {
60
+ for (let i = 0; i < argv.length; i++) {
61
+ const arg = argv[i];
45
62
  if (arg === '--force')
46
63
  out.force = true;
47
64
  else if (arg === '--help' || arg === '-h')
48
65
  out.help = true;
66
+ else if (arg === '--template' || arg === '-t') {
67
+ const value = argv[i + 1];
68
+ if (value !== undefined && !value.startsWith('-')) {
69
+ out.template = value;
70
+ i++;
71
+ }
72
+ else {
73
+ out.template = '';
74
+ }
75
+ }
76
+ else if (arg.startsWith('--template='))
77
+ out.template = arg.slice('--template='.length);
49
78
  else if (!arg.startsWith('-') && out.dir === undefined)
50
79
  out.dir = arg;
51
80
  }
@@ -54,34 +83,45 @@ export function parseArgs(argv) {
54
83
  export const HELP = `create-marcapony-app — scaffold a Marcapony app
55
84
 
56
85
  Usage
57
- npx create-marcapony-app [directory] [--force]
86
+ npx create-marcapony-app [directory] [--template <name>] [--force]
87
+
88
+ Templates
89
+ ${TEMPLATES.map((t) => ` ${t.name.padEnd(10)} ${t.summary}`).join('\n')}
58
90
 
59
91
  Options
60
- --force Write into the directory even if it already has files
61
- -h Show this help
92
+ --template, -t <name> Which template to use (asked when omitted in a
93
+ terminal, otherwise ${DEFAULT_TEMPLATE})
94
+ --force Write into the directory even if it already has files
95
+ -h, --help Show this help
62
96
 
63
97
  Next, in the new directory:
64
- npx marcapony app link get this app's key
65
- bun run dev run it locally
66
- npx marcapony app deploy put it live
98
+ bun install install dependencies, including the Marcapony CLI
99
+ bun run link get this app's key
100
+ bun run dev run it locally
101
+ bun run deploy put it live
102
+
103
+ The scaffolder runs on Node 20 or newer. The app it creates needs Bun.
67
104
  `;
68
- export function nextSteps(dir) {
105
+ export function nextSteps(dir, template = DEFAULT_TEMPLATE) {
69
106
  return [
70
107
  '',
71
- `Created ${dir}.`,
108
+ `Created ${dir} from the ${template} template.`,
109
+ '',
110
+ 'Read its README.md first: it says what the app does and which scopes and',
111
+ 'permissions to enable when you create the app in the Marcapony dashboard.',
72
112
  '',
73
113
  'Next:',
74
114
  ` cd ${dir}`,
75
115
  ' bun install',
76
- ' npx marcapony app link # writes your app key into .dev.vars',
116
+ ' bun run link # writes your app key into .dev.vars',
77
117
  ' bun run dev',
78
118
  '',
79
119
  'When it is ready:',
80
- ' npx marcapony app deploy',
120
+ ' bun run deploy',
81
121
  '',
82
122
  ].join('\n');
83
123
  }
84
- /** Resolve `template/` relative to the compiled entry, not the cwd. */
124
+ /** Resolve `template/` (the directory holding `base/` and every overlay) relative to the compiled entry, not the cwd. */
85
125
  export function templateRoot(moduleUrl) {
86
126
  return resolve(dirname(fileURLToPath(moduleUrl)), '..', 'template');
87
127
  }
@@ -106,6 +146,10 @@ export function copyTemplate(from, to) {
106
146
  const relative = source.slice(from.length).replace(/^[/\\]/, '');
107
147
  if (relative.length === 0)
108
148
  return true;
149
+ // Always descend: an existing directory (from an overlay, or already in a
150
+ // --force target) must not hide the files beneath it.
151
+ if (statSync(source).isDirectory())
152
+ return true;
109
153
  const segments = relative.split(/[/\\]/);
110
154
  const last = segments[segments.length - 1];
111
155
  if (last === undefined)
@@ -127,6 +171,15 @@ export function copyTemplate(from, to) {
127
171
  renameSync(sourcePath, targetPath);
128
172
  }
129
173
  }
174
+ /**
175
+ * Scaffold one template: its overlay first, then the base. `copyTemplate` never
176
+ * overwrites, so an overlay file wins over the base file of the same name, and
177
+ * neither ever replaces a file that was already in the target.
178
+ */
179
+ export function scaffoldTemplate(root, template, to) {
180
+ copyTemplate(join(root, template), to);
181
+ copyTemplate(join(root, BASE_DIR), to);
182
+ }
130
183
  export function applyPackageName(dir, name) {
131
184
  const path = join(dir, 'package.json');
132
185
  const manifest = JSON.parse(readFileSync(path, 'utf8'));
@@ -146,26 +199,55 @@ async function promptForDir() {
146
199
  rl.close();
147
200
  }
148
201
  }
202
+ async function promptForTemplate() {
203
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
204
+ try {
205
+ process.stdout.write('Template:\n');
206
+ TEMPLATES.forEach((t, i) => {
207
+ process.stdout.write(` ${i + 1}. ${t.name.padEnd(10)} ${t.summary}\n`);
208
+ });
209
+ for (;;) {
210
+ const answer = (await rl.question(`Choose 1-${TEMPLATES.length} (1): `)).trim();
211
+ if (answer.length === 0)
212
+ return DEFAULT_TEMPLATE;
213
+ const byNumber = TEMPLATES[Number(answer) - 1];
214
+ if (/^\d+$/.test(answer) && byNumber)
215
+ return byNumber.name;
216
+ if (isTemplateName(answer))
217
+ return answer;
218
+ process.stdout.write(`Type a number from 1 to ${TEMPLATES.length}, or a template name.\n`);
219
+ }
220
+ }
221
+ finally {
222
+ rl.close();
223
+ }
224
+ }
149
225
  export async function run(argv, moduleUrl) {
150
226
  const args = parseArgs(argv);
151
227
  if (args.help) {
152
228
  process.stdout.write(HELP);
153
229
  return 0;
154
230
  }
231
+ if (args.template !== undefined && !isTemplateName(args.template)) {
232
+ process.stderr.write(unknownTemplateMessage(args.template));
233
+ return 1;
234
+ }
155
235
  const requested = args.dir ?? (process.stdin.isTTY ? await promptForDir() : DEFAULT_DIR);
156
236
  const target = resolve(process.cwd(), requested);
157
237
  if (isNonEmptyDir(target) && !args.force) {
158
238
  process.stderr.write(`${requested} already has files in it. Pick another name, or pass --force to write into it anyway.\n`);
159
239
  return 1;
160
240
  }
161
- const template = templateRoot(moduleUrl);
162
- if (!existsSync(template)) {
163
- process.stderr.write(`The template directory is missing from this install (looked in ${template}). Reinstall create-marcapony-app.\n`);
241
+ const root = templateRoot(moduleUrl);
242
+ if (!existsSync(join(root, BASE_DIR))) {
243
+ process.stderr.write(`The template directory is missing from this install (looked in ${root}). Reinstall create-marcapony-app.\n`);
164
244
  return 1;
165
245
  }
166
- copyTemplate(template, target);
246
+ const template = args.template ??
247
+ (process.stdin.isTTY ? await promptForTemplate() : DEFAULT_TEMPLATE);
248
+ scaffoldTemplate(root, template, target);
167
249
  applyPackageName(target, sanitizePackageName(basename(target)));
168
- process.stdout.write(nextSteps(requested));
250
+ process.stdout.write(nextSteps(requested, template));
169
251
  return 0;
170
252
  }
171
253
  /**
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "create-marcapony-app",
3
- "version": "0.1.1",
4
- "description": "Scaffold a Marcapony app — a Worker backed by the Marcapony API, ready for `marcapony app link` and `marcapony app deploy`",
3
+ "version": "0.2.1",
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",
7
7
  "homepage": "https://marcapony.com",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/creafolks/marcapony-api.git",
10
+ "url": "git+https://github.com/creafolks/marcapony-devkit.git",
11
11
  "directory": "create-app"
12
12
  },
13
13
  "publishConfig": {
@@ -27,7 +27,8 @@
27
27
  "build": "tsc -p tsconfig.build.json",
28
28
  "typecheck": "tsc --noEmit",
29
29
  "test": "bun test",
30
- "prepublishOnly": "bun run build"
30
+ "prepublishOnly": "bun run build",
31
+ "check:templates": "bun run scripts/check-templates.ts"
31
32
  },
32
33
  "devDependencies": {
33
34
  "@types/bun": "^1.3.14",
@@ -0,0 +1,7 @@
1
+ # `bun run link` writes the real values into `.dev.vars` for you: the key is
2
+ # minted fresh and never passes through a clipboard. This file is only here to
3
+ # document what ends up there.
4
+ MARCAPONY_API_KEY=mpk_...
5
+ MARCAPONY_API_URL=https://api.marcapony.com/ext/v1
6
+ # MARCAPONY_APP_ID is not written locally. The platform sets it when the app is
7
+ # deployed, so locally there is no app id and identity() is always null.
@@ -5,24 +5,27 @@
5
5
  "type": "module",
6
6
  "scripts": {
7
7
  "dev": "bun run scripts/dev.ts",
8
+ "link": "marcapony app link",
9
+ "deploy": "marcapony app deploy",
8
10
  "build": "bun run build:client && bun run build:worker",
9
11
  "build:client": "vite build",
10
12
  "build:worker": "esbuild src/server/index.ts --bundle --format=esm --platform=neutral --conditions=worker,browser --target=es2022 --outfile=dist/worker/index.js",
11
13
  "typecheck": "tsc --noEmit"
12
14
  },
13
15
  "dependencies": {
14
- "hono": "^4.6.14",
15
- "marcapony-sdk": "^0.2.0",
16
- "react": "^19.0.0",
17
- "react-dom": "^19.0.0"
16
+ "hono": "^4.13.0",
17
+ "marcapony-sdk": "^0.7.0",
18
+ "react": "^19.3.0",
19
+ "react-dom": "^19.3.0"
18
20
  },
19
21
  "devDependencies": {
20
- "@types/bun": "^1.3.14",
21
- "@types/react": "^19.0.0",
22
- "@types/react-dom": "^19.0.0",
23
- "@vitejs/plugin-react": "^5.0.0",
24
- "esbuild": "^0.25.0",
25
- "typescript": "^5.8.3",
26
- "vite": "^7.0.0"
22
+ "@types/bun": "^1.4.4",
23
+ "@types/react": "^19.3.0",
24
+ "@types/react-dom": "^19.3.0",
25
+ "@vitejs/plugin-react": "^5.2.0",
26
+ "esbuild": "^0.28.0",
27
+ "marcapony": "^0.4.2",
28
+ "typescript": "^5.9.0",
29
+ "vite": "^7.3.0"
27
30
  }
28
31
  }
@@ -6,6 +6,6 @@
6
6
  "not_found_handling": "single-page-application",
7
7
  "run_worker_first": ["/api/*"]
8
8
  },
9
- "compatibilityDate": "2025-05-10",
9
+ "compatibilityDate": "2026-10-01",
10
10
  "compatibilityFlags": ["nodejs_compat"]
11
11
  }
@@ -4,7 +4,7 @@
4
4
  *
5
5
  * Caveat worth knowing: this runs under Bun, not the Workers runtime. The two
6
6
  * are close but not identical, so a deployed app can still surface something
7
- * local dev did not. Verify after `bunx marcapony app deploy`, and prefer plain
7
+ * local dev did not. Verify after `bun run deploy`, and prefer plain
8
8
  * web APIs (fetch, Request, Response, crypto) over Node built-ins in
9
9
  * `src/server` — those are the ones that behave the same in both.
10
10
  */
@@ -27,10 +27,27 @@ function loadDevVars(): Record<string, string> {
27
27
  return out
28
28
  }
29
29
 
30
+ function readPlacement(): string | undefined {
31
+ try {
32
+ const config = JSON.parse(readFileSync('marcapony.json', 'utf8')) as { placement?: string }
33
+ return config.placement
34
+ } catch {
35
+ return undefined
36
+ }
37
+ }
38
+
30
39
  const env = loadDevVars()
31
40
  if (!env.MARCAPONY_API_KEY) {
32
41
  console.warn(
33
- `No MARCAPONY_API_KEY in ${ENV_FILE} — /api routes that call Marcapony will fail.\nRun \`bunx marcapony app link\` to get one.`,
42
+ `No MARCAPONY_API_KEY in ${ENV_FILE} — /api routes that call Marcapony will fail.\nRun \`bun run link\` to get one.`,
43
+ )
44
+ }
45
+
46
+ // A portal app only learns who is signed in from a header the platform adds,
47
+ // using the app id it sets at deploy. Neither exists here.
48
+ if (!env.MARCAPONY_APP_ID && readPlacement() === 'portal') {
49
+ console.info(
50
+ 'Local dev has no app id and no signed-in visitor, so identity is null and signed-in routes answer 401.\nTry those flows on the deployed app (`bun run deploy`), opened from the portal or the dashboard.',
34
51
  )
35
52
  }
36
53
 
@@ -0,0 +1,71 @@
1
+ import { createClient, MarcaponyError, type Identity } from 'marcapony-sdk'
2
+
3
+ /**
4
+ * The one place that owns the Marcapony env contract and builds the client.
5
+ * Keep it that way: a second `createClient` call somewhere else is how a key
6
+ * ends up read from the wrong place, or bundled into the browser.
7
+ */
8
+ export interface MarcaponyBindings {
9
+ /** Scoped app key (`mpk_...`). Written into `.dev.vars` by `bun run link`. */
10
+ MARCAPONY_API_KEY?: string
11
+ /** API root. Also written by `bun run link`; the SDK defaults to production. */
12
+ MARCAPONY_API_URL?: string
13
+ /**
14
+ * The app's id. The platform sets it when the app is deployed, and
15
+ * `identity()` needs it to check who is signed in. `bun run link` does not
16
+ * write it, so locally there is no app id (and no identity header either):
17
+ * identity is always null in local dev.
18
+ */
19
+ MARCAPONY_APP_ID?: string
20
+ }
21
+
22
+ export type Marcapony = ReturnType<typeof createClient>
23
+
24
+ /**
25
+ * Workers env is request-scoped, so build the client per request. The SDK is
26
+ * zero-dependency and holds no connections, so construction is effectively free.
27
+ */
28
+ export function marcaponyFromEnv(env: MarcaponyBindings): Marcapony {
29
+ if (!env.MARCAPONY_API_KEY) {
30
+ throw new Error(
31
+ 'MARCAPONY_API_KEY is missing. Run `bun run link` in this project. It writes the key into .dev.vars for you.',
32
+ )
33
+ }
34
+ return createClient({
35
+ apiKey: env.MARCAPONY_API_KEY,
36
+ baseUrl: env.MARCAPONY_API_URL,
37
+ appId: env.MARCAPONY_APP_ID,
38
+ })
39
+ }
40
+
41
+ /**
42
+ * Who is signed in on this request, or null. The SDK's `identity()` throws
43
+ * without an app id; locally there is none, so this answers null there instead
44
+ * of failing every request. Use it for display and for hiding buttons only:
45
+ * the platform enforces access itself on every call.
46
+ */
47
+ export async function identityOf(
48
+ mp: Marcapony,
49
+ env: MarcaponyBindings,
50
+ request: Request,
51
+ ): Promise<Identity | null> {
52
+ if (!env.MARCAPONY_APP_ID) return null
53
+ return mp.identity(request)
54
+ }
55
+
56
+ /**
57
+ * Turns a failed call into a JSON answer for the browser. A Marcapony error
58
+ * keeps its status (401 not signed in, 403 not allowed, 404, 422 invalid
59
+ * input, 429) so the interface can tell the visitor what happened; anything
60
+ * else is a 500.
61
+ */
62
+ export function errorResponse(err: unknown): Response {
63
+ if (err instanceof MarcaponyError && err.status >= 400 && err.status < 500) {
64
+ return Response.json({ error: err.message, code: err.code }, { status: err.status })
65
+ }
66
+ console.error(err)
67
+ return Response.json(
68
+ { error: err instanceof Error ? err.message : 'Unexpected error' },
69
+ { status: 500 },
70
+ )
71
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Calls this app's own `/api` routes. The interface never talks to Marcapony
3
+ * directly: the app key lives on the server and must stay there.
4
+ */
5
+ export class ApiError extends Error {
6
+ readonly status: number
7
+
8
+ constructor(status: number, message: string) {
9
+ super(message)
10
+ this.status = status
11
+ }
12
+ }
13
+
14
+ export async function api<T>(path: string, init?: { method?: string; body?: unknown }): Promise<T> {
15
+ const response = await fetch(path, {
16
+ method: init?.method ?? (init?.body === undefined ? 'GET' : 'POST'),
17
+ headers: init?.body === undefined ? undefined : { 'Content-Type': 'application/json' },
18
+ body: init?.body === undefined ? undefined : JSON.stringify(init.body),
19
+ })
20
+ const body = (await response.json().catch(() => ({}))) as { error?: string }
21
+ if (!response.ok) {
22
+ throw new ApiError(response.status, body.error ?? `Request failed with status ${response.status}`)
23
+ }
24
+ return body as T
25
+ }
26
+
27
+ export function errorMessage(err: unknown): string {
28
+ return err instanceof Error ? err.message : 'Request failed'
29
+ }
30
+
31
+ /** One id per user action, reused when that action is retried. */
32
+ export function newRequestId(): string {
33
+ return crypto.randomUUID()
34
+ }