create-signet-app 0.4.8 → 0.6.0

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 (99) hide show
  1. package/README.md +133 -33
  2. package/{template-full → base/api}/api/app.ts +105 -13
  3. package/base/api/api/db/open.ts +121 -0
  4. package/{template-full → base/api}/api/db/schema.ts +34 -7
  5. package/{template-full → base/api}/api/env.ts +16 -0
  6. package/base/api/api/server.ts +163 -0
  7. package/{template-full → base/api}/api/services.ts +103 -10
  8. package/base/api/drizzle/0002_ai_paywalls_workflows.sql +77 -0
  9. package/base/api/drizzle/meta/0002_snapshot.json +1759 -0
  10. package/{template-full → base/api}/drizzle/meta/_journal.json +7 -0
  11. package/base/api/test/api.test.ts +51 -0
  12. package/base/api/test/helpers.ts +51 -0
  13. package/base/both/scripts/dev.ts +44 -0
  14. package/base/shared/README.md +385 -0
  15. package/{template-full → base/shared}/_github/workflows/ci.yml +1 -1
  16. package/{template-full → base/web}/src/lib/api.ts +28 -1
  17. package/{template-full → base/web}/src/main.tsx +4 -1
  18. package/{template-full → base/web}/src/routeTree.gen.ts +155 -90
  19. package/{template-full → base/web}/src/router.test.ts +13 -9
  20. package/base/web/src/routes/_app/index.tsx +55 -0
  21. package/{template-full → base/web}/src/routes/_app.tsx +40 -16
  22. package/{template-full → base/web}/vite.config.ts +3 -1
  23. package/package.json +9 -5
  24. package/parts/account/api/test/account.test.ts +30 -0
  25. package/parts/account/part.ts +6 -0
  26. package/parts/admin/api/test/admin.test.ts +35 -0
  27. package/parts/admin/part.ts +6 -0
  28. package/{template-full → parts/admin/web}/src/routes/_app/admin.tsx +2 -1
  29. package/parts/ai/api/api/routes/ai.ts +28 -0
  30. package/parts/ai/api/test/ai.test.ts +52 -0
  31. package/parts/ai/part.ts +16 -0
  32. package/{template-full → parts/auth/api}/api/routes/account.ts +32 -3
  33. package/{template-full → parts/auth/api}/api/routes/auth.ts +5 -3
  34. package/parts/auth/api/test/auth.test.ts +28 -0
  35. package/{template-full → parts/auth/both}/e2e/smoke.spec.ts +21 -7
  36. package/parts/auth/part.ts +22 -0
  37. package/parts/growth/part.ts +7 -0
  38. package/{template-full/_mcp → parts/mcp/api}/test/mcp.test.ts +25 -16
  39. package/parts/mcp/part.ts +8 -0
  40. package/parts/notifications/api/test/notifications.test.ts +18 -0
  41. package/parts/notifications/part.ts +6 -0
  42. package/{template-full → parts/notifications/web}/src/routes/_app/notifications.tsx +1 -1
  43. package/parts/orgs/api/test/orgs.test.ts +56 -0
  44. package/parts/orgs/part.ts +7 -0
  45. package/{template-full → parts/payments/api}/api/routes/billing.ts +3 -2
  46. package/parts/payments/api/test/payments.test.ts +31 -0
  47. package/parts/payments/part.ts +12 -0
  48. package/{template-full → parts/payments/web}/src/routes/_app/billing.tsx +6 -3
  49. package/parts/paywalls/api/api/routes/paywall.ts +126 -0
  50. package/parts/paywalls/api/test/paywalls.test.ts +71 -0
  51. package/parts/paywalls/part.ts +8 -0
  52. package/parts/privacy/api/test/privacy.test.ts +20 -0
  53. package/parts/privacy/part.ts +7 -0
  54. package/parts/workflows/api/api/workflows.ts +33 -0
  55. package/parts/workflows/api/test/workflows.test.ts +44 -0
  56. package/parts/workflows/part.ts +7 -0
  57. package/parts/workflows/web/src/routes/_app/approvals.tsx +34 -0
  58. package/src/compose.ts +426 -0
  59. package/src/desktop.ts +10 -10
  60. package/src/index.ts +407 -174
  61. package/template-api/_targets/deno/Dockerfile +12 -0
  62. package/template-api/_targets/deno/_dockerignore +10 -0
  63. package/template-api/_targets/deno/src/server.ts +43 -0
  64. package/template-full/README.md +0 -166
  65. package/template-full/api/db/open.ts +0 -33
  66. package/template-full/api/server.ts +0 -50
  67. package/template-full/scripts/dev.ts +0 -17
  68. package/template-full/src/routes/_app/index.tsx +0 -33
  69. package/template-full/test/api.test.ts +0 -238
  70. package/template-full/tsconfig.json +0 -9
  71. /package/{template-full → base/api}/api/db/index.ts +0 -0
  72. /package/{template-full → base/api}/api/db/kv.ts +0 -0
  73. /package/{template-full → base/api}/drizzle/0000_init.sql +0 -0
  74. /package/{template-full → base/api}/drizzle/0001_orgs.sql +0 -0
  75. /package/{template-full → base/api}/drizzle/meta/0000_snapshot.json +0 -0
  76. /package/{template-full → base/api}/drizzle/meta/0001_snapshot.json +0 -0
  77. /package/{template-full → base/api}/drizzle.config.ts +0 -0
  78. /package/{template-full → base/api}/tsconfig.api.json +0 -0
  79. /package/{template-full → base/shared}/_gitignore +0 -0
  80. /package/{template-full → base/shared}/biome.json +0 -0
  81. /package/{template-full → base/web}/index.html +0 -0
  82. /package/{template-full → base/web}/src/app.css +0 -0
  83. /package/{template-full → base/web}/src/components/toaster.tsx +0 -0
  84. /package/{template-full → base/web}/src/router.ts +0 -0
  85. /package/{template-full → base/web}/src/routes/__root.tsx +0 -0
  86. /package/{template-full → base/web}/tsconfig.app.json +0 -0
  87. /package/{template-full → base/web}/tsconfig.node.json +0 -0
  88. /package/{template-full → base/web}/tsconfig.test.json +0 -0
  89. /package/{template-full → parts/account/web}/src/routes/_app/account.tsx +0 -0
  90. /package/{template-full → parts/auth/both}/playwright.config.ts +0 -0
  91. /package/{template-full → parts/auth/web}/src/routes/login.tsx +0 -0
  92. /package/{template-full → parts/notifications/api}/api/routes/notifications.ts +0 -0
  93. /package/{template-full → parts/orgs/web}/src/routes/_app/org/index.tsx +0 -0
  94. /package/{template-full → parts/orgs/web}/src/routes/_app/org/members.tsx +0 -0
  95. /package/{template-full → parts/orgs/web}/src/routes/_app/org/new.tsx +0 -0
  96. /package/{template-full → parts/orgs/web}/src/routes/invite.$token.tsx +0 -0
  97. /package/{template-full → parts/payments/api}/api/plans.ts +0 -0
  98. /package/{template-full → parts/privacy/api}/api/routes/privacy.ts +0 -0
  99. /package/{template-full → parts/privacy/web}/src/routes/_app/privacy.tsx +0 -0
