@aglyn/tenant-data-admin 1.8.0 → 1.9.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.8.0",
3
+ "version": "1.9.1",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.8.0",
29
- "@aglyn/shared-util-email": "1.8.0",
30
- "@aglyn/shared-util-fbserver": "1.8.0",
31
- "@aglyn/shared-util-first-touch": "1.8.0",
32
- "@aglyn/shared-util-http": "1.8.0",
33
- "@aglyn/shared-util-tools": "1.8.0",
28
+ "@aglyn/aglyn": "1.9.1",
29
+ "@aglyn/shared-util-email": "1.9.1",
30
+ "@aglyn/shared-util-fbserver": "1.9.1",
31
+ "@aglyn/shared-util-first-touch": "1.9.1",
32
+ "@aglyn/shared-util-http": "1.9.1",
33
+ "@aglyn/shared-util-tools": "1.9.1",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -40,7 +40,8 @@ function errorResponse(status, type, fallbackMessage, init) {
40
40
  // above it carries it too. Written out rather than looked up so this module
41
41
  // stays import-free; `api-http.spec.ts` reads the plan table and fails when
42
42
  // the two disagree.
43
- planRequired: (init)=>errorResponse(403, 'plan_required', 'API access requires the Business plan or above', init),
43
+ planRequired: (init)=>errorResponse(403, 'plan_required', // Pro since pricing v4 (AGL-4126), Business before it.
44
+ 'API access requires the Pro plan or above', init),
44
45
  insufficientScope: (scope, headers)=>errorResponse(403, 'insufficient_scope', `Missing the "${scope}" scope`, {
45
46
  code: scope,
46
47
  headers
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/api-http.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * HTTP building blocks for the customer REST API (`/api/v1`, AGL-617): a\n * consistent JSON error envelope, list/pagination helpers, and a per-key\n * rate limiter. Everything here is pure (Web `Response` + plain data), so it\n * is unit-tested directly.\n */\n\n/** Every error response is `{ error: { type, message, code?, fields? } }`. */\nexport interface ApiErrorBody {\n error: {\n type: string\n message: string\n code?: string\n /** Per-field reasons on a validation failure (AGL-901). */\n fields?: Record<string, string>\n }\n}\n\nexport interface ApiResponseInit {\n message?: string\n code?: string\n /**\n * Field id → reason, surfaced on `validation_failed`. Additive: clients\n * that only read `type`/`message` are unaffected.\n */\n fields?: Record<string, string>\n headers?: Record<string, string>\n}\n\nfunction errorResponse(\n status: number,\n type: string,\n fallbackMessage: string,\n init?: ApiResponseInit,\n): Response {\n const error: ApiErrorBody['error'] = {\n type,\n message: init?.message ?? fallbackMessage,\n }\n if (init?.code) error.code = init.code\n if (init?.fields && Object.keys(init.fields).length) error.fields = init.fields\n return Response.json({ error }, { status, headers: init?.headers })\n}\n\n/** Canonical error responses. Pass `{ headers }` to carry rate-limit headers. */\nexport const ApiErrors = {\n unauthorized: (init?: ApiResponseInit) =>\n errorResponse(401, 'unauthorized', 'Invalid or missing API key', init),\n // The plan named is the cheapest one carrying `apiAccess`, and every plan\n // above it carries it too. Written out rather than looked up so this module\n // stays import-free; `api-http.spec.ts` reads the plan table and fails when\n // the two disagree.\n planRequired: (init?: ApiResponseInit) =>\n errorResponse(\n 403,\n 'plan_required',\n 'API access requires the Business plan or above',\n init,\n ),\n insufficientScope: (scope: string, headers?: Record<string, string>) =>\n errorResponse(403, 'insufficient_scope', `Missing the \"${scope}\" scope`, {\n code: scope,\n headers,\n }),\n forbidden: (init?: ApiResponseInit) =>\n errorResponse(403, 'forbidden', 'Not permitted', init),\n notFound: (init?: ApiResponseInit) =>\n errorResponse(404, 'not_found', 'Not found', init),\n badRequest: (init?: ApiResponseInit) =>\n errorResponse(400, 'bad_request', 'Bad request', init),\n /**\n * The request conflicts with work already in flight (AGL-1709). Used by the\n * idempotency claim for the one case it must fail CLOSED: an identical\n * attempt that has taken the claim but not yet settled. Letting the second\n * caller through is the duplicate the key exists to prevent, so it is\n * refused rather than served — and a client that reads `type` gets a\n * retriable answer rather than a mystery.\n */\n conflict: (init?: ApiResponseInit) =>\n errorResponse(409, 'conflict', 'Conflicts with the current state', init),\n methodNotAllowed: (init?: ApiResponseInit) =>\n errorResponse(405, 'method_not_allowed', 'Method not allowed', init),\n /**\n * The three refusals an upload can produce that a JSON-only API never could\n * (AGL-2463). Built here rather than at the call site so `/v1` keeps ONE\n * error envelope — a client branching on `error.type` must not meet a bare\n * `{ error: '<sentence>' }` on the one surface that handles bytes.\n */\n unsupportedMediaType: (init?: ApiResponseInit) =>\n errorResponse(415, 'unsupported_media_type', 'Unsupported file type', init),\n payloadTooLarge: (init?: ApiResponseInit) =>\n errorResponse(413, 'payload_too_large', 'File too large', init),\n /**\n * 451, matching the console's own media chokepoints: the asset is refused\n * because its content hash is on the takedown ledger, which is a legal\n * verdict rather than a permission or a quota.\n */\n unavailableForLegalReasons: (init?: ApiResponseInit) =>\n errorResponse(\n 451,\n 'unavailable_for_legal_reasons',\n 'This file has been removed and cannot be uploaded',\n init,\n ),\n rateLimited: (retryAfterSec: number, headers?: Record<string, string>) =>\n errorResponse(429, 'rate_limited', 'Too many requests', {\n headers: { 'Retry-After': String(Math.max(1, retryAfterSec)), ...headers },\n }),\n internal: (init?: ApiResponseInit) =>\n errorResponse(500, 'internal_error', 'Something went wrong', init),\n}\n\n/**\n * Re-emit `response` with `headers` merged in — the escape hatch for a\n * refusal built by a shared helper that knows nothing about this request's\n * rate-limit budget (the lockdown 423, AGL-1596). Status, body and the\n * response's own headers are preserved; `set` overwrites rather than\n * appends, so a header named on both sides appears exactly once (the passed\n * value wins) and no client ever reads a doubled `X-RateLimit-Remaining`.\n */\nexport function withResponseHeaders(\n response: Response,\n headers: Record<string, string>,\n): Response {\n const merged = new Headers(response.headers)\n for (const [name, value] of Object.entries(headers)) merged.set(name, value)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: merged,\n })\n}\n\n/** Success JSON with an optional status + headers (e.g. rate-limit headers). */\nexport function apiJson(\n data: unknown,\n init?: { status?: number; headers?: Record<string, string> },\n): Response {\n return Response.json(data, {\n status: init?.status ?? 200,\n headers: init?.headers,\n })\n}\n\n// ── Pagination ──────────────────────────────────────────────────────────────\n\nexport const DEFAULT_PAGE_LIMIT = 25\nexport const MAX_PAGE_LIMIT = 100\n\n/** Clamp a `?limit=` value to [1, MAX], defaulting when absent/invalid. */\nexport function parseLimit(raw: string | null | undefined): number {\n const n = Number(raw)\n if (!Number.isFinite(n) || n < 1) return DEFAULT_PAGE_LIMIT\n return Math.min(Math.floor(n), MAX_PAGE_LIMIT)\n}\n\n/** Opaque cursor = base64url of an underlying key (e.g. a Firestore doc id). */\nexport function encodeCursor(value: string): string {\n return Buffer.from(value, 'utf8').toString('base64url')\n}\n\nexport function decodeCursor(\n cursor: string | null | undefined,\n): string | undefined {\n if (!cursor) return undefined\n try {\n const decoded = Buffer.from(cursor, 'base64url').toString('utf8')\n return decoded.length > 0 ? decoded : undefined\n } catch {\n return undefined\n }\n}\n\n/** List envelope: `{ data, next_cursor, has_more }`. */\nexport function listResponse(\n data: unknown[],\n nextCursor: string | null,\n headers?: Record<string, string>,\n): Response {\n return apiJson(\n { object: 'list', data, next_cursor: nextCursor, has_more: nextCursor != null },\n { headers },\n )\n}\n\n// ── Rate limiting (fixed window, per key) ───────────────────────────────────\n\nexport interface RateLimitState {\n count: number\n windowStartMs: number\n}\n\nexport interface RateLimitResult {\n allowed: boolean\n limit: number\n remaining: number\n resetMs: number\n}\n\nexport interface RateLimitOptions {\n limit?: number\n windowMs?: number\n now?: number\n store?: Map<string, RateLimitState>\n}\n\nexport const DEFAULT_RATE_LIMIT = 120\nexport const DEFAULT_RATE_WINDOW_MS = 60_000\n\n// Per-instance store. Serverless instances are ephemeral, so this blunts\n// bursts rather than enforcing a global cap (matches the app's other\n// limiters); a durable per-key counter can back it later.\nconst defaultStore = new Map<string, RateLimitState>()\n\n/** Count one request against `key`'s fixed window. `now`/`store` injectable. */\nexport function checkRateLimit(\n key: string,\n options?: RateLimitOptions,\n): RateLimitResult {\n const limit = options?.limit ?? DEFAULT_RATE_LIMIT\n const windowMs = options?.windowMs ?? DEFAULT_RATE_WINDOW_MS\n const now = options?.now ?? Date.now()\n const store = options?.store ?? defaultStore\n\n const state = store.get(key)\n if (!state || now - state.windowStartMs >= windowMs) {\n store.set(key, { count: 1, windowStartMs: now })\n return { allowed: true, limit, remaining: limit - 1, resetMs: now + windowMs }\n }\n state.count += 1\n return {\n allowed: state.count <= limit,\n limit,\n remaining: Math.max(0, limit - state.count),\n resetMs: state.windowStartMs + windowMs,\n }\n}\n\n/**\n * Report `key`'s window WITHOUT counting a request against it (AGL-2414).\n *\n * `checkRateLimit` fuses \"is there budget\" with \"spend some\", which is the\n * right shape when every call is a request to be counted. It is the wrong\n * shape when the budget meters something the caller has not done *yet* and\n * may never do — `/api/v1` gates the Firestore key lookup on an IP's budget\n * of *unproductive* lookups, so it has to ask before the lookup and only\n * charge if the lookup came back empty. Asking with `checkRateLimit` would\n * charge every request, including the successful ones, which is precisely the\n * customer-visible cap that budget must not become.\n *\n * `allowed` answers \"would the NEXT call be admitted\", i.e. `count < limit` —\n * one off from `checkRateLimit`'s post-increment `count <= limit`, and the\n * same verdict for the same request. `remaining` is what is left now, so an\n * untouched or expired window reports the full `limit` rather than\n * `limit - 1`.\n */\nexport function peekRateLimit(\n key: string,\n options?: RateLimitOptions,\n): RateLimitResult {\n const limit = options?.limit ?? DEFAULT_RATE_LIMIT\n const windowMs = options?.windowMs ?? DEFAULT_RATE_WINDOW_MS\n const now = options?.now ?? Date.now()\n const store = options?.store ?? defaultStore\n\n const state = store.get(key)\n if (!state || now - state.windowStartMs >= windowMs) {\n return { allowed: true, limit, remaining: limit, resetMs: now + windowMs }\n }\n return {\n allowed: state.count < limit,\n limit,\n remaining: Math.max(0, limit - state.count),\n resetMs: state.windowStartMs + windowMs,\n }\n}\n\n/**\n * Rate-limit headers, in BOTH spellings (AGL-2727).\n *\n * `X-RateLimit-*` is the de-facto set this API has always sent, and it is kept\n * verbatim — including `Reset` as an epoch second — because integrations are\n * already reading it and a header that changes meaning under a client is worse\n * than one it has to learn.\n *\n * `RateLimit-*` is RFC 9331, which is what a caller that was not written\n * against this specific API looks for, and increasingly what an agent looks\n * for. Same numbers, standard spelling. Its `Reset` is SECONDS REMAINING, not\n * an epoch — that is the RFC's own choice, and the better one: a duration is\n * read against the caller's clock rather than ours, so a skewed clock cannot\n * turn \"wait 12 seconds\" into \"wait until 1970\".\n *\n * ⚠️ Both are computed from the SAME `result`, so they can never disagree.\n * Two independently-derived budgets on one response is a bug that reads as a\n * rounding error.\n */\nexport function rateLimitHeaders(\n result: RateLimitResult,\n now: number = Date.now(),\n): Record<string, string> {\n const remainingSeconds = Math.max(0, Math.ceil((result.resetMs - now) / 1000))\n return {\n 'X-RateLimit-Limit': String(result.limit),\n 'X-RateLimit-Remaining': String(result.remaining),\n 'X-RateLimit-Reset': String(Math.ceil(result.resetMs / 1000)),\n 'RateLimit-Limit': String(result.limit),\n 'RateLimit-Remaining': String(result.remaining),\n 'RateLimit-Reset': String(remainingSeconds),\n }\n}\n"],"names":["errorResponse","status","type","fallbackMessage","init","error","message","code","fields","Object","keys","length","Response","json","headers","ApiErrors","unauthorized","planRequired","insufficientScope","scope","forbidden","notFound","badRequest","conflict","methodNotAllowed","unsupportedMediaType","payloadTooLarge","unavailableForLegalReasons","rateLimited","retryAfterSec","String","Math","max","internal","withResponseHeaders","response","merged","Headers","name","value","entries","set","body","statusText","apiJson","data","DEFAULT_PAGE_LIMIT","MAX_PAGE_LIMIT","parseLimit","raw","n","Number","isFinite","min","floor","encodeCursor","Buffer","from","toString","decodeCursor","cursor","undefined","decoded","listResponse","nextCursor","object","next_cursor","has_more","DEFAULT_RATE_LIMIT","DEFAULT_RATE_WINDOW_MS","defaultStore","Map","checkRateLimit","key","options","limit","windowMs","now","Date","store","state","get","windowStartMs","count","allowed","remaining","resetMs","peekRateLimit","rateLimitHeaders","result","remainingSeconds","ceil"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAED,4EAA4E;AAsB5E,SAASA,cACPC,MAAc,EACdC,IAAY,EACZC,eAAuB,EACvBC,IAAsB;;IAEtB,MAAMC,QAA+B;QACnCH;QACAI,OAAO,UAAEF,wBAAAA,KAAME,OAAO,mBAAIH;IAC5B;IACA,IAAIC,wBAAAA,KAAMG,IAAI,EAAEF,MAAME,IAAI,GAAGH,KAAKG,IAAI;IACtC,IAAIH,CAAAA,wBAAAA,KAAMI,MAAM,KAAIC,OAAOC,IAAI,CAACN,KAAKI,MAAM,EAAEG,MAAM,EAAEN,MAAMG,MAAM,GAAGJ,KAAKI,MAAM;IAC/E,OAAOI,SAASC,IAAI,CAAC;QAAER;IAAM,GAAG;QAAEJ;QAAQa,OAAO,EAAEV,wBAAAA,KAAMU,OAAO;IAAC;AACnE;AAEA,+EAA+E,GAC/E,OAAO,MAAMC,YAAY;IACvBC,cAAc,CAACZ,OACbJ,cAAc,KAAK,gBAAgB,8BAA8BI;IACnE,0EAA0E;IAC1E,4EAA4E;IAC5E,4EAA4E;IAC5E,oBAAoB;IACpBa,cAAc,CAACb,OACbJ,cACE,KACA,iBACA,kDACAI;IAEJc,mBAAmB,CAACC,OAAeL,UACjCd,cAAc,KAA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AEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASY,iBACdC,MAAuB,EACvBZ,MAAcC,KAAKD,GAAG,EAAE;IAExB,MAAMa,mBAAmB3D,KAAKC,GAAG,CAAC,GAAGD,KAAK4D,IAAI,CAAC,AAACF,CAAAA,OAAOH,OAAO,GAAGT,GAAE,IAAK;IACxE,OAAO;QACL,qBAAqB/C,OAAO2D,OAAOd,KAAK;QACxC,yBAAyB7C,OAAO2D,OAAOJ,SAAS;QAChD,qBAAqBvD,OAAOC,KAAK4D,IAAI,CAACF,OAAOH,OAAO,GAAG;QACvD,mBAAmBxD,OAAO2D,OAAOd,KAAK;QACtC,uBAAuB7C,OAAO2D,OAAOJ,SAAS;QAC9C,mBAAmBvD,OAAO4D;IAC5B;AACF"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/api-http.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/**\n * HTTP building blocks for the customer REST API (`/api/v1`, AGL-617): a\n * consistent JSON error envelope, list/pagination helpers, and a per-key\n * rate limiter. Everything here is pure (Web `Response` + plain data), so it\n * is unit-tested directly.\n */\n\n/** Every error response is `{ error: { type, message, code?, fields? } }`. */\nexport interface ApiErrorBody {\n error: {\n type: string\n message: string\n code?: string\n /** Per-field reasons on a validation failure (AGL-901). */\n fields?: Record<string, string>\n }\n}\n\nexport interface ApiResponseInit {\n message?: string\n code?: string\n /**\n * Field id → reason, surfaced on `validation_failed`. Additive: clients\n * that only read `type`/`message` are unaffected.\n */\n fields?: Record<string, string>\n headers?: Record<string, string>\n}\n\nfunction errorResponse(\n status: number,\n type: string,\n fallbackMessage: string,\n init?: ApiResponseInit,\n): Response {\n const error: ApiErrorBody['error'] = {\n type,\n message: init?.message ?? fallbackMessage,\n }\n if (init?.code) error.code = init.code\n if (init?.fields && Object.keys(init.fields).length) error.fields = init.fields\n return Response.json({ error }, { status, headers: init?.headers })\n}\n\n/** Canonical error responses. Pass `{ headers }` to carry rate-limit headers. */\nexport const ApiErrors = {\n unauthorized: (init?: ApiResponseInit) =>\n errorResponse(401, 'unauthorized', 'Invalid or missing API key', init),\n // The plan named is the cheapest one carrying `apiAccess`, and every plan\n // above it carries it too. Written out rather than looked up so this module\n // stays import-free; `api-http.spec.ts` reads the plan table and fails when\n // the two disagree.\n planRequired: (init?: ApiResponseInit) =>\n errorResponse(\n 403,\n 'plan_required',\n // Pro since pricing v4 (AGL-4126), Business before it.\n 'API access requires the Pro plan or above',\n init,\n ),\n insufficientScope: (scope: string, headers?: Record<string, string>) =>\n errorResponse(403, 'insufficient_scope', `Missing the \"${scope}\" scope`, {\n code: scope,\n headers,\n }),\n forbidden: (init?: ApiResponseInit) =>\n errorResponse(403, 'forbidden', 'Not permitted', init),\n notFound: (init?: ApiResponseInit) =>\n errorResponse(404, 'not_found', 'Not found', init),\n badRequest: (init?: ApiResponseInit) =>\n errorResponse(400, 'bad_request', 'Bad request', init),\n /**\n * The request conflicts with work already in flight (AGL-1709). Used by the\n * idempotency claim for the one case it must fail CLOSED: an identical\n * attempt that has taken the claim but not yet settled. Letting the second\n * caller through is the duplicate the key exists to prevent, so it is\n * refused rather than served — and a client that reads `type` gets a\n * retriable answer rather than a mystery.\n */\n conflict: (init?: ApiResponseInit) =>\n errorResponse(409, 'conflict', 'Conflicts with the current state', init),\n methodNotAllowed: (init?: ApiResponseInit) =>\n errorResponse(405, 'method_not_allowed', 'Method not allowed', init),\n /**\n * The three refusals an upload can produce that a JSON-only API never could\n * (AGL-2463). Built here rather than at the call site so `/v1` keeps ONE\n * error envelope — a client branching on `error.type` must not meet a bare\n * `{ error: '<sentence>' }` on the one surface that handles bytes.\n */\n unsupportedMediaType: (init?: ApiResponseInit) =>\n errorResponse(415, 'unsupported_media_type', 'Unsupported file type', init),\n payloadTooLarge: (init?: ApiResponseInit) =>\n errorResponse(413, 'payload_too_large', 'File too large', init),\n /**\n * 451, matching the console's own media chokepoints: the asset is refused\n * because its content hash is on the takedown ledger, which is a legal\n * verdict rather than a permission or a quota.\n */\n unavailableForLegalReasons: (init?: ApiResponseInit) =>\n errorResponse(\n 451,\n 'unavailable_for_legal_reasons',\n 'This file has been removed and cannot be uploaded',\n init,\n ),\n rateLimited: (retryAfterSec: number, headers?: Record<string, string>) =>\n errorResponse(429, 'rate_limited', 'Too many requests', {\n headers: { 'Retry-After': String(Math.max(1, retryAfterSec)), ...headers },\n }),\n internal: (init?: ApiResponseInit) =>\n errorResponse(500, 'internal_error', 'Something went wrong', init),\n}\n\n/**\n * Re-emit `response` with `headers` merged in — the escape hatch for a\n * refusal built by a shared helper that knows nothing about this request's\n * rate-limit budget (the lockdown 423, AGL-1596). Status, body and the\n * response's own headers are preserved; `set` overwrites rather than\n * appends, so a header named on both sides appears exactly once (the passed\n * value wins) and no client ever reads a doubled `X-RateLimit-Remaining`.\n */\nexport function withResponseHeaders(\n response: Response,\n headers: Record<string, string>,\n): Response {\n const merged = new Headers(response.headers)\n for (const [name, value] of Object.entries(headers)) merged.set(name, value)\n return new Response(response.body, {\n status: response.status,\n statusText: response.statusText,\n headers: merged,\n })\n}\n\n/** Success JSON with an optional status + headers (e.g. rate-limit headers). */\nexport function apiJson(\n data: unknown,\n init?: { status?: number; headers?: Record<string, string> },\n): Response {\n return Response.json(data, {\n status: init?.status ?? 200,\n headers: init?.headers,\n })\n}\n\n// ── Pagination ──────────────────────────────────────────────────────────────\n\nexport const DEFAULT_PAGE_LIMIT = 25\nexport const MAX_PAGE_LIMIT = 100\n\n/** Clamp a `?limit=` value to [1, MAX], defaulting when absent/invalid. */\nexport function parseLimit(raw: string | null | undefined): number {\n const n = Number(raw)\n if (!Number.isFinite(n) || n < 1) return DEFAULT_PAGE_LIMIT\n return Math.min(Math.floor(n), MAX_PAGE_LIMIT)\n}\n\n/** Opaque cursor = base64url of an underlying key (e.g. a Firestore doc id). */\nexport function encodeCursor(value: string): string {\n return Buffer.from(value, 'utf8').toString('base64url')\n}\n\nexport function decodeCursor(\n cursor: string | null | undefined,\n): string | undefined {\n if (!cursor) return undefined\n try {\n const decoded = Buffer.from(cursor, 'base64url').toString('utf8')\n return decoded.length > 0 ? decoded : undefined\n } catch {\n return undefined\n }\n}\n\n/** List envelope: `{ data, next_cursor, has_more }`. */\nexport function listResponse(\n data: unknown[],\n nextCursor: string | null,\n headers?: Record<string, string>,\n): Response {\n return apiJson(\n { object: 'list', data, next_cursor: nextCursor, has_more: nextCursor != null },\n { headers },\n )\n}\n\n// ── Rate limiting (fixed window, per key) ───────────────────────────────────\n\nexport interface RateLimitState {\n count: number\n windowStartMs: number\n}\n\nexport interface RateLimitResult {\n allowed: boolean\n limit: number\n remaining: number\n resetMs: number\n}\n\nexport interface RateLimitOptions {\n limit?: number\n windowMs?: number\n now?: number\n store?: Map<string, RateLimitState>\n}\n\nexport const DEFAULT_RATE_LIMIT = 120\nexport const DEFAULT_RATE_WINDOW_MS = 60_000\n\n// Per-instance store. Serverless instances are ephemeral, so this blunts\n// bursts rather than enforcing a global cap (matches the app's other\n// limiters); a durable per-key counter can back it later.\nconst defaultStore = new Map<string, RateLimitState>()\n\n/** Count one request against `key`'s fixed window. `now`/`store` injectable. */\nexport function checkRateLimit(\n key: string,\n options?: RateLimitOptions,\n): RateLimitResult {\n const limit = options?.limit ?? DEFAULT_RATE_LIMIT\n const windowMs = options?.windowMs ?? DEFAULT_RATE_WINDOW_MS\n const now = options?.now ?? Date.now()\n const store = options?.store ?? defaultStore\n\n const state = store.get(key)\n if (!state || now - state.windowStartMs >= windowMs) {\n store.set(key, { count: 1, windowStartMs: now })\n return { allowed: true, limit, remaining: limit - 1, resetMs: now + windowMs }\n }\n state.count += 1\n return {\n allowed: state.count <= limit,\n limit,\n remaining: Math.max(0, limit - state.count),\n resetMs: state.windowStartMs + windowMs,\n }\n}\n\n/**\n * Report `key`'s window WITHOUT counting a request against it (AGL-2414).\n *\n * `checkRateLimit` fuses \"is there budget\" with \"spend some\", which is the\n * right shape when every call is a request to be counted. It is the wrong\n * shape when the budget meters something the caller has not done *yet* and\n * may never do — `/api/v1` gates the Firestore key lookup on an IP's budget\n * of *unproductive* lookups, so it has to ask before the lookup and only\n * charge if the lookup came back empty. Asking with `checkRateLimit` would\n * charge every request, including the successful ones, which is precisely the\n * customer-visible cap that budget must not become.\n *\n * `allowed` answers \"would the NEXT call be admitted\", i.e. `count < limit` —\n * one off from `checkRateLimit`'s post-increment `count <= limit`, and the\n * same verdict for the same request. `remaining` is what is left now, so an\n * untouched or expired window reports the full `limit` rather than\n * `limit - 1`.\n */\nexport function peekRateLimit(\n key: string,\n options?: RateLimitOptions,\n): RateLimitResult {\n const limit = options?.limit ?? DEFAULT_RATE_LIMIT\n const windowMs = options?.windowMs ?? DEFAULT_RATE_WINDOW_MS\n const now = options?.now ?? Date.now()\n const store = options?.store ?? defaultStore\n\n const state = store.get(key)\n if (!state || now - state.windowStartMs >= windowMs) {\n return { allowed: true, limit, remaining: limit, resetMs: now + windowMs }\n }\n return {\n allowed: state.count < limit,\n limit,\n remaining: Math.max(0, limit - state.count),\n resetMs: state.windowStartMs + windowMs,\n }\n}\n\n/**\n * Rate-limit headers, in BOTH spellings (AGL-2727).\n *\n * `X-RateLimit-*` is the de-facto set this API has always sent, and it is kept\n * verbatim — including `Reset` as an epoch second — because integrations are\n * already reading it and a header that changes meaning under a client is worse\n * than one it has to learn.\n *\n * `RateLimit-*` is RFC 9331, which is what a caller that was not written\n * against this specific API looks for, and increasingly what an agent looks\n * for. Same numbers, standard spelling. Its `Reset` is SECONDS REMAINING, not\n * an epoch — that is the RFC's own choice, and the better one: a duration is\n * read against the caller's clock rather than ours, so a skewed clock cannot\n * turn \"wait 12 seconds\" into \"wait until 1970\".\n *\n * ⚠️ Both are computed from the SAME `result`, so they can never disagree.\n * Two independently-derived budgets on one response is a bug that reads as a\n * rounding error.\n */\nexport function rateLimitHeaders(\n result: RateLimitResult,\n now: number = Date.now(),\n): Record<string, string> {\n const remainingSeconds = Math.max(0, Math.ceil((result.resetMs - now) / 1000))\n return {\n 'X-RateLimit-Limit': String(result.limit),\n 'X-RateLimit-Remaining': String(result.remaining),\n 'X-RateLimit-Reset': String(Math.ceil(result.resetMs / 1000)),\n 'RateLimit-Limit': String(result.limit),\n 'RateLimit-Remaining': String(result.remaining),\n 'RateLimit-Reset': String(remainingSeconds),\n }\n}\n"],"names":["errorResponse","status","type","fallbackMessage","init","error","message","code","fields","Object","keys","length","Response","json","headers","ApiErrors","unauthorized","planRequired","insufficientScope","scope","forbidden","notFound","badRequest","conflict","methodNotAllowed","unsupportedMediaType","payloadTooLarge","unavailableForLegalReasons","rateLimited","retryAfterSec","String","Math","max","internal","withResponseHeaders","response","merged","Headers","name","value","entries","set","body","statusText","apiJson","data","DEFAULT_PAGE_LIMIT","MAX_PAGE_LIMIT","parseLimit","raw","n","Number","isFinite","min","floor","encodeCursor","Buffer","from","toString","decodeCursor","cursor","undefined","decoded","listResponse","nextCursor","object","next_cursor","has_more","DEFAULT_RATE_LIMIT","DEFAULT_RATE_WINDOW_MS","defaultStore","Map","checkRateLimit","key","options","limit","windowMs","now","Date","store","state","get","windowStartMs","count","allowed","remaining","resetMs","peekRateLimit","rateLimitHeaders","result","remainingSeconds","ceil"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;CAKC,GAED,4EAA4E;AAsB5E,SAASA,cACPC,MAAc,EACdC,IAAY,EACZC,eAAuB,EACvBC,IAAsB;;IAEtB,MAAMC,QAA+B;QACnCH;QACAI,OAAO,UAAEF,wBAAAA,KAAME,OAAO,mBAAIH;IAC5B;IACA,IAAIC,wBAAAA,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,EACXC,OAA0B;;IAE1B,MAAMC,gBAAQD,2BAAAA,QAASC,KAAK,mBAAIP;IAChC,MAAMQ,oBAAWF,2BAAAA,QAASE,QAAQ,oBAAIP;IACtC,MAAMQ,eAAMH,2BAAAA,QAASG,GAAG,oBAAIC,KAAKD,GAAG;IACpC,MAAME,iBAAQL,2BAAAA,QAASK,KAAK,oBAAIT;IAEhC,MAAMU,QAAQD,MAAME,GAAG,CAACR;IACxB,IAAI,CAACO,SAASH,MAAMG,MAAME,aAAa,IAAIN,UAAU;QACnD,OAAO;YAAEQ,SAAS;YAAMT;YAAOU,WAAWV;YAAOW,SAAST,MAAMD;QAAS;IAC3E;IACA,OAAO;QACLQ,SAASJ,MAAMG,KAAK,GAAGR;QACvBA;QACAU,WAAWtD,KAAKC,GAAG,CAAC,GAAG2C,QAAQK,MAAMG,KAAK;QAC1CG,SAASN,MAAME,aAAa,GAAGN;IACjC;AACF;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASY,iBACdC,MAAuB,EACvBZ,MAAcC,KAAKD,GAAG,EAAE;IAExB,MAAMa,mBAAmB3D,KAAKC,GAAG,CAAC,GAAGD,KAAK4D,IAAI,CAAC,AAACF,CAAAA,OAAOH,OAAO,GAAGT,GAAE,IAAK;IACxE,OAAO;QACL,qBAAqB/C,OAAO2D,OAAOd,KAAK;QACxC,yBAAyB7C,OAAO2D,OAAOJ,SAAS;QAChD,qBAAqBvD,OAAOC,KAAK4D,IAAI,CAACF,OAAOH,OAAO,GAAG;QACvD,mBAAmBxD,OAAO2D,OAAOd,KAAK;QACtC,uBAAuB7C,OAAO2D,OAAOJ,SAAS;QAC9C,mBAAmBvD,OAAO4D;IAC5B;AACF"}
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- import { type AiTierId, type OrgPlan } from '@aglyn/aglyn/server';
17
+ import { type OrgPlan } from '@aglyn/aglyn/server';
18
18
  import { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd, type AddonKind } from '@aglyn/aglyn/app-utils/bundle-intent';
19
19
  export { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd, type AddonKind };
20
20
  /**
@@ -24,10 +24,10 @@ export { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd, type A
24
24
  * one subscription, so every kind has a monthly and a yearly price
25
25
  * (Stripe allows a single interval per subscription; annual orgs attach
26
26
  * the `_YEARLY` variants). Seat/member/dataset/host prices are per-plan;
27
- * POS registers, the Event Calendar and Site Care (AGL-3954) are flat; the
28
- * Aglyn AI add-on is priced per TIER (AGL-3965, `STRIPE_PRICE_AI_{TIER}`),
29
- * on any paid plan. Prices are minted by `tools/scripts/setup-stripe.mjs` —
30
- * keep the three in sync.
27
+ * POS registers, the Event Calendar, Site Care (AGL-3954) and Aglyn AI
28
+ * credit blocks (AGL-4144, `STRIPE_PRICE_AI_CREDITS`, on any paid plan) are
29
+ * flat. Prices are minted by `tools/scripts/setup-stripe.mjs` — keep the
30
+ * three in sync.
31
31
  */
32
32
  export type BillingInterval = 'month' | 'year';
33
33
  /**
@@ -48,54 +48,26 @@ export type BillingInterval = 'month' | 'year';
48
48
  * reintroducing it: `free` has nothing to sell and `enterprise` is quoted
49
49
  * per deal (no `STRIPE_PRICE_ENTERPRISE_*` exists), so everything else is
50
50
  * by definition a paid, priced plan.
51
+ *
52
+ * Since pricing v4 (2026-11-03, AGL-4126) that is Starter and Pro. Business,
53
+ * Scale, Advanced and Agency are retired: their prices are archived and
54
+ * their env removed, and no subscription carried one when v4 shipped, so
55
+ * nothing is left on Stripe for the read-back to recognise.
51
56
  */
52
57
  export declare const PAID_PLANS: readonly OrgPlan[];
53
- /**
54
- * The Stripe price id of an Aglyn AI tier (AGL-3965):
55
- * `STRIPE_PRICE_AI_{TIER}[_YEARLY]`, lookup key `aglyn_ai_{tier}[_yearly]`.
56
- * The same price on every plan; null when the env isn't configured.
57
- */
58
- export declare function aiTierPriceId(tier: AiTierId, interval: BillingInterval): string | null;
59
- /**
60
- * The per-plan AI add-on price sold before tiers existed
61
- * (`STRIPE_PRICE_{PLAN}_AI_ADDON[_YEARLY]`, AGL-2897). Never sold again; read
62
- * only so an item still carrying one is recognised as the add-on and as the
63
- * tier with its price and band until `migrate-ai-addon-tiers.mjs` moves it.
64
- */
65
- export declare function legacyAiAddonPriceId(plan: OrgPlan, interval: BillingInterval): string | null;
66
- /**
67
- * Which Aglyn AI tier a price id sells (AGL-3965): a tier price, or a legacy
68
- * per-plan add-on price read as the tier with the same price and band
69
- * (`LEGACY_AI_ADDON_TIER_BY_PLAN`). Null for anything else.
70
- */
71
- export declare function aiTierFromPriceId(priceId: string | null | undefined): AiTierId | null;
72
- /**
73
- * The tier a subscription's items carry (AGL-3965), or null when none is an
74
- * Aglyn AI item with a quantity. Written to `org.aiTier` beside the
75
- * `seatAddons` map `addonQuantitiesFromItems` derives from the same items.
76
- */
77
- export declare function aiTierFromItems(items: ReadonlyArray<{
78
- price?: {
79
- id?: string;
80
- } | null;
81
- quantity?: number | null;
82
- }> | null | undefined): AiTierId | null;
83
58
  /**
84
59
  * The Stripe price id for an add-on kind on a plan at a billing interval;
85
60
  * null when the plan doesn't sell it (free) or the env isn't configured.
86
- *
87
- * `tier` picks the Aglyn AI tier; absent, the tier a plan-named purchase
88
- * means (`defaultAiTierForPlan`). Ignored for every other kind.
89
61
  */
90
- export declare function addonPriceId(kind: AddonKind, plan: OrgPlan, interval: BillingInterval, tier?: AiTierId | null): string | null;
62
+ export declare function addonPriceId(kind: AddonKind, plan: OrgPlan, interval: BillingInterval): string | null;
91
63
  /**
92
64
  * The env var that holds an add-on's price id on a plan at an interval, or
93
65
  * null where the plan sells no such price. Named on its own so a checkout
94
66
  * that Stripe refuses can say which variable points at a missing price.
95
- * For the Aglyn AI add-on it is the tier's (`STRIPE_PRICE_AI_{TIER}`,
96
- * AGL-3965), `tier` read as `addonPriceId` reads it.
67
+ * For Aglyn AI credit blocks it is `STRIPE_PRICE_AI_CREDITS[_YEARLY]`
68
+ * (AGL-4144), on a plan that sells them.
97
69
  */
98
- export declare function addonPriceEnvName(kind: AddonKind, plan: OrgPlan, interval: BillingInterval, tier?: AiTierId | null): string | null;
70
+ export declare function addonPriceEnvName(kind: AddonKind, plan: OrgPlan, interval: BillingInterval): string | null;
99
71
  /**
100
72
  * Reverse map: which add-on kind a subscription item's price id sells.
101
73
  * Null for non-add-on prices (the base plan item, unknown prices).
@@ -103,12 +75,12 @@ export declare function addonPriceEnvName(kind: AddonKind, plan: OrgPlan, interv
103
75
  export declare function addonKindFromPriceId(priceId: string | null | undefined): AddonKind | null;
104
76
  /**
105
77
  * The price an add-on item moves to on a target plan/interval: the kind's
106
- * price there, and for the Aglyn AI add-on the SAME tier the item carries
107
- * now (AGL-3965) — a tier is chosen on its own, so a plan change re-prices
108
- * only its interval, and a legacy per-plan item becomes the tier with its
109
- * price and band.
78
+ * price there. Aglyn AI credit blocks are one flat price per interval
79
+ * (AGL-4144), so a plan change re-prices only their interval. The current
80
+ * price is accepted so a caller states what it is moving from; no kind needs
81
+ * it to choose the target any more.
110
82
  */
111
- export declare function addonTargetPriceId(kind: AddonKind, plan: OrgPlan, interval: BillingInterval, currentPriceId: string | null | undefined): string | null;
83
+ export declare function addonTargetPriceId(kind: AddonKind, plan: OrgPlan, interval: BillingInterval, _currentPriceId?: string | null): string | null;
112
84
  /**
113
85
  * The BASE plan's Stripe price id at an interval
114
86
  * (`STRIPE_PRICE_{PLAN}[_YEARLY]`); null for `free`, for the custom-priced
@@ -15,13 +15,15 @@
15
15
  * limitations under the License.
16
16
  */ import { SELF_SERVE_PLANS } from "@aglyn/aglyn/server";
17
17
  import { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd } from "@aglyn/aglyn/app-utils/bundle-intent";
18
- // The Aglyn AI tiers (AGL-3965) by their own module rather than the server
19
- // barrel: the webhook and every billing route read a subscription's AI item
20
- // through here, and the many route specs that stub `@aglyn/aglyn/server`
21
- // with a partial object would otherwise see every tier helper as undefined.
22
- import { AI_TIER_IDS, defaultAiTierForPlan, LEGACY_AI_ADDON_TIER_BY_PLAN, planSellsAiTiers } from "@aglyn/aglyn/app-utils/plan-entitlements";
18
+ // The Aglyn AI credit block (AGL-4144) by its own modules rather than the
19
+ // server barrel: the webhook and every billing route read a subscription's
20
+ // AI item through here, and the many route specs that stub
21
+ // `@aglyn/aglyn/server` with a partial object would otherwise see these as
22
+ // undefined.
23
+ import { planSellsAiCredits } from "@aglyn/aglyn/app-utils/plan-entitlements";
24
+ import { AI_CREDIT_BLOCK_ENV_KEY } from "@aglyn/aglyn/app-utils/ai-credit-blocks";
23
25
  /*
24
- * The add-on kinds, their unit prices (the Aglyn AI tier's included) and
26
+ * The add-on kinds, their unit prices (the Aglyn AI credit block's included) and
25
27
  * their ceilings live beside the bundle-link parser (AGL-3955), so the link,
26
28
  * the Billing card and this price map read one list. Re-exported here for
27
29
  * every server reader that already imports them from this module.
@@ -35,7 +37,9 @@ import { AI_TIER_IDS, defaultAiTierForPlan, LEGACY_AI_ADDON_TIER_BY_PLAN, planSe
35
37
  /** Kinds priced flat across plans (env `STRIPE_PRICE_{SUFFIX}[_YEARLY]`). */ const FLAT_ENV_NAME = {
36
38
  posRegisters: 'POS_REGISTER',
37
39
  eventCalendar: 'EVENT_CALENDAR',
38
- siteCare: 'SITE_CARE'
40
+ siteCare: 'SITE_CARE',
41
+ // Credits by the block (AGL-4144): `STRIPE_PRICE_AI_CREDITS[_YEARLY]`.
42
+ aiAddon: AI_CREDIT_BLOCK_ENV_KEY
39
43
  };
40
44
  /**
41
45
  * Every plan that is sold with a Stripe price — DERIVED, never hand-listed
@@ -55,91 +59,41 @@ import { AI_TIER_IDS, defaultAiTierForPlan, LEGACY_AI_ADDON_TIER_BY_PLAN, planSe
55
59
  * reintroducing it: `free` has nothing to sell and `enterprise` is quoted
56
60
  * per deal (no `STRIPE_PRICE_ENTERPRISE_*` exists), so everything else is
57
61
  * by definition a paid, priced plan.
62
+ *
63
+ * Since pricing v4 (2026-11-03, AGL-4126) that is Starter and Pro. Business,
64
+ * Scale, Advanced and Agency are retired: their prices are archived and
65
+ * their env removed, and no subscription carried one when v4 shipped, so
66
+ * nothing is left on Stripe for the read-back to recognise.
58
67
  */ export const PAID_PLANS = SELF_SERVE_PLANS.filter((plan)=>plan !== 'free');
59
68
  function env(name) {
60
69
  const value = process.env[name];
61
70
  return value ? value : null;
62
71
  }
63
- /**
64
- * The Stripe price id of an Aglyn AI tier (AGL-3965):
65
- * `STRIPE_PRICE_AI_{TIER}[_YEARLY]`, lookup key `aglyn_ai_{tier}[_yearly]`.
66
- * The same price on every plan; null when the env isn't configured.
67
- */ export function aiTierPriceId(tier, interval) {
68
- const yearly = interval === 'year' ? '_YEARLY' : '';
69
- return env(`STRIPE_PRICE_AI_${tier.toUpperCase()}${yearly}`);
70
- }
71
- /**
72
- * The per-plan AI add-on price sold before tiers existed
73
- * (`STRIPE_PRICE_{PLAN}_AI_ADDON[_YEARLY]`, AGL-2897). Never sold again; read
74
- * only so an item still carrying one is recognised as the add-on and as the
75
- * tier with its price and band until `migrate-ai-addon-tiers.mjs` moves it.
76
- */ export function legacyAiAddonPriceId(plan, interval) {
77
- if (!PAID_PLANS.includes(plan)) return null;
78
- const yearly = interval === 'year' ? '_YEARLY' : '';
79
- return env(`STRIPE_PRICE_${plan.toUpperCase()}_AI_ADDON${yearly}`);
80
- }
81
- /**
82
- * Which Aglyn AI tier a price id sells (AGL-3965): a tier price, or a legacy
83
- * per-plan add-on price read as the tier with the same price and band
84
- * (`LEGACY_AI_ADDON_TIER_BY_PLAN`). Null for anything else.
85
- */ export function aiTierFromPriceId(priceId) {
86
- if (!priceId) return null;
87
- for (const interval of [
88
- 'month',
89
- 'year'
90
- ]){
91
- for (const tier of AI_TIER_IDS){
92
- if (aiTierPriceId(tier, interval) === priceId) return tier;
93
- }
94
- for (const plan of PAID_PLANS){
95
- if (legacyAiAddonPriceId(plan, interval) === priceId) {
96
- var _LEGACY_AI_ADDON_TIER_BY_PLAN_plan;
97
- return (_LEGACY_AI_ADDON_TIER_BY_PLAN_plan = LEGACY_AI_ADDON_TIER_BY_PLAN[plan]) != null ? _LEGACY_AI_ADDON_TIER_BY_PLAN_plan : null;
98
- }
99
- }
100
- }
101
- return null;
102
- }
103
- /**
104
- * The tier a subscription's items carry (AGL-3965), or null when none is an
105
- * Aglyn AI item with a quantity. Written to `org.aiTier` beside the
106
- * `seatAddons` map `addonQuantitiesFromItems` derives from the same items.
107
- */ export function aiTierFromItems(items) {
108
- for (const item of items != null ? items : []){
109
- var _ref;
110
- var _item_price;
111
- const tier = aiTierFromPriceId(item == null ? void 0 : (_item_price = item.price) == null ? void 0 : _item_price.id);
112
- if (tier && Number((_ref = item == null ? void 0 : item.quantity) != null ? _ref : 1) >= 1) return tier;
113
- }
114
- return null;
115
- }
116
72
  /**
117
73
  * The Stripe price id for an add-on kind on a plan at a billing interval;
118
74
  * null when the plan doesn't sell it (free) or the env isn't configured.
119
- *
120
- * `tier` picks the Aglyn AI tier; absent, the tier a plan-named purchase
121
- * means (`defaultAiTierForPlan`). Ignored for every other kind.
122
- */ export function addonPriceId(kind, plan, interval, tier) {
123
- const name = addonPriceEnvName(kind, plan, interval, tier);
75
+ */ export function addonPriceId(kind, plan, interval) {
76
+ const name = addonPriceEnvName(kind, plan, interval);
124
77
  return name ? env(name) : null;
125
78
  }
126
79
  /**
127
80
  * The env var that holds an add-on's price id on a plan at an interval, or
128
81
  * null where the plan sells no such price. Named on its own so a checkout
129
82
  * that Stripe refuses can say which variable points at a missing price.
130
- * For the Aglyn AI add-on it is the tier's (`STRIPE_PRICE_AI_{TIER}`,
131
- * AGL-3965), `tier` read as `addonPriceId` reads it.
132
- */ export function addonPriceEnvName(kind, plan, interval, tier) {
83
+ * For Aglyn AI credit blocks it is `STRIPE_PRICE_AI_CREDITS[_YEARLY]`
84
+ * (AGL-4144), on a plan that sells them.
85
+ */ export function addonPriceEnvName(kind, plan, interval) {
133
86
  const yearly = interval === 'year' ? '_YEARLY' : '';
134
- if (kind === 'aiAddon') {
135
- if (!planSellsAiTiers(plan)) return null;
136
- const chosen = tier != null ? tier : defaultAiTierForPlan(plan);
137
- return chosen ? `STRIPE_PRICE_AI_${chosen.toUpperCase()}${yearly}` : null;
138
- }
87
+ // Flat, but sold only on a paid self-serve plan: Free has no subscription
88
+ // to carry the blocks and Enterprise's AI is in the agreement.
89
+ if (kind === 'aiAddon' && !planSellsAiCredits(plan)) return null;
139
90
  const flat = FLAT_ENV_NAME[kind];
140
91
  if (flat) return `STRIPE_PRICE_${flat}${yearly}`;
141
92
  const suffix = PER_PLAN_ENV_SUFFIX[kind];
142
- if (!suffix || plan === 'free') return null;
93
+ // Only a plan that is sold has per-plan add-on prices: Free sells none, and
94
+ // the plans pricing v4 retired (AGL-4126) are sold no longer, so their
95
+ // `STRIPE_PRICE_{PLAN}_EXTRA_*` env is not read.
96
+ if (!suffix || !PAID_PLANS.includes(plan)) return null;
143
97
  return `STRIPE_PRICE_${plan.toUpperCase()}_${suffix}${yearly}`;
144
98
  }
145
99
  /**
@@ -147,15 +101,18 @@ function env(name) {
147
101
  * Null for non-add-on prices (the base plan item, unknown prices).
148
102
  */ export function addonKindFromPriceId(priceId) {
149
103
  if (!priceId) return null;
150
- if (aiTierFromPriceId(priceId)) return 'aiAddon';
151
104
  for (const kind of ADDON_KINDS){
152
- if (kind === 'aiAddon') continue;
153
105
  for (const interval of [
154
106
  'month',
155
107
  'year'
156
108
  ]){
157
- if (FLAT_ENV_NAME[kind]) {
158
- if (addonPriceId(kind, 'starter', interval) === priceId) return kind;
109
+ const flat = FLAT_ENV_NAME[kind];
110
+ if (flat) {
111
+ // Read by the env name itself rather than through a plan, so a flat
112
+ // price is recognised whichever plans sell it.
113
+ if (env(`STRIPE_PRICE_${flat}${interval === 'year' ? '_YEARLY' : ''}`) === priceId) {
114
+ return kind;
115
+ }
159
116
  continue;
160
117
  }
161
118
  for (const plan of PAID_PLANS){
@@ -167,13 +124,12 @@ function env(name) {
167
124
  }
168
125
  /**
169
126
  * The price an add-on item moves to on a target plan/interval: the kind's
170
- * price there, and for the Aglyn AI add-on the SAME tier the item carries
171
- * now (AGL-3965) — a tier is chosen on its own, so a plan change re-prices
172
- * only its interval, and a legacy per-plan item becomes the tier with its
173
- * price and band.
174
- */ export function addonTargetPriceId(kind, plan, interval, currentPriceId) {
175
- const tier = kind === 'aiAddon' ? aiTierFromPriceId(currentPriceId) : null;
176
- return addonPriceId(kind, plan, interval, tier);
127
+ * price there. Aglyn AI credit blocks are one flat price per interval
128
+ * (AGL-4144), so a plan change re-prices only their interval. The current
129
+ * price is accepted so a caller states what it is moving from; no kind needs
130
+ * it to choose the target any more.
131
+ */ export function addonTargetPriceId(kind, plan, interval, _currentPriceId) {
132
+ return addonPriceId(kind, plan, interval);
177
133
  }
178
134
  /**
179
135
  * The BASE plan's Stripe price id at an interval
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/billing-addons.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n SELF_SERVE_PLANS,\n type AiTierId,\n type OrgPlan,\n} from '@aglyn/aglyn/server'\nimport {\n ADDON_KINDS,\n addonMaxForBaseline,\n addonMaxForPlan,\n addonUnitUsd,\n type AddonKind,\n} from '@aglyn/aglyn/app-utils/bundle-intent'\n// The Aglyn AI tiers (AGL-3965) by their own module rather than the server\n// barrel: the webhook and every billing route read a subscription's AI item\n// through here, and the many route specs that stub `@aglyn/aglyn/server`\n// with a partial object would otherwise see every tier helper as undefined.\nimport {\n AI_TIER_IDS,\n defaultAiTierForPlan,\n LEGACY_AI_ADDON_TIER_BY_PLAN,\n planSellsAiTiers,\n} from '@aglyn/aglyn/app-utils/plan-entitlements'\n\n/*\n * The add-on kinds, their unit prices (the Aglyn AI tier's included) and\n * their ceilings live beside the bundle-link parser (AGL-3955), so the link,\n * the Billing card and this price map read one list. Re-exported here for\n * every server reader that already imports them from this module.\n */\nexport { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd, type AddonKind }\n\n/**\n * Self-serve add-on price map (AGL-525): the bridge between\n * `STRIPE_PRICE_*` env price ids, `org.seatAddons` keys, and\n * `PLAN_PRICING` USD amounts. Add-ons bill as extra items on the org's\n * one subscription, so every kind has a monthly and a yearly price\n * (Stripe allows a single interval per subscription; annual orgs attach\n * the `_YEARLY` variants). Seat/member/dataset/host prices are per-plan;\n * POS registers, the Event Calendar and Site Care (AGL-3954) are flat; the\n * Aglyn AI add-on is priced per TIER (AGL-3965, `STRIPE_PRICE_AI_{TIER}`),\n * on any paid plan. Prices are minted by `tools/scripts/setup-stripe.mjs` —\n * keep the three in sync.\n */\nexport type BillingInterval = 'month' | 'year'\n\n/** Kinds priced per plan (env `STRIPE_PRICE_{PLAN}_{SUFFIX}[_YEARLY]`). */\nconst PER_PLAN_ENV_SUFFIX: Partial<Record<AddonKind, string>> = {\n managers: 'EXTRA_SEAT',\n members: 'EXTRA_MEMBER',\n datasets: 'EXTRA_DATASET',\n hosts: 'EXTRA_HOST',\n}\n\n/** Kinds priced flat across plans (env `STRIPE_PRICE_{SUFFIX}[_YEARLY]`). */\nconst FLAT_ENV_NAME: Partial<Record<AddonKind, string>> = {\n posRegisters: 'POS_REGISTER',\n eventCalendar: 'EVENT_CALENDAR',\n siteCare: 'SITE_CARE',\n}\n\n/**\n * Every plan that is sold with a Stripe price — DERIVED, never hand-listed\n * (AGL-1340).\n *\n * The literal that used to sit here listed starter, pro, business and\n * advanced only — it predated the Scale and Agency tiers, so\n * `addonKindFromPriceId()` could not recognise a single Scale/Agency add-on\n * price coming back from Stripe. `addonPriceId()` still SOLD them (it only\n * uppercases the plan), so the money moved and the read-back returned\n * nothing: the webhook wrote `seatAddons: {all zeros}` for the\n * highest-paying orgs on the next subscription event, and `seatAddons` is an\n * ENTITLEMENT INPUT (`plan-entitlements.ts` — it raises `hostLimit` and\n * `posRegisters`, and flips the `eventCalendar` feature).\n *\n * Deriving from `SELF_SERVE_PLANS` is what stops the next tier from\n * reintroducing it: `free` has nothing to sell and `enterprise` is quoted\n * per deal (no `STRIPE_PRICE_ENTERPRISE_*` exists), so everything else is\n * by definition a paid, priced plan.\n */\nexport const PAID_PLANS: readonly OrgPlan[] = SELF_SERVE_PLANS.filter(\n (plan) => plan !== 'free',\n)\n\nfunction env(name: string): string | null {\n const value = process.env[name]\n return value ? value : null\n}\n\n/**\n * The Stripe price id of an Aglyn AI tier (AGL-3965):\n * `STRIPE_PRICE_AI_{TIER}[_YEARLY]`, lookup key `aglyn_ai_{tier}[_yearly]`.\n * The same price on every plan; null when the env isn't configured.\n */\nexport function aiTierPriceId(\n tier: AiTierId,\n interval: BillingInterval,\n): string | null {\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_AI_${tier.toUpperCase()}${yearly}`)\n}\n\n/**\n * The per-plan AI add-on price sold before tiers existed\n * (`STRIPE_PRICE_{PLAN}_AI_ADDON[_YEARLY]`, AGL-2897). Never sold again; read\n * only so an item still carrying one is recognised as the add-on and as the\n * tier with its price and band until `migrate-ai-addon-tiers.mjs` moves it.\n */\nexport function legacyAiAddonPriceId(\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n if (!PAID_PLANS.includes(plan)) return null\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_${plan.toUpperCase()}_AI_ADDON${yearly}`)\n}\n\n/**\n * Which Aglyn AI tier a price id sells (AGL-3965): a tier price, or a legacy\n * per-plan add-on price read as the tier with the same price and band\n * (`LEGACY_AI_ADDON_TIER_BY_PLAN`). Null for anything else.\n */\nexport function aiTierFromPriceId(\n priceId: string | null | undefined,\n): AiTierId | null {\n if (!priceId) return null\n for (const interval of ['month', 'year'] as const) {\n for (const tier of AI_TIER_IDS) {\n if (aiTierPriceId(tier, interval) === priceId) return tier\n }\n for (const plan of PAID_PLANS) {\n if (legacyAiAddonPriceId(plan, interval) === priceId) {\n return LEGACY_AI_ADDON_TIER_BY_PLAN[plan] ?? null\n }\n }\n }\n return null\n}\n\n/**\n * The tier a subscription's items carry (AGL-3965), or null when none is an\n * Aglyn AI item with a quantity. Written to `org.aiTier` beside the\n * `seatAddons` map `addonQuantitiesFromItems` derives from the same items.\n */\nexport function aiTierFromItems(\n items:\n | ReadonlyArray<{ price?: { id?: string } | null; quantity?: number | null }>\n | null\n | undefined,\n): AiTierId | null {\n for (const item of items ?? []) {\n const tier = aiTierFromPriceId(item?.price?.id)\n if (tier && Number(item?.quantity ?? 1) >= 1) return tier\n }\n return null\n}\n\n/**\n * The Stripe price id for an add-on kind on a plan at a billing interval;\n * null when the plan doesn't sell it (free) or the env isn't configured.\n *\n * `tier` picks the Aglyn AI tier; absent, the tier a plan-named purchase\n * means (`defaultAiTierForPlan`). Ignored for every other kind.\n */\nexport function addonPriceId(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n tier?: AiTierId | null,\n): string | null {\n const name = addonPriceEnvName(kind, plan, interval, tier)\n return name ? env(name) : null\n}\n\n/**\n * The env var that holds an add-on's price id on a plan at an interval, or\n * null where the plan sells no such price. Named on its own so a checkout\n * that Stripe refuses can say which variable points at a missing price.\n * For the Aglyn AI add-on it is the tier's (`STRIPE_PRICE_AI_{TIER}`,\n * AGL-3965), `tier` read as `addonPriceId` reads it.\n */\nexport function addonPriceEnvName(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n tier?: AiTierId | null,\n): string | null {\n const yearly = interval === 'year' ? '_YEARLY' : ''\n if (kind === 'aiAddon') {\n if (!planSellsAiTiers(plan)) return null\n const chosen = tier ?? defaultAiTierForPlan(plan)\n return chosen ? `STRIPE_PRICE_AI_${chosen.toUpperCase()}${yearly}` : null\n }\n const flat = FLAT_ENV_NAME[kind]\n if (flat) return `STRIPE_PRICE_${flat}${yearly}`\n const suffix = PER_PLAN_ENV_SUFFIX[kind]\n if (!suffix || plan === 'free') return null\n return `STRIPE_PRICE_${plan.toUpperCase()}_${suffix}${yearly}`\n}\n\n/**\n * Reverse map: which add-on kind a subscription item's price id sells.\n * Null for non-add-on prices (the base plan item, unknown prices).\n */\nexport function addonKindFromPriceId(\n priceId: string | null | undefined,\n): AddonKind | null {\n if (!priceId) return null\n if (aiTierFromPriceId(priceId)) return 'aiAddon'\n for (const kind of ADDON_KINDS) {\n if (kind === 'aiAddon') continue\n for (const interval of ['month', 'year'] as const) {\n if (FLAT_ENV_NAME[kind]) {\n if (addonPriceId(kind, 'starter', interval) === priceId) return kind\n continue\n }\n for (const plan of PAID_PLANS) {\n if (addonPriceId(kind, plan, interval) === priceId) return kind\n }\n }\n }\n return null\n}\n\n/**\n * The price an add-on item moves to on a target plan/interval: the kind's\n * price there, and for the Aglyn AI add-on the SAME tier the item carries\n * now (AGL-3965) — a tier is chosen on its own, so a plan change re-prices\n * only its interval, and a legacy per-plan item becomes the tier with its\n * price and band.\n */\nexport function addonTargetPriceId(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n currentPriceId: string | null | undefined,\n): string | null {\n const tier = kind === 'aiAddon' ? aiTierFromPriceId(currentPriceId) : null\n return addonPriceId(kind, plan, interval, tier)\n}\n\n/**\n * The BASE plan's Stripe price id at an interval\n * (`STRIPE_PRICE_{PLAN}[_YEARLY]`); null for `free`, for the custom-priced\n * `enterprise`, and for an env that isn't configured. Read at call time, so\n * it never freezes a stale value at module load the way the routes'\n * `PRICE_ENV` maps do.\n */\nexport function planPriceId(\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n if (!PAID_PLANS.includes(plan)) return null\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_${plan.toUpperCase()}${yearly}`)\n}\n\n/**\n * Which plan a subscription item's price sells AND on which interval; null for\n * an add-on price, the metered price, an ad-hoc enterprise price, and anything\n * unknown.\n *\n * The interval half exists because a schedule phase read back from Stripe\n * carries price IDS and nothing else (AGL-2150): rebuilding that phase's item\n * list needs to know which interval it is priced on, and guessing it from the\n * live subscription is wrong exactly when the pending change is also an\n * interval change.\n */\nexport function planAndIntervalFromPriceId(\n priceId: string | null | undefined,\n): { plan: OrgPlan; interval: BillingInterval } | null {\n if (!priceId) return null\n for (const plan of PAID_PLANS) {\n for (const interval of ['month', 'year'] as const) {\n if (planPriceId(plan, interval) === priceId) return { plan, interval }\n }\n }\n return null\n}\n\n/**\n * Which plan a subscription item's price sells; null for an add-on price,\n * the metered price, an ad-hoc enterprise price, and anything unknown.\n */\nexport function planFromPriceId(\n priceId: string | null | undefined,\n): OrgPlan | null {\n return planAndIntervalFromPriceId(priceId)?.plan ?? null\n}\n\n/**\n * The shared metered-usage price (AGL-635) that makes reported usage\n * billable, for a given billing interval.\n *\n * Stripe rejects a subscription whose items mix `recurring.interval`, so the\n * metered item has to recur the same way the plan does. There are two prices\n * — `aglyn_metered_usage` (monthly) and `aglyn_metered_usage_yearly` — and\n * both bill $0.01 per aggregated unit against the SAME meter, because the\n * rollup posts an already-computed value in CENTS. The interval is therefore\n * the only thing that differs, and it is the only thing a caller must get\n * right.\n *\n * `interval` is REQUIRED on purpose (AGL-1280). It used to be monthly-only\n * with no argument, so the failure mode of forgetting it was attaching a\n * monthly price to a yearly subscription — the exact mixed-interval crash\n * this signature now makes unrepresentable. A default would hand that\n * footgun straight back.\n */\nexport function meteredPriceId(interval: 'month' | 'year'): string | null {\n return env(\n interval === 'year' ? 'STRIPE_PRICE_METERED_YEARLY' : 'STRIPE_PRICE_METERED',\n )\n}\n\n/**\n * Whether a price id is EITHER shared metered-usage price.\n *\n * Interval-agnostic by design: callers ask this to exclude the metered item\n * from plan/add-on reasoning, and an annual subscription's metered item must\n * be excluded just as thoroughly as a monthly one.\n */\nexport function isMeteredPriceId(priceId: string | null | undefined): boolean {\n if (!priceId) return false\n return (\n priceId === meteredPriceId('month') || priceId === meteredPriceId('year')\n )\n}\n\n/**\n * The subscription's BASE PLAN item, identified POSITIVELY (AGL-1340).\n *\n * This used to be \"whatever no add-on price claims\" — identification by\n * elimination, which quietly returns the wrong item the moment a\n * subscription carries anything the add-on map doesn't recognise: the\n * metered item, a grandfathered v1 price, a coupon-era SKU, an item added\n * by hand in the Stripe dashboard. Picking an add-on item as the plan item\n * means a plan switch re-prices the ADD-ON, and reads the billing interval\n * off it.\n *\n * So: match a known `STRIPE_PRICE_{PLAN}[_YEARLY]` first. Only when nothing\n * matches — an enterprise deal bills on an ad-hoc price, and grandfathered\n * subscriptions predate the current SKUs — fall back to the old rule,\n * minus the metered item, and finally to `items[0]` so behaviour for those\n * subscriptions is unchanged.\n */\nexport function findPlanItem<T extends { price?: { id?: string } | null }>(\n items: readonly T[] | null | undefined,\n): T | null {\n const list = items ?? []\n const byPlanPrice = list.find((item) => planFromPriceId(item?.price?.id))\n if (byPlanPrice) return byPlanPrice\n const notAnAddon = list.find(\n (item) =>\n !addonKindFromPriceId(item?.price?.id) &&\n !isMeteredPriceId(item?.price?.id),\n )\n return notAnAddon ?? list[0] ?? null\n}\n\n/**\n * Full add-on quantity map (explicit zeros for absent kinds) from a\n * subscription's items — the shape written to `org.seatAddons` so\n * removals and dashboard edits converge on sync (AGL-527).\n */\nexport function addonQuantitiesFromItems(\n items:\n | Array<{ price?: { id?: string } | null; quantity?: number | null }>\n | null\n | undefined,\n): Record<AddonKind, number> {\n const quantities = Object.fromEntries(\n ADDON_KINDS.map((kind) => [kind, 0]),\n ) as Record<AddonKind, number>\n for (const item of items ?? []) {\n const kind = addonKindFromPriceId(item?.price?.id)\n if (kind) {\n quantities[kind] += Math.max(0, Math.floor(Number(item?.quantity ?? 0)))\n }\n }\n return quantities\n}\n"],"names":["SELF_SERVE_PLANS","ADDON_KINDS","addonMaxForBaseline","addonMaxForPlan","addonUnitUsd","AI_TIER_IDS","defaultAiTierForPlan","LEGACY_AI_ADDON_TIER_BY_PLAN","planSellsAiTiers","PER_PLAN_ENV_SUFFIX","managers","members","datasets","hosts","FLAT_ENV_NAME","posRegisters","eventCalendar","siteCare","PAID_PLANS","filter","plan","env","name","value","process","aiTierPriceId","tier","interval","yearly","toUpperCase","legacyAiAddonPriceId","includes","aiTierFromPriceId","priceId","aiTierFromItems","items","item","price","id","Number","quantity","addonPriceId","kind","addonPriceEnvName","chosen","flat","suffix","addonKindFromPriceId","addonTargetPriceId","currentPriceId","planPriceId","planAndIntervalFromPriceId","planFromPriceId","meteredPriceId","isMeteredPriceId","findPlanItem","notAnAddon","list","byPlanPrice","find","addonQuantitiesFromItems","quantities","Object","fromEntries","map","Math","max","floor"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QAGX,sBAAqB;AAC5B,SACEC,WAAW,EACXC,mBAAmB,EACnBC,eAAe,EACfC,YAAY,QAEP,uCAAsC;AAC7C,2EAA2E;AAC3E,4EAA4E;AAC5E,yEAAyE;AACzE,4EAA4E;AAC5E,SACEC,WAAW,EACXC,oBAAoB,EACpBC,4BAA4B,EAC5BC,gBAAgB,QACX,2CAA0C;AAEjD;;;;;CAKC,GACD,SAASP,WAAW,EAAEC,mBAAmB,EAAEC,eAAe,EAAEC,YAAY,GAAkB;AAgB1F,yEAAyE,GACzE,MAAMK,sBAA0D;IAC9DC,UAAU;IACVC,SAAS;IACTC,UAAU;IACVC,OAAO;AACT;AAEA,2EAA2E,GAC3E,MAAMC,gBAAoD;IACxDC,cAAc;IACdC,eAAe;IACfC,UAAU;AACZ;AAEA;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,MAAMC,aAAiClB,iBAAiBmB,MAAM,CACnE,CAACC,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AAhBgB,gBAAgBhB,yBAAAA,cAAAA,KAAMC,KAAK,qBAAXD,YAAaE,EAAE;;IACvE,IAAIoB,aAAa,OAAOA;IACxB,MAAMF,aAAaC,KAAKE,IAAI,CAC1B,CAACvB;YACuBA,aACJA;eADlB,CAACW,qBAAqBX,yBAAAA,cAAAA,KAAMC,KAAK,qBAAXD,YAAaE,EAAE,KACrC,CAACgB,iBAAiBlB,yBAAAA,eAAAA,KAAMC,KAAK,qBAAXD,aAAaE,EAAE;;IAErC,QAAOkB,OAAAA,qBAAAA,aAAcC,IAAI,CAAC,EAAE,YAArBD,OAAyB;AAClC;AAEA;;;;CAIC,GACD,OAAO,SAASI,yBACdzB,KAGa;IAEb,MAAM0B,aAAaC,OAAOC,WAAW,CACnC9D,YAAY+D,GAAG,CAAC,CAACtB,OAAS;YAACA;YAAM;SAAE;IAErC,KAAK,MAAMN,QAAQD,gBAAAA,QAAS,EAAE,CAAE;YACIC;QAAlC,MAAMM,OAAOK,qBAAqBX,yBAAAA,cAAAA,KAAMC,KAAK,qBAAXD,YAAaE,EAAE;QACjD,IAAII,MAAM;;YACRmB,UAAU,CAACnB,KAAK,IAAIuB,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAAC5B,eAAOH,wBAAAA,KAAMI,QAAQ,mBAAI;QACtE;IACF;IACA,OAAOqB;AACT"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/billing-addons.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n SELF_SERVE_PLANS,\n type OrgPlan,\n} from '@aglyn/aglyn/server'\nimport {\n ADDON_KINDS,\n addonMaxForBaseline,\n addonMaxForPlan,\n addonUnitUsd,\n type AddonKind,\n} from '@aglyn/aglyn/app-utils/bundle-intent'\n// The Aglyn AI credit block (AGL-4144) by its own modules rather than the\n// server barrel: the webhook and every billing route read a subscription's\n// AI item through here, and the many route specs that stub\n// `@aglyn/aglyn/server` with a partial object would otherwise see these as\n// undefined.\nimport { planSellsAiCredits } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport { AI_CREDIT_BLOCK_ENV_KEY } from '@aglyn/aglyn/app-utils/ai-credit-blocks'\n\n/*\n * The add-on kinds, their unit prices (the Aglyn AI credit block's included) and\n * their ceilings live beside the bundle-link parser (AGL-3955), so the link,\n * the Billing card and this price map read one list. Re-exported here for\n * every server reader that already imports them from this module.\n */\nexport { ADDON_KINDS, addonMaxForBaseline, addonMaxForPlan, addonUnitUsd, type AddonKind }\n\n/**\n * Self-serve add-on price map (AGL-525): the bridge between\n * `STRIPE_PRICE_*` env price ids, `org.seatAddons` keys, and\n * `PLAN_PRICING` USD amounts. Add-ons bill as extra items on the org's\n * one subscription, so every kind has a monthly and a yearly price\n * (Stripe allows a single interval per subscription; annual orgs attach\n * the `_YEARLY` variants). Seat/member/dataset/host prices are per-plan;\n * POS registers, the Event Calendar, Site Care (AGL-3954) and Aglyn AI\n * credit blocks (AGL-4144, `STRIPE_PRICE_AI_CREDITS`, on any paid plan) are\n * flat. Prices are minted by `tools/scripts/setup-stripe.mjs` — keep the\n * three in sync.\n */\nexport type BillingInterval = 'month' | 'year'\n\n/** Kinds priced per plan (env `STRIPE_PRICE_{PLAN}_{SUFFIX}[_YEARLY]`). */\nconst PER_PLAN_ENV_SUFFIX: Partial<Record<AddonKind, string>> = {\n managers: 'EXTRA_SEAT',\n members: 'EXTRA_MEMBER',\n datasets: 'EXTRA_DATASET',\n hosts: 'EXTRA_HOST',\n}\n\n/** Kinds priced flat across plans (env `STRIPE_PRICE_{SUFFIX}[_YEARLY]`). */\nconst FLAT_ENV_NAME: Partial<Record<AddonKind, string>> = {\n posRegisters: 'POS_REGISTER',\n eventCalendar: 'EVENT_CALENDAR',\n siteCare: 'SITE_CARE',\n // Credits by the block (AGL-4144): `STRIPE_PRICE_AI_CREDITS[_YEARLY]`.\n aiAddon: AI_CREDIT_BLOCK_ENV_KEY,\n}\n\n/**\n * Every plan that is sold with a Stripe price — DERIVED, never hand-listed\n * (AGL-1340).\n *\n * The literal that used to sit here listed starter, pro, business and\n * advanced only — it predated the Scale and Agency tiers, so\n * `addonKindFromPriceId()` could not recognise a single Scale/Agency add-on\n * price coming back from Stripe. `addonPriceId()` still SOLD them (it only\n * uppercases the plan), so the money moved and the read-back returned\n * nothing: the webhook wrote `seatAddons: {all zeros}` for the\n * highest-paying orgs on the next subscription event, and `seatAddons` is an\n * ENTITLEMENT INPUT (`plan-entitlements.ts` — it raises `hostLimit` and\n * `posRegisters`, and flips the `eventCalendar` feature).\n *\n * Deriving from `SELF_SERVE_PLANS` is what stops the next tier from\n * reintroducing it: `free` has nothing to sell and `enterprise` is quoted\n * per deal (no `STRIPE_PRICE_ENTERPRISE_*` exists), so everything else is\n * by definition a paid, priced plan.\n *\n * Since pricing v4 (2026-11-03, AGL-4126) that is Starter and Pro. Business,\n * Scale, Advanced and Agency are retired: their prices are archived and\n * their env removed, and no subscription carried one when v4 shipped, so\n * nothing is left on Stripe for the read-back to recognise.\n */\nexport const PAID_PLANS: readonly OrgPlan[] = SELF_SERVE_PLANS.filter(\n (plan) => plan !== 'free',\n)\n\nfunction env(name: string): string | null {\n const value = process.env[name]\n return value ? value : null\n}\n\n/**\n * The Stripe price id for an add-on kind on a plan at a billing interval;\n * null when the plan doesn't sell it (free) or the env isn't configured.\n */\nexport function addonPriceId(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n const name = addonPriceEnvName(kind, plan, interval)\n return name ? env(name) : null\n}\n\n/**\n * The env var that holds an add-on's price id on a plan at an interval, or\n * null where the plan sells no such price. Named on its own so a checkout\n * that Stripe refuses can say which variable points at a missing price.\n * For Aglyn AI credit blocks it is `STRIPE_PRICE_AI_CREDITS[_YEARLY]`\n * (AGL-4144), on a plan that sells them.\n */\nexport function addonPriceEnvName(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n const yearly = interval === 'year' ? '_YEARLY' : ''\n // Flat, but sold only on a paid self-serve plan: Free has no subscription\n // to carry the blocks and Enterprise's AI is in the agreement.\n if (kind === 'aiAddon' && !planSellsAiCredits(plan)) return null\n const flat = FLAT_ENV_NAME[kind]\n if (flat) return `STRIPE_PRICE_${flat}${yearly}`\n const suffix = PER_PLAN_ENV_SUFFIX[kind]\n // Only a plan that is sold has per-plan add-on prices: Free sells none, and\n // the plans pricing v4 retired (AGL-4126) are sold no longer, so their\n // `STRIPE_PRICE_{PLAN}_EXTRA_*` env is not read.\n if (!suffix || !PAID_PLANS.includes(plan)) return null\n return `STRIPE_PRICE_${plan.toUpperCase()}_${suffix}${yearly}`\n}\n\n/**\n * Reverse map: which add-on kind a subscription item's price id sells.\n * Null for non-add-on prices (the base plan item, unknown prices).\n */\nexport function addonKindFromPriceId(\n priceId: string | null | undefined,\n): AddonKind | null {\n if (!priceId) return null\n for (const kind of ADDON_KINDS) {\n for (const interval of ['month', 'year'] as const) {\n const flat = FLAT_ENV_NAME[kind]\n if (flat) {\n // Read by the env name itself rather than through a plan, so a flat\n // price is recognised whichever plans sell it.\n if (env(`STRIPE_PRICE_${flat}${interval === 'year' ? '_YEARLY' : ''}`) === priceId) {\n return kind\n }\n continue\n }\n for (const plan of PAID_PLANS) {\n if (addonPriceId(kind, plan, interval) === priceId) return kind\n }\n }\n }\n return null\n}\n\n/**\n * The price an add-on item moves to on a target plan/interval: the kind's\n * price there. Aglyn AI credit blocks are one flat price per interval\n * (AGL-4144), so a plan change re-prices only their interval. The current\n * price is accepted so a caller states what it is moving from; no kind needs\n * it to choose the target any more.\n */\nexport function addonTargetPriceId(\n kind: AddonKind,\n plan: OrgPlan,\n interval: BillingInterval,\n _currentPriceId?: string | null,\n): string | null {\n return addonPriceId(kind, plan, interval)\n}\n\n/**\n * The BASE plan's Stripe price id at an interval\n * (`STRIPE_PRICE_{PLAN}[_YEARLY]`); null for `free`, for the custom-priced\n * `enterprise`, and for an env that isn't configured. Read at call time, so\n * it never freezes a stale value at module load the way the routes'\n * `PRICE_ENV` maps do.\n */\nexport function planPriceId(\n plan: OrgPlan,\n interval: BillingInterval,\n): string | null {\n if (!PAID_PLANS.includes(plan)) return null\n const yearly = interval === 'year' ? '_YEARLY' : ''\n return env(`STRIPE_PRICE_${plan.toUpperCase()}${yearly}`)\n}\n\n/**\n * Which plan a subscription item's price sells AND on which interval; null for\n * an add-on price, the metered price, an ad-hoc enterprise price, and anything\n * unknown.\n *\n * The interval half exists because a schedule phase read back from Stripe\n * carries price IDS and nothing else (AGL-2150): rebuilding that phase's item\n * list needs to know which interval it is priced on, and guessing it from the\n * live subscription is wrong exactly when the pending change is also an\n * interval change.\n */\nexport function planAndIntervalFromPriceId(\n priceId: string | null | undefined,\n): { plan: OrgPlan; interval: BillingInterval } | null {\n if (!priceId) return null\n for (const plan of PAID_PLANS) {\n for (const interval of ['month', 'year'] as const) {\n if (planPriceId(plan, interval) === priceId) return { plan, interval }\n }\n }\n return null\n}\n\n/**\n * Which plan a subscription item's price sells; null for an add-on price,\n * the metered price, an ad-hoc enterprise price, and anything unknown.\n */\nexport function planFromPriceId(\n priceId: string | null | undefined,\n): OrgPlan | null {\n return planAndIntervalFromPriceId(priceId)?.plan ?? null\n}\n\n/**\n * The shared metered-usage price (AGL-635) that makes reported usage\n * billable, for a given billing interval.\n *\n * Stripe rejects a subscription whose items mix `recurring.interval`, so the\n * metered item has to recur the same way the plan does. There are two prices\n * — `aglyn_metered_usage` (monthly) and `aglyn_metered_usage_yearly` — and\n * both bill $0.01 per aggregated unit against the SAME meter, because the\n * rollup posts an already-computed value in CENTS. The interval is therefore\n * the only thing that differs, and it is the only thing a caller must get\n * right.\n *\n * `interval` is REQUIRED on purpose (AGL-1280). It used to be monthly-only\n * with no argument, so the failure mode of forgetting it was attaching a\n * monthly price to a yearly subscription — the exact mixed-interval crash\n * this signature now makes unrepresentable. A default would hand that\n * footgun straight back.\n */\nexport function meteredPriceId(interval: 'month' | 'year'): string | null {\n return env(\n interval === 'year' ? 'STRIPE_PRICE_METERED_YEARLY' : 'STRIPE_PRICE_METERED',\n )\n}\n\n/**\n * Whether a price id is EITHER shared metered-usage price.\n *\n * Interval-agnostic by design: callers ask this to exclude the metered item\n * from plan/add-on reasoning, and an annual subscription's metered item must\n * be excluded just as thoroughly as a monthly one.\n */\nexport function isMeteredPriceId(priceId: string | null | undefined): boolean {\n if (!priceId) return false\n return (\n priceId === meteredPriceId('month') || priceId === meteredPriceId('year')\n )\n}\n\n/**\n * The subscription's BASE PLAN item, identified POSITIVELY (AGL-1340).\n *\n * This used to be \"whatever no add-on price claims\" — identification by\n * elimination, which quietly returns the wrong item the moment a\n * subscription carries anything the add-on map doesn't recognise: the\n * metered item, a grandfathered v1 price, a coupon-era SKU, an item added\n * by hand in the Stripe dashboard. Picking an add-on item as the plan item\n * means a plan switch re-prices the ADD-ON, and reads the billing interval\n * off it.\n *\n * So: match a known `STRIPE_PRICE_{PLAN}[_YEARLY]` first. Only when nothing\n * matches — an enterprise deal bills on an ad-hoc price, and grandfathered\n * subscriptions predate the current SKUs — fall back to the old rule,\n * minus the metered item, and finally to `items[0]` so behaviour for those\n * subscriptions is unchanged.\n */\nexport function findPlanItem<T extends { price?: { id?: string } | null }>(\n items: readonly T[] | null | undefined,\n): T | null {\n const list = items ?? []\n const byPlanPrice = list.find((item) => planFromPriceId(item?.price?.id))\n if (byPlanPrice) return byPlanPrice\n const notAnAddon = list.find(\n (item) =>\n !addonKindFromPriceId(item?.price?.id) &&\n !isMeteredPriceId(item?.price?.id),\n )\n return notAnAddon ?? list[0] ?? null\n}\n\n/**\n * Full add-on quantity map (explicit zeros for absent kinds) from a\n * subscription's items — the shape written to `org.seatAddons` so\n * removals and dashboard edits converge on sync (AGL-527).\n */\nexport function addonQuantitiesFromItems(\n items:\n | Array<{ price?: { id?: string } | null; quantity?: number | null }>\n | null\n | undefined,\n): Record<AddonKind, number> {\n const quantities = Object.fromEntries(\n ADDON_KINDS.map((kind) => [kind, 0]),\n ) as Record<AddonKind, number>\n for (const item of items ?? []) {\n const kind = addonKindFromPriceId(item?.price?.id)\n if (kind) {\n quantities[kind] += Math.max(0, Math.floor(Number(item?.quantity ?? 0)))\n }\n }\n return quantities\n}\n"],"names":["SELF_SERVE_PLANS","ADDON_KINDS","addonMaxForBaseline","addonMaxForPlan","addonUnitUsd","planSellsAiCredits","AI_CREDIT_BLOCK_ENV_KEY","PER_PLAN_ENV_SUFFIX","managers","members","datasets","hosts","FLAT_ENV_NAME","posRegisters","eventCalendar","siteCare","aiAddon","PAID_PLANS","filter","plan","env","name","value","process","addonPriceId","kind","interval","addonPriceEnvName","yearly","flat","suffix","includes","toUpperCase","addonKindFromPriceId","priceId","addonTargetPriceId","_currentPriceId","planPriceId","planAndIntervalFromPriceId","planFromPriceId","meteredPriceId","isMeteredPriceId","findPlanItem","items","notAnAddon","list","byPlanPrice","find","item","price","id","addonQuantitiesFromItems","quantities","Object","fromEntries","map","Math","max","floor","Number","quantity"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,QAEX,sBAAqB;AAC5B,SACEC,WAAW,EACXC,mBAAmB,EACnBC,eAAe,EACfC,YAAY,QAEP,uCAAsC;AAC7C,0EAA0E;AAC1E,2EAA2E;AAC3E,2DAA2D;AAC3D,2EAA2E;AAC3E,aAAa;AACb,SAASC,kBAAkB,QAAQ,2CAA0C;AAC7E,SAASC,uBAAuB,QAAQ,0CAAyC;AAEjF;;;;;CAKC,GACD,SAASL,WAAW,EAAEC,mBAAmB,EAAEC,eAAe,EAAEC,YAAY,GAAkB;AAgB1F,yEAAyE,GACzE,M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AiBP,OAAkC;IACjE,IAAI,CAACA,SAAS,OAAO;IACrB,OACEA,YAAYM,eAAe,YAAYN,YAAYM,eAAe;AAEtE;AAEA;;;;;;;;;;;;;;;;CAgBC,GACD,OAAO,SAASE,aACdC,KAAsC;QAU/BC;IARP,MAAMC,OAAOF,gBAAAA,QAAS,EAAE;IACxB,MAAMG,cAAcD,KAAKE,IAAI,CAAC,CAACC;YAAyBA;eAAhBT,gBAAgBS,yBAAAA,cAAAA,KAAMC,KAAK,qBAAXD,YAAaE,EAAE;;IACvE,IAAIJ,aAAa,OAAOA;IACxB,MAAMF,aAAaC,KAAKE,IAAI,CAC1B,CAACC;YACuBA,aACJA;eADlB,CAACf,qBAAqBe,yBAAAA,cAAAA,KAAMC,KAAK,qBAAXD,YAAaE,EAAE,KACrC,CAACT,iBAAiBO,yBAAAA,eAAAA,KAAMC,KAAK,qBAAXD,aAAaE,EAAE;;IAErC,QAAON,OAAAA,qBAAAA,aAAcC,IAAI,CAAC,EAAE,YAArBD,OAAyB;AAClC;AAEA;;;;CAIC,GACD,OAAO,SAASO,yBACdR,KAGa;IAEb,MAAMS,aAAaC,OAAOC,WAAW,CACnCrD,YAAYsD,GAAG,CAAC,CAAC9B,OAAS;YAACA;YAAM;SAAE;IAErC,KAAK,MAAMuB,QAAQL,gBAAAA,QAAS,EAAE,CAAE;YACIK;QAAlC,MAAMvB,OAAOQ,qBAAqBe,yBAAAA,cAAAA,KAAMC,KAAK,qBAAXD,YAAaE,EAAE;QACjD,IAAIzB,MAAM;;YACR2B,UAAU,CAAC3B,KAAK,IAAI+B,KAAKC,GAAG,CAAC,GAAGD,KAAKE,KAAK,CAACC,eAAOX,wBAAAA,KAAMY,QAAQ,mBAAI;QACtE;IACF;IACA,OAAOR;AACT"}
@@ -41,7 +41,7 @@
41
41
  * unguessable id and carrying the workspace. Only the Admin SDK reads or
42
42
  * writes them; the rules deny every client, staff included.
43
43
  */
44
- import type { AiTierId, OrgPlan } from '@aglyn/aglyn/server';
44
+ import type { OrgPlan } from '@aglyn/aglyn/server';
45
45
  import { type AddonKind, type BundleAddons } from '@aglyn/aglyn/app-utils/bundle-intent';
46
46
  import type { PurchaseGatePreclearance } from '@aglyn/aglyn/plugin-manager/purchase-gate-preclearance';
47
47
  export declare const BUNDLE_LINKS_COLLECTION = "bundleLinks";
@@ -82,8 +82,6 @@ export interface BundleLinkDoc {
82
82
  addons?: BundleAddons;
83
83
  interval?: 'month' | 'year';
84
84
  coupon?: string;
85
- /** The Aglyn AI tier an `ai:<tier>` entry named (AGL-3965). */
86
- aiTier?: AiTierId;
87
85
  };
88
86
  domain?: BundleLinkDomain;
89
87
  }
@@ -106,8 +104,8 @@ export interface MintBundleLinkOptions {
106
104
  interval?: unknown;
107
105
  coupon?: unknown;
108
106
  /**
109
- * The Aglyn AI tier staff chose (AGL-4025), kept with the AI add-on; an
110
- * `ai:<tier>` entry in `addons` names one too, and this wins when both do.
107
+ * A retired Aglyn AI tier (AGL-4025). Credits are sold by the block since
108
+ * AGL-4144 (`ai:<blocks>` in `addons`), so a link naming a tier is refused.
111
109
  */
112
110
  aiTier?: unknown;
113
111
  /** The chosen domain, quoted from the registrar's search; optional. */
@@ -43,7 +43,6 @@
43
43
  import { fitBundleAddonsToPlan, normalizeBundleDomain, parseBundleAddons } from "@aglyn/aglyn/app-utils/bundle-intent";
44
44
  import { createResourceUid } from "@aglyn/aglyn/app-utils/create-resource-uid";
45
45
  import { onboardingDestination } from "@aglyn/aglyn/app-utils/onboarding-deep-link";
46
- import { isAiTierId } from "@aglyn/aglyn/app-utils/plan-entitlements";
47
46
  import { isUpgradeProposalPlan, normalizeUpgradeProposalBundle, upgradeProposalIntent } from "@aglyn/aglyn/app-utils/upgrade-proposal";
48
47
  import { isLiveSubscriptionStatus, ORG_BILLING_DOC_ID, ORG_BILLING_SUBCOLLECTION } from "@aglyn/aglyn/app-utils/org-billing-doc";
49
48
  import { FieldValue } from "firebase-admin/firestore";
@@ -88,15 +87,15 @@ function cents(value) {
88
87
  throw new BundleLinkError('Choose a paid plan the workspace can buy itself');
89
88
  }
90
89
  const plan = options.plan;
90
+ if (options.aiTier != null) {
91
+ throw new BundleLinkError('AI tiers were replaced by AI credit blocks. Choose a number of blocks instead.');
92
+ }
91
93
  const parsed = parseBundleAddons(options.addons);
92
94
  const fitted = fitBundleAddonsToPlan(parsed.addons, plan);
93
95
  const bundle = normalizeUpgradeProposalBundle(plan, {
94
96
  addons: fitted.addons,
95
97
  interval: options.interval,
96
- coupon: options.coupon,
97
- // The tier staff chose (AGL-4025), or the one an `ai:<tier>` entry named
98
- // (AGL-3965), kept with the AI add-on.
99
- aiTier: isAiTierId(options.aiTier) ? options.aiTier : parsed.aiTier
98
+ coupon: options.coupon
100
99
  });
101
100
  const intent = _extends({
102
101
  plan