@@ -10,18 +10,23 @@ export const envSchema = z.object({
10
10
  PORT: z.coerce.number().default(3000),
11
11
  /** The SQLite file. ":memory:" for a throwaway database. */
12
12
  DATABASE_PATH: z.string().default("data/app.db"),
13
+ // auth:begin
13
14
  /** Signs session cookies. 32+ random characters, different per environment. */
14
15
  SESSION_SECRET: z.string().min(32),
15
16
  /** Keys the stored one-time-code hashes. 32+ random characters. */
16
17
  OTP_SECRET: z.string().min(32),
17
18
  /** Comma-separated phone numbers (E.164) that get the admin role on sign-in. */
18
19
  ADMIN_PHONES: z.string().default(""),
20
+ // auth:end
21
+ // payments:begin
19
22
  /**
20
23
  * "fake": Upgrade switches the plan at once and no money moves. Refused in
21
24
  * staging and production. "razorpay": webhooks through signet-payments
22
25
  * (see README).
23
26
  */
24
27
  BILLING: z.enum(["fake", "razorpay"]).default("fake"),
28
+ // payments:end
29
+ // orgs:begin
25
30
  /**
26
31
  * Your app's own domain, e.g. "app.example.com": then acme.app.example.com
27
32
  * opens the org with slug "acme". Hosts outside it are looked up as an
@@ -29,14 +34,25 @@ export const envSchema = z.object({
29
34
  * x-org header or the switch cookie, which is all local development needs.
30
35
  */
31
36
  ORG_ROOT_DOMAIN: z.string().optional(),
37
+ // orgs:end
32
38
  /**
33
39
  * "on": JSON request logs, a span per request and /health/live and
34
40
  * /health/ready (server.ts). Off by default. See observability in app.ts.
35
41
  */
36
42
  OBSERVABILITY: z.enum(["on", "off"]).default("off"),
43
+ // payments:begin
37
44
  RAZORPAY_KEY_ID: z.string().optional(),
38
45
  RAZORPAY_KEY_SECRET: z.string().optional(),
39
46
  RAZORPAY_WEBHOOK_SECRET: z.string().optional(),
47
+ // payments:end
48
+ // ai:begin
49
+ /**
50
+ * AI spend caps in cost units (1,000,000 = one US dollar): per user per UTC
51
+ * day, and for the whole app per month. A cap stored in ai_spend_caps wins.
52
+ */
53
+ AI_CAP_USER_DAY: z.coerce.number().int().min(0).default(200_000),
54
+ AI_CAP_GLOBAL_MONTH: z.coerce.number().int().min(0).default(50_000_000),
55
+ // ai:end
40
56
  // mcp:begin
41
57
  /** The MCP endpoint at /mcp (api/app.ts). "off" answers it with a 404. */
42
58
  MCP: z.enum(["on", "off"]).default("on"),
@@ -0,0 +1,163 @@
1
+ /// <reference types="bun" /> // @bun
2
+ // web:begin
3
+ // The one process to run: the API under /api (and /mcp), and the built web
4
+ // app from dist/ for every other path. `dev` runs this next to Vite, which
5
+ // proxies /api to it; `start` serves both from here.
6
+ import { join, normalize } from "node:path"
7
+ // web:end
8
+ // The one process to run: the API under /api (and /mcp). `dev` runs it and // @!web
9
+ // restarts it on change; `start` serves it. // @!web
10
+ // !bun:begin
11
+ import { readFile } from "node:fs/promises" // @web
12
+ import { createServer } from "node:http"
13
+ import { Readable } from "node:stream"
14
+ // !bun:end
15
+ import { createApp } from "./app.ts"
16
+ import { pruneKv, sqlKv } from "./db/kv.ts"
17
+ import { openDb } from "./db/open.ts"
18
+ import { env } from "./env.ts"
19
+ import { createAppWorkflows } from "./workflows.ts" // @workflows
20
+
21
+ const { db, query } = openDb(env.DATABASE_PATH)
22
+ // OBSERVABILITY=on adds request logs, spans and /health/live and /health/ready.
23
+ const serviceName = "__APP_NAME__"
24
+ const observability = env.OBSERVABILITY === "on" ? { serviceName } : undefined
25
+ const app = createApp({ db, query, kv: sqlKv(db.orm), observability })
26
+ setInterval(() => pruneKv(db.orm), 60 * 60 * 1000)
27
+ // workflows:begin
28
+ // The workflow runner (api/workflows.ts): every second it takes the runs that
29
+ // are due, including any a restart cut short. The same on Bun, Deno and Node.
30
+ void createAppWorkflows(db).poll({ intervalMs: 1000 })
31
+ // workflows:end
32
+
33
+ const DIST = join(import.meta.dirname, "../dist") // @web
34
+
35
+ // bun:begin
36
+ const server = Bun.serve({
37
+ port: env.PORT,
38
+ async fetch(req, srv) { // @web
39
+ fetch(req, srv) { // @!web
40
+ const { pathname } = new URL(req.url)
41
+ if (
42
+ pathname.startsWith("/api/") ||
43
+ pathname.startsWith("/mcp") ||
44
+ (observability && pathname.startsWith("/health/"))
45
+ ) {
46
+ // Overwrite, never append: a client-set x-forwarded-for must not pick its
47
+ // own rate-limit bucket. Behind a proxy of your own, pass the proxy's
48
+ // header through instead and raise TRUST's hops in services.ts.
49
+ const headers = new Headers(req.headers)
50
+ headers.set("x-forwarded-for", srv.requestIP(req)?.address ?? "")
51
+ return app.fetch(new Request(req, { headers }))
52
+ }
53
+ // web:begin
54
+ // A file (it has an extension) or the app's index.html for its routes.
55
+ if (/\.[a-z0-9]+$/i.test(pathname)) {
56
+ const path = normalize(join(DIST, pathname))
57
+ const file = Bun.file(path)
58
+ if (path.startsWith(DIST) && (await file.exists())) return new Response(file)
59
+ return new Response("Not found", { status: 404 })
60
+ }
61
+ const index = Bun.file(join(DIST, "index.html"))
62
+ if (await index.exists()) return new Response(index)
63
+ return new Response("No web build yet: run `build`, or use `dev` and open Vite's URL.", {
64
+ status: 404,
65
+ })
66
+ // web:end
67
+ return new Response("Not found", { status: 404 }) // @!web
68
+ },
69
+ })
70
+
71
+ console.log(`Listening on ${server.url}`)
72
+ // bun:end
73
+ // !bun:begin
74
+ // web:begin
75
+ const TYPES: Record<string, string> = {
76
+ html: "text/html; charset=utf-8",
77
+ js: "text/javascript; charset=utf-8",
78
+ css: "text/css; charset=utf-8",
79
+ json: "application/json",
80
+ webmanifest: "application/manifest+json",
81
+ svg: "image/svg+xml",
82
+ png: "image/png",
83
+ jpg: "image/jpeg",
84
+ webp: "image/webp",
85
+ ico: "image/x-icon",
86
+ woff2: "font/woff2",
87
+ txt: "text/plain; charset=utf-8",
88
+ }
89
+
90
+ /** A file from dist/, or null when there is none. */
91
+ async function file(path: string): Promise<Response | null> {
92
+ const body = await readFile(path).catch(() => null)
93
+ if (!body) return null
94
+ const type = TYPES[path.slice(path.lastIndexOf(".") + 1)] ?? "application/octet-stream"
95
+ return new Response(body, { headers: { "content-type": type } })
96
+ }
97
+ // web:end
98
+
99
+ /** One request: the API, or (with the web app) a file from dist/. */
100
+ async function handle(req: Request, ip: string): Promise<Response> { // @web
101
+ function handle(req: Request, ip: string): Promise<Response> | Response { // @!web
102
+ const { pathname } = new URL(req.url)
103
+ if (
104
+ pathname.startsWith("/api/") ||
105
+ pathname.startsWith("/mcp") ||
106
+ (observability && pathname.startsWith("/health/"))
107
+ ) {
108
+ // Overwrite, never append: a client-set x-forwarded-for must not pick its
109
+ // own rate-limit bucket. Behind a proxy of your own, pass the proxy's
110
+ // header through instead and raise TRUST's hops in services.ts.
111
+ const headers = new Headers(req.headers)
112
+ headers.set("x-forwarded-for", ip)
113
+ return app.fetch(new Request(req, { headers }))
114
+ }
115
+ // web:begin
116
+ // A file (it has an extension) or the app's index.html for its routes.
117
+ if (/\.[a-z0-9]+$/i.test(pathname)) {
118
+ const path = normalize(join(DIST, pathname))
119
+ const found = path.startsWith(DIST) ? await file(path) : null
120
+ return found ?? new Response("Not found", { status: 404 })
121
+ }
122
+ const index = await file(join(DIST, "index.html"))
123
+ if (index) return index
124
+ return new Response("No web build yet: run `build`, or use `dev` and open Vite's URL.", {
125
+ status: 404,
126
+ })
127
+ // web:end
128
+ return new Response("Not found", { status: 404 }) // @!web
129
+ }
130
+
131
+ // node:http runs under Node and Deno alike: requests in, the fetch-style
132
+ // handler above, responses streamed back out.
133
+ const server = createServer(async (req, res) => {
134
+ try {
135
+ const headers = new Headers()
136
+ for (const [key, value] of Object.entries(req.headers))
137
+ if (value !== undefined) headers.set(key, Array.isArray(value) ? value.join(", ") : value)
138
+ const method = req.method ?? "GET"
139
+ const response = await handle(
140
+ new Request(`http://${req.headers.host ?? "localhost"}${req.url ?? "/"}`, {
141
+ method,
142
+ headers,
143
+ body:
144
+ method === "GET" || method === "HEAD"
145
+ ? undefined
146
+ : (Readable.toWeb(req) as unknown as ReadableStream),
147
+ // Required by fetch for a streamed request body.
148
+ duplex: "half",
149
+ } as RequestInit),
150
+ req.socket.remoteAddress ?? "",
151
+ )
152
+ // Headers iterate set-cookie once per cookie; writeHead takes a flat list.
153
+ res.writeHead(response.status, [...response.headers].flat())
154
+ if (response.body) Readable.fromWeb(response.body as never).pipe(res)
155
+ else res.end()
156
+ } catch (err) {
157
+ console.error(err)
158
+ if (!res.headersSent) res.writeHead(500, { "content-type": "application/json" })
159
+ res.end(JSON.stringify({ success: false, error: "Internal error" }))
160
+ }
161
+ })
162
+ server.listen(env.PORT, () => console.log(`Listening on http://localhost:${env.PORT}`))
163
+ // !bun:end
@@ -1,29 +1,56 @@
1
+ import { createExtractor, fakeProvider } from "@dapplelight/signet-ai" // @ai
2
+ // admin:begin
1
3
  import { type AdminContext, type Authorize, defineAdmin, roles } from "@dapplelight/signet-db/admin"
4
+ // admin:end
5
+ import { createAiSpend } from "@dapplelight/signet-db/ai-spend" // @ai
6
+ // payments:begin
2
7
  import { createEntitlements } from "@dapplelight/signet-db/entitlements"
3
- import { createGrowth } from "@dapplelight/signet-db/growth"
8
+ // payments:end
9
+ import { createGrowth } from "@dapplelight/signet-db/growth" // @growth
10
+ import { createOfferings } from "@dapplelight/signet-db/offerings" // @paywalls
11
+ // orgs:begin
4
12
  import { createOrgs } from "@dapplelight/signet-db/orgs"
13
+ // orgs:end
14
+ // privacy:begin
5
15
  import { createPrivacy } from "@dapplelight/signet-db/privacy"
16
+ // privacy:end
17
+ // payments:begin
6
18
  import { createPayments, sqlStore } from "@dapplelight/signet-payments"
7
19
  import { razorpay } from "@dapplelight/signet-payments/razorpay"
20
+ // payments:end
8
21
  import type { KeyValue } from "@dapplelight/signet-server/adapters"
22
+ // auth:begin
9
23
  import { kvRateLimitStore } from "@dapplelight/signet-server/adapters"
24
+ // auth:end
25
+ // account:begin
10
26
  import { kvApiKeyStore } from "@dapplelight/signet-server/auth/api-keys"
27
+ // account:end
28
+ // auth:begin
11
29
  import { devSmsSender, type SmsSender } from "@dapplelight/signet-server/auth/otp"
12
30
  import { kvSessionStore } from "@dapplelight/signet-server/auth/sessions"
31
+ // auth:end
32
+ // notifications:begin
13
33
  import {
14
34
  createNotifier,
15
35
  defineTemplates,
16
36
  kvNotifyStore,
17
37
  } from "@dapplelight/signet-server/notify/notifier"
38
+ // notifications:end
18
39
  import type { LevelSetting } from "@dapplelight/signet-server/observability/logger"
40
+ // notifications:begin
19
41
  import { eq } from "drizzle-orm"
20
42
  import { z } from "zod"
43
+ // notifications:end
21
44
  import type { Db } from "./db/index.ts"
22
- import * as schema from "./db/schema.ts"
23
- import { env } from "./env.ts"
24
- import { plans } from "./plans.ts"
45
+ import * as schema from "./db/schema.ts" // @notifications|payments|privacy|growth|orgs|admin|ai
46
+ import { env } from "./env.ts" // @auth
47
+ import { plans } from "./plans.ts" // @payments
48
+ import { createAppWorkflows } from "./workflows.ts" // @workflows
49
+ // payments:begin
25
50
 
26
51
  export { PLAN_DISPLAY, type PlanId, plans } from "./plans.ts"
52
+ // payments:end
53
+ // privacy:begin
27
54
 
28
55
  /** DPDP consent purposes the privacy screen lists. Bump NOTICE_VERSION when the notice text changes. */
29
56
  export const PURPOSES = [
@@ -39,6 +66,8 @@ export const PURPOSES = [
39
66
  },
40
67
  ] as const
41
68
  export const NOTICE_VERSION = "2026-01-01"
69
+ // privacy:end
70
+ // notifications:begin
42
71
 
43
72
  /** In-app notification templates. Add email, SMS or WhatsApp variants per event as you need them. */
44
73
  export const templates = defineTemplates({
@@ -53,6 +82,7 @@ export const templates = defineTemplates({
53
82
  },
54
83
  },
55
84
  },
85
+ // payments:begin
56
86
  "billing.plan_changed": {
57
87
  category: "billing",
58
88
  data: z.object({ plan: z.string() }),
@@ -64,13 +94,16 @@ export const templates = defineTemplates({
64
94
  },
65
95
  },
66
96
  },
97
+ // payments:end
67
98
  })
99
+ // notifications:end
68
100
 
69
101
  /**
70
102
  * Where the client IP comes from: server.ts overwrites x-forwarded-for with the
71
103
  * socket's address, so one hop. Behind your own proxy, see server.ts.
72
104
  */
73
105
  export const TRUST = { forwardedHops: 1 } as const
106
+ // admin:begin
74
107
 
75
108
  /** Users' columns only an admin may set: who someone is, and what they may do. */
76
109
  const ADMIN_ONLY_USER_COLUMNS = ["role", "phone"]
@@ -87,14 +120,17 @@ const adminAuthorize: Authorize<AdminContext> = (ctx, check) =>
87
120
  Object.keys(check.input ?? {}).some((k) => ADMIN_ONLY_USER_COLUMNS.includes(k))
88
121
  ? false
89
122
  : byRole(ctx, check)
123
+ // admin:end
90
124
 
91
125
  export type Deps = {
92
126
  db: Db
93
127
  /** Raw SQL with `?` placeholders, for signet-payments' store. */
94
128
  query: (sql: string, params: unknown[]) => Record<string, unknown>[]
95
129
  kv: KeyValue
130
+ // auth:begin
96
131
  /** Sends one-time codes. Default: printed to the console, development only. */
97
132
  sms?: SmsSender
133
+ // auth:end
98
134
  /** Request logs, spans and health routes. Absent: none of them, and no /health. */
99
135
  observability?: ObservabilityConfig
100
136
  }
@@ -113,8 +149,13 @@ export type ObservabilityConfig = {
113
149
  }
114
150
 
115
151
  /** Everything the routes use, built once per process. */
116
- export function createServices({ db, query, kv, sms }: Deps) {
152
+ // auth:begin
153
+ export function createServices({ db, query, kv, sms }: Deps) { // @payments
154
+ export function createServices({ db, kv, sms }: Deps) { // @!payments
155
+ // auth:end
156
+ export function createServices({ db, kv }: Deps) { // @!auth
117
157
  const orm = db.orm
158
+ // auth:begin
118
159
  const sessions = {
119
160
  cookieName: "session",
120
161
  secret: env.SESSION_SECRET,
@@ -129,6 +170,8 @@ export function createServices({ db, query, kv, sms }: Deps) {
129
170
  sender: sms ?? devSmsSender({ appEnv: env.APP_ENV }),
130
171
  rateLimit,
131
172
  }
173
+ // auth:end
174
+ // notifications:begin
132
175
  const notifier = createNotifier({
133
176
  channels: {},
134
177
  templates,
@@ -138,6 +181,8 @@ export function createServices({ db, query, kv, sms }: Deps) {
138
181
  return u ? { phone: u.phone, ...(u.email ? { email: u.email } : {}) } : null
139
182
  },
140
183
  })
184
+ // notifications:end
185
+ // payments:begin
141
186
  const entitlements = createEntitlements(db, {
142
187
  plans,
143
188
  default: "free",
@@ -167,34 +212,82 @@ export function createServices({ db, query, kv, sms }: Deps) {
167
212
  await entitlements.applyBillingEvent(event)
168
213
  },
169
214
  })
215
+ // payments:end
216
+ // ai:begin
217
+ // Spend per user and for the app, per UTC day and month, in cost units
218
+ // (1,000,000 = one US dollar). A cap an admin sets wins over these.
219
+ const aiSpend = createAiSpend(db, {
220
+ tables: { usageCounters: schema.usageCounters, aiSpendCaps: schema.spendCaps },
221
+ caps: { user: { day: env.AI_CAP_USER_DAY }, global: { month: env.AI_CAP_GLOBAL_MONTH } },
222
+ })
223
+ const ai = createExtractor({
224
+ // A canned answer, so /api/ai runs with no key and no network. Put a real
225
+ // provider here (see README, "AI"); its pricing is what the caps count.
226
+ providers: [
227
+ {
228
+ ...fakeProvider((input: string) => ({ summary: input.slice(0, 80) })),
229
+ pricing: { perCallUsd: 0.001 },
230
+ },
231
+ ],
232
+ // Checks the caps before each call and charges its cost after.
233
+ ledger: aiSpend.ledger,
234
+ })
235
+ // ai:end
170
236
  return {
171
237
  db,
172
238
  orm,
173
239
  kv,
240
+ // auth:begin
174
241
  sessions,
175
242
  rateLimit,
176
243
  otp,
177
- apiKeys: kvApiKeyStore(kv),
178
- notifier,
244
+ // auth:end
245
+ apiKeys: kvApiKeyStore(kv), // @account
246
+ notifier, // @notifications
247
+ // payments:begin
179
248
  entitlements,
180
249
  payments,
250
+ // payments:end
251
+ // privacy:begin
181
252
  privacy: createPrivacy(db, {
182
253
  tables: schema,
183
254
  // What export covers and erasure deletes, children before parents.
184
- userTables: [schema.feedback, [schema.users, schema.users.id]],
255
+ userTables: [schema.feedback, [schema.users, schema.users.id]], // @growth
256
+ userTables: [[schema.users, schema.users.id]], // @!growth
185
257
  respondWithinMs: 30 * 86_400_000,
186
258
  }),
187
- growth: createGrowth(db, { tables: schema }),
259
+ // privacy:end
260
+ growth: createGrowth(db, { tables: schema }), // @growth
261
+ // ai:begin
262
+ aiSpend,
263
+ ai,
264
+ // ai:end
265
+ // Offerings and placements: what each paywall sells (api/routes/paywall.ts). // @paywalls
266
+ offerings: createOfferings(db, { tables: schema, plans }), // @paywalls
267
+ workflows: createAppWorkflows(db), // @workflows
268
+ // orgs:begin
188
269
  // Orgs, roles (owner, admin, member) and invites. Add roles with
189
270
  // `roles: defineRoles({ ...DEFAULT_ORG_ROLES, ... })`.
190
271
  orgs: createOrgs(db, { tables: schema }),
191
272
  /** The org switch cookie: Secure everywhere but local http. */
192
273
  orgCookie: { secure: env.APP_ENV !== "development" },
274
+ // orgs:end
275
+ // admin:begin
193
276
  admin: defineAdmin(schema, {
194
277
  authorize: adminAuthorize,
195
278
  // Per table by SQL name: search, readonly, hidden columns, row actions.
196
- tables: { kv: false, idempotency_keys: false },
279
+ tables: {
280
+ kv: false,
281
+ idempotency_keys: false,
282
+ // These change through their own APIs, which keep them consistent: read only here. // @ai|paywalls|workflows
283
+ ai_spend_caps: { ops: ["list", "get"] }, // @ai
284
+ offerings: { ops: ["list", "get"] }, // @paywalls
285
+ placements: { ops: ["list", "get"] }, // @paywalls
286
+ workflow_runs: { ops: ["list", "get"] }, // @workflows
287
+ workflow_steps: { ops: ["list", "get"] }, // @workflows
288
+ },
197
289
  }),
290
+ // admin:end
198
291
  }
199
292
  }
200
293
 
@@ -0,0 +1,77 @@
1
+ CREATE TABLE `offerings` (
2
+ `id` text PRIMARY KEY NOT NULL,
3
+ `key` text NOT NULL,
4
+ `version` integer NOT NULL,
5
+ `products` text NOT NULL,
6
+ `paywall` text,
7
+ `note` text,
8
+ `created_by` text,
9
+ `created_at` integer DEFAULT (cast((julianday('now') - 2440587.5) * 86400000 as integer)) NOT NULL
10
+ );
11
+ --> statement-breakpoint
12
+ CREATE TABLE `placements` (
13
+ `placement` text PRIMARY KEY NOT NULL,
14
+ `offering` text NOT NULL,
15
+ `version` integer,
16
+ `overrides` text NOT NULL,
17
+ `experiment` text,
18
+ `updated_by` text,
19
+ `updated_at` integer DEFAULT (cast((julianday('now') - 2440587.5) * 86400000 as integer)) NOT NULL
20
+ );
21
+ --> statement-breakpoint
22
+ CREATE TABLE `ai_spend_caps` (
23
+ `id` text PRIMARY KEY NOT NULL,
24
+ `scope` text NOT NULL,
25
+ `subject` text NOT NULL,
26
+ `period` text NOT NULL,
27
+ `units` integer,
28
+ `updated_by` text,
29
+ `updated_at` integer DEFAULT (cast((julianday('now') - 2440587.5) * 86400000 as integer)) NOT NULL
30
+ );
31
+ --> statement-breakpoint
32
+ CREATE TABLE `workflow_events` (
33
+ `id` text PRIMARY KEY NOT NULL,
34
+ `name` text NOT NULL,
35
+ `run_id` text,
36
+ `payload` text,
37
+ `created_at` integer NOT NULL
38
+ );
39
+ --> statement-breakpoint
40
+ CREATE INDEX `workflow_events_name` ON `workflow_events` (`name`,`id`);--> statement-breakpoint
41
+ CREATE TABLE `workflow_runs` (
42
+ `id` text PRIMARY KEY NOT NULL,
43
+ `workflow` text NOT NULL,
44
+ `input` text,
45
+ `status` text NOT NULL,
46
+ `output` text,
47
+ `error` text,
48
+ `created_by` text,
49
+ `wake_at` integer,
50
+ `lease_owner` text,
51
+ `lease_until` integer,
52
+ `waiting_on` text,
53
+ `created_at` integer NOT NULL,
54
+ `updated_at` integer NOT NULL,
55
+ `finished_at` integer
56
+ );
57
+ --> statement-breakpoint
58
+ CREATE INDEX `workflow_runs_due` ON `workflow_runs` (`status`,`wake_at`);--> statement-breakpoint
59
+ CREATE TABLE `workflow_steps` (
60
+ `run_id` text NOT NULL,
61
+ `step_id` text NOT NULL,
62
+ `seq` integer NOT NULL,
63
+ `kind` text NOT NULL,
64
+ `status` text NOT NULL,
65
+ `output` text,
66
+ `error` text,
67
+ `attempts` integer DEFAULT 0 NOT NULL,
68
+ `wake_at` integer,
69
+ `event` text,
70
+ `event_id` text,
71
+ `approvers` text,
72
+ `summary` text,
73
+ `decided_by` text,
74
+ `started_at` integer NOT NULL,
75
+ `finished_at` integer,
76
+ PRIMARY KEY(`run_id`, `step_id`)
77
+ );