@aglyn/aglyn 1.24.0 → 1.26.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 (54) hide show
  1. package/package.json +11 -11
  2. package/src/lib/app-utils/activity-labels.js +4 -1
  3. package/src/lib/app-utils/activity-labels.js.map +1 -1
  4. package/src/lib/app-utils/bandwidth-cap.d.ts +99 -1
  5. package/src/lib/app-utils/bandwidth-cap.js +148 -4
  6. package/src/lib/app-utils/bandwidth-cap.js.map +1 -1
  7. package/src/lib/app-utils/business-details.d.ts +5 -0
  8. package/src/lib/app-utils/business-details.js +4 -0
  9. package/src/lib/app-utils/business-details.js.map +1 -1
  10. package/src/lib/app-utils/crm.d.ts +17 -30
  11. package/src/lib/app-utils/crm.js +139 -3
  12. package/src/lib/app-utils/crm.js.map +1 -1
  13. package/src/lib/app-utils/docs-help-sections.generated.js +4 -1
  14. package/src/lib/app-utils/docs-help-sections.generated.js.map +1 -1
  15. package/src/lib/app-utils/docs-help.generated.d.ts +1 -1
  16. package/src/lib/app-utils/docs-help.generated.js +7 -0
  17. package/src/lib/app-utils/docs-help.generated.js.map +1 -1
  18. package/src/lib/app-utils/docs-index.generated.js +95 -11
  19. package/src/lib/app-utils/docs-index.generated.js.map +1 -1
  20. package/src/lib/app-utils/host-tokens.d.ts +17 -0
  21. package/src/lib/app-utils/host-tokens.js +18 -0
  22. package/src/lib/app-utils/host-tokens.js.map +1 -1
  23. package/src/lib/app-utils/native-app-association.d.ts +5 -3
  24. package/src/lib/app-utils/native-app-association.js +5 -3
  25. package/src/lib/app-utils/native-app-association.js.map +1 -1
  26. package/src/lib/app-utils/native-nav.js +1 -1
  27. package/src/lib/app-utils/native-nav.js.map +1 -1
  28. package/src/lib/app-utils/notifications.js +5 -0
  29. package/src/lib/app-utils/notifications.js.map +1 -1
  30. package/src/lib/app-utils/plan-entitlements.d.ts +227 -36
  31. package/src/lib/app-utils/plan-entitlements.js +339 -45
  32. package/src/lib/app-utils/plan-entitlements.js.map +1 -1
  33. package/src/lib/app-utils/reusable-component-keys.d.ts +9 -0
  34. package/src/lib/app-utils/reusable-component-keys.js +9 -0
  35. package/src/lib/app-utils/reusable-component-keys.js.map +1 -1
  36. package/src/lib/app-utils/server.d.ts +1 -0
  37. package/src/lib/app-utils/server.js +1 -0
  38. package/src/lib/app-utils/server.js.map +1 -1
  39. package/src/lib/app-utils/sign-in-hint-cookie.d.ts +58 -0
  40. package/src/lib/app-utils/sign-in-hint-cookie.js +71 -0
  41. package/src/lib/app-utils/sign-in-hint-cookie.js.map +1 -0
  42. package/src/lib/app-utils/sign-in-visibility.d.ts +75 -0
  43. package/src/lib/app-utils/sign-in-visibility.js +79 -0
  44. package/src/lib/app-utils/sign-in-visibility.js.map +1 -0
  45. package/src/lib/app-utils/site-live-url.d.ts +4 -1
  46. package/src/lib/app-utils/site-live-url.js +17 -3
  47. package/src/lib/app-utils/site-live-url.js.map +1 -1
  48. package/src/lib/app-utils/usage-level.d.ts +50 -0
  49. package/src/lib/app-utils/usage-level.js +94 -0
  50. package/src/lib/app-utils/usage-level.js.map +1 -0
  51. package/src/lib/foundation/definitions/org-billing.types.d.ts +45 -2
  52. package/src/lib/foundation/definitions/org-billing.types.js.map +1 -1
  53. package/src/lib/foundation/definitions/platform.types.d.ts +9 -0
  54. package/src/lib/foundation/definitions/platform.types.js.map +1 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/aglyn",
3
- "version": "1.24.0",
3
+ "version": "1.26.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -37,16 +37,16 @@
37
37
  "./package.json": "./package.json"
38
38
  },
39
39
  "dependencies": {
40
- "@aglyn/shared-data-enums": "1.24.0",
41
- "@aglyn/shared-data-mdi": "1.24.0",
42
- "@aglyn/shared-data-types": "1.24.0",
43
- "@aglyn/shared-util-email": "1.24.0",
44
- "@aglyn/shared-util-first-touch": "1.24.0",
45
- "@aglyn/shared-util-http": "1.24.0",
46
- "@aglyn/shared-util-logger": "1.24.0",
47
- "@aglyn/shared-util-timestamp": "1.24.0",
48
- "@aglyn/shared-util-tools": "1.24.0",
49
- "@aglyn/shared-util-vendor": "1.24.0",
40
+ "@aglyn/shared-data-enums": "1.26.0",
41
+ "@aglyn/shared-data-mdi": "1.26.0",
42
+ "@aglyn/shared-data-types": "1.26.0",
43
+ "@aglyn/shared-util-email": "1.26.0",
44
+ "@aglyn/shared-util-first-touch": "1.26.0",
45
+ "@aglyn/shared-util-http": "1.26.0",
46
+ "@aglyn/shared-util-logger": "1.26.0",
47
+ "@aglyn/shared-util-timestamp": "1.26.0",
48
+ "@aglyn/shared-util-tools": "1.26.0",
49
+ "@aglyn/shared-util-vendor": "1.26.0",
50
50
  "@data-driven-forms/react-form-renderer": "^4.2.3",
51
51
  "@msgpack/msgpack": "^3.1.3",
52
52
  "@types/unist": "^3.0.3",
@@ -126,6 +126,7 @@ import { isPluginJobTargetType, pluginActivityActionSentence, pluginActivityTarg
126
126
  'host.reattach-domain': 'Reattached a domain',
127
127
  'host.set-subdomain': 'Changed a site address',
128
128
  'host.transfer': 'Transferred a site',
129
+ 'host.usageLevel': 'Set the site usage level',
129
130
  'lockdown.lock': 'Locked the workspace down',
130
131
  'lockdown.payouts-pause': 'Paused payouts',
131
132
  'lockdown.payouts-restore': 'Restored payouts',
@@ -160,6 +161,7 @@ import { isPluginJobTargetType, pluginActivityActionSentence, pluginActivityTarg
160
161
  'org.successManagerSet': 'Assigned a success manager',
161
162
  'org.upgradeProposal.propose': 'Proposed an upgrade',
162
163
  'org.upgradeProposal.withdraw': 'Withdrew an upgrade proposal',
164
+ 'org.usageLevel': 'Set the workspace usage level',
163
165
  'orgs.unverified.reap': 'Removed unverified organizations',
164
166
  'person.erased': 'Erased a person',
165
167
  'person.erasure-requested': 'Requested erasure of a person',
@@ -194,7 +196,8 @@ import { isPluginJobTargetType, pluginActivityActionSentence, pluginActivityTarg
194
196
  'user.setAdAudienceOptOut': 'Changed the ad audience opt-out',
195
197
  'user.setPassword': 'Set the password',
196
198
  'user.signOutDevice': 'Signed a device out',
197
- 'user.updateProfile': 'Updated the profile'
199
+ 'user.updateProfile': 'Updated the profile',
200
+ 'user.usageLevel': 'Set the account usage level'
198
201
  };
199
202
  /** Leading namespaces as a reader names them. */ const NAMESPACE_LABELS = {
200
203
  org: 'Organization',
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/activity-labels.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 * ONE LABEL MAP FOR EVERY ACTIVITY AND AUDIT LIST (AGL-3660).\n *\n * Two logs feed the console's lists. The activity logs\n * (`orgs/{id}/activity`, `hosts/{id}/activity`) store a prose sentence or a\n * plugin's code plus a `{ type, id, name }` target. The staff audit trail\n * (`adminAudit`) stores a dotted code (`ai.job.output`, `org.override`) and\n * a Firestore PATH as its target (`orgs/abc/aiJobs/xyz`). The staff tables\n * printed both raw, so a reader saw `ai.job.output` next to\n * `orgs/9fK…/aiJobs/Qe2…` and had to know the schema to read their own\n * audit trail.\n *\n * Every list now draws its words from here: an action as a sentence\n * (`Created page Home with Aglyn AI`), a target as the site and the item,\n * and — for an audit row — why, the credits it spent and what came of it.\n * The raw code and path are kept on the description, for a tooltip and for\n * the staff details dialog, and never as the visible text.\n */\n\nimport {\n activityActionLabel,\n activityPrimaryText,\n activityTypeLabel,\n type ActivityEntryLike,\n type ActivityTargetLike,\n} from './activity-presenter'\nimport { orgOverrideReasonSummary } from './org-override-reason'\nimport {\n isPluginJobTargetType,\n pluginActivityActionSentence,\n pluginActivityTargetLabel,\n pluginStaffAuditActionLabel,\n pluginStaffAuditCollection,\n pluginStaffAuditDescribe,\n} from '../plugin-manager/plugin-activity-actions'\n\n/** What a list row and the details dialog show for one entry. */\nexport interface ActivityDescription {\n /** The act, as a sentence. Never a code. */\n action: string\n /** What it was done to, in words: the site and the item. Never a path. */\n target: string\n /** Why it was done, when the writer recorded a reason. */\n why: string | null\n /** AI credits it spent, when it spent any. */\n credits: number | null\n /** What came of it, when the writer recorded an outcome. */\n result: string | null\n /** The stored code, when the action was one — for a tooltip and staff. */\n code: string | null\n /** The stored target path (audit) or `type/id` (activity) — staff only. */\n path: string | null\n /** The organization the entry concerns, when it names one. */\n orgId: string | null\n /** The site the entry concerns, when it names one. */\n hostId: string | null\n /** The plugin job behind the entry (an AI job), when there is one. */\n jobId: string | null\n /** The account the entry concerns, when it names one. */\n uid: string | null\n}\n\n/** Names a route resolved for the ids an entry carries. */\nexport interface ActivityNames {\n /** Organization name by org id. */\n orgs?: Readonly<Record<string, string | null | undefined>>\n /** Site name by host id. */\n hosts?: Readonly<Record<string, string | null | undefined>>\n /** An account's address (or name) by uid. */\n users?: Readonly<Record<string, string | null | undefined>>\n}\n\n/** `screen` → `page`, `Home` → `page Home`: the noun a sentence uses. */\nexport function activityTargetPhrase(target: ActivityTargetLike | null | undefined): string {\n const noun = activityTypeLabel(target?.type)\n const lower = noun === 'Item' ? 'item' : noun.charAt(0).toLowerCase() + noun.slice(1)\n const name = target?.name?.trim()\n return name ? `${lower} ${name}` : lower\n}\n\n/**\n * An activity row's action as a sentence about its target. A plugin code\n * with a declared sentence fills it (`Created {target} with Aglyn AI`); any\n * other code reads as its label, and a prose action as itself.\n */\nexport function activityActionSentence(\n action: string | undefined,\n target?: ActivityTargetLike | null,\n): string {\n const stored = action?.trim() ?? ''\n const sentence = pluginActivityActionSentence(stored)\n if (sentence) return sentence.replace('{target}', activityTargetPhrase(target))\n return activityActionLabel(stored)\n}\n\n/**\n * A one-column feed's line: the sentence when the code declares one, else\n * the action with its target's name (`Saved the screen — Home`).\n */\nexport function activityRowText(entry: ActivityEntryLike): string {\n const stored = entry.action?.trim() ?? ''\n return pluginActivityActionSentence(stored)\n ? activityActionSentence(stored, entry.target)\n : activityPrimaryText(entry)\n}\n\n/** Whether a stored action is a dotted code rather than a sentence. */\nexport function isActivityCode(action: unknown): action is string {\n return typeof action === 'string' && /^[a-z][\\w-]*(\\.[\\w-]+)+$/i.test(action.trim())\n}\n\n/*==========================================\n * THE STAFF AUDIT TRAIL'S WORDS.\n *\n * Every code core's doors write. A plugin's doors declare their own through\n * `staffAuditLabels` (the AI plugin's `ai.job.*`), and a code neither knows\n * is humanized from its segments rather than shown raw, so a new writer\n * reads as `Billing: invoice paid` until somebody names it properly.\n *==========================================*/\nexport const STAFF_AUDIT_ACTION_LABELS: Readonly<Record<string, string>> = {\n 'account.closed.self': 'Closed their own account',\n 'account.exported.self': 'Exported their own account data',\n 'ai-usage.exported': 'Exported AI usage',\n 'billing.assistOverage.setCap': 'Set the AI overage ceiling',\n 'billing.assistOverage.setHardCap': 'Set the AI stop-at-band switch',\n 'billing.autoLocked': 'Locked automatically for billing',\n 'billing.bundle-link-minted': 'Made a bundle checkout link',\n 'billing.collaboratorAllocation': 'Changed collaborator seats',\n 'billing.dispute.opened': 'Payment dispute opened',\n 'billing.disputeClosed': 'Payment dispute closed',\n 'billing.disputeOpened': 'Payment dispute opened',\n 'billing.disputeUnattributed': 'Unattributed payment dispute',\n 'billing.invoice': 'Invoice event',\n 'billing.invoice.closed': 'Invoice closed',\n 'billing.invoice.failed': 'Invoice payment failed',\n 'billing.invoice.paid': 'Invoice paid',\n 'billing.manage': 'Opened billing management',\n 'billing.orphanedSubscription': 'Found a subscription with no workspace',\n 'billing.paymentFailed': 'Payment failed',\n 'billing.paymentMethod.changed': 'Changed the payment method',\n 'billing.platformDisputeLost': 'Lost a payment dispute',\n 'billing.platformInvoiceUncollectible': 'Invoice marked uncollectible',\n 'billing.registerAllocation': 'Changed register allocation',\n 'billing.storageOverage.setCap': 'Set the storage overage ceiling',\n 'billing.subscriptionCanceled': 'Subscription canceled',\n 'billing.usage': 'Recorded usage',\n 'billing.usageBudget.set': 'Set the usage budget',\n 'billing.view': 'Viewed billing',\n 'billing.webhookInert': 'Ignored a billing webhook',\n 'billing.webhookSignatureRejected': 'Rejected a billing webhook signature',\n 'broadcast.send': 'Sent a broadcast',\n 'client-build.preview-sent': 'Sent a client build preview',\n 'contact.phone.erased': 'Erased a phone number',\n 'contact.suppression.recorded': 'Added a contact suppression',\n 'contact.suppression.released': 'Released a contact suppression',\n 'coupon.create': 'Created a coupon',\n 'coupon.promotion_code.update': 'Updated a promotion code',\n 'data.transfer.export': 'Exported data',\n 'data.transfer.plan': 'Planned a data transfer',\n 'email.history-imported': 'Imported email history',\n 'email.message-viewed': 'Viewed an email message',\n 'email.sending-domains.reap': 'Removed unused sending domains',\n 'email.suppression.release': 'Released an email suppression',\n 'emailSendRate.update': 'Changed the email send rate',\n 'erasure.runBatch': 'Ran an erasure batch',\n 'erasures.replayed': 'Replayed erasures',\n 'firestore.export': 'Exported the database',\n 'firstPartyHosts.update': 'Changed first-party sites',\n 'flags.update': 'Changed feature flags',\n 'freeWorkspaceCap.update': 'Changed the free workspace cap',\n 'host.deleted': 'Deleted a site',\n 'host.domain.released': 'Released a domain',\n 'host.reattach-domain': 'Reattached a domain',\n 'host.set-subdomain': 'Changed a site address',\n 'host.transfer': 'Transferred a site',\n 'lockdown.lock': 'Locked the workspace down',\n 'lockdown.payouts-pause': 'Paused payouts',\n 'lockdown.payouts-restore': 'Restored payouts',\n 'lockdown.renewals-pause': 'Paused renewals',\n 'lockdown.renewals-resume': 'Resumed renewals',\n 'lockdown.resend-notice': 'Resent the lockdown notice',\n 'maintenance.auditArchive.run': 'Archived the audit log',\n 'maintenance.reapArtifacts.run': 'Removed stale build artifacts',\n 'maintenance.reverifyPlugins.run': 'Re-verified plugins',\n 'operatorAlerts.test': 'Sent a test operator alert',\n 'operatorAlerts.update': 'Changed operator alerts',\n 'org.acquisition-viewed': 'Viewed where the organization came from',\n 'org.auditLog': 'Viewed the organization audit log',\n 'org.discount.apply': 'Applied a discount',\n 'org.discount.remove': 'Removed a discount',\n 'org.enterprise.provision': 'Provisioned enterprise billing',\n 'org.erase-failed': 'Organization erasure failed',\n 'org.erased': 'Erased the organization',\n 'org.erasureCanceled': 'Canceled the organization erasure',\n 'org.erasureRequested': 'Requested organization erasure',\n 'org.exported': 'Exported the organization',\n 'org.name': 'Renamed the organization',\n 'org.note': 'Added a staff note',\n 'org.override': 'Overrode the plan',\n 'org.refund': 'Issued a refund',\n 'org.seatAddons.changed': 'Changed seat add-ons',\n 'org.sso.enforceSignInMethods': 'Changed enforced sign-in methods',\n 'org.sso.jit': 'Changed single sign-on provisioning',\n 'org.subscription-cancel': 'Canceled the subscription',\n 'org.subscriptionStarted.settle': 'Settled a new subscription',\n 'org.successManagerCleared': 'Removed the success manager',\n 'org.successManagerSet': 'Assigned a success manager',\n 'org.upgradeProposal.propose': 'Proposed an upgrade',\n 'org.upgradeProposal.withdraw': 'Withdrew an upgrade proposal',\n 'orgs.unverified.reap': 'Removed unverified organizations',\n 'person.erased': 'Erased a person',\n 'person.erasure-requested': 'Requested erasure of a person',\n 'plan.name': 'Renamed a plan',\n 'plugins.artifacts.reap': 'Removed stale plugin builds',\n 'plugins.remoteServer.load': 'Loaded a remote plugin server',\n 'plugins.verification.decline': 'Declined a plugin verification',\n 'plugins.verifier.regression': 'Plugin verifier regression',\n 'security.pageSecurityHold': 'Put a page on security hold',\n 'security.paymentFraudHold': 'Put a workspace on hold for payment fraud',\n 'security.staffGranted': 'Granted staff access',\n 'site.package.apply': 'Applied a site package',\n 'site.package.undo': 'Undid a site package',\n 'sso.domain.driftDetected': 'Single sign-on domain drift detected',\n 'staff.evidence': 'Recorded evidence',\n 'staff.paymentFailed': 'Payment failed (staff notice)',\n 'staff.planChanged': 'Plan changed (staff notice)',\n 'staff.subscriptionCanceled': 'Subscription canceled (staff notice)',\n 'staff.subscriptionStarted': 'Subscription started (staff notice)',\n 'systemEmail.staffSend': 'Sent a system email',\n 'systemEmail.test': 'Sent a test system email',\n 'taxFilingConfig.clear': 'Cleared the tax filing settings',\n 'taxFilingConfig.update': 'Changed the tax filing settings',\n 'taxablePurchases.clear': 'Cleared taxable purchases',\n 'taxablePurchases.update': 'Changed taxable purchases',\n 'user.acquisition-viewed': 'Viewed where the account came from',\n 'user.erased': 'Erased the account',\n 'user.impersonate': 'Signed in as the account',\n 'user.nativeAppCheck': 'Verified the desktop app for the account',\n 'user.nativeAppSignIn': 'Signed in to the app through the console',\n 'user.sendPasswordReset': 'Sent a password reset',\n 'user.setAdAudienceOptOut': 'Changed the ad audience opt-out',\n 'user.setPassword': 'Set the password',\n 'user.signOutDevice': 'Signed a device out',\n 'user.updateProfile': 'Updated the profile',\n}\n\n/** Leading namespaces as a reader names them. */\nconst NAMESPACE_LABELS: Readonly<Record<string, string>> = {\n org: 'Organization',\n orgs: 'Organizations',\n user: 'Account',\n host: 'Site',\n}\n\n/** `paymentMethod` → `payment method`, `reattach-domain` → `reattach domain`. */\nfunction words(segment: string): string {\n return segment\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/[-_]+/g, ' ')\n .toLowerCase()\n .trim()\n}\n\n/** A code nobody named, as words: `billing.invoice.paid` → `Billing: invoice paid`. */\nexport function humanizeActivityCode(code: string): string {\n const [head = '', ...rest] = code.trim().split('.').filter(Boolean)\n const lead = NAMESPACE_LABELS[head] ?? words(head).replace(/^./, (c) => c.toUpperCase())\n if (!rest.length) return lead\n return `${lead}: ${rest.map(words).join(' ')}`\n}\n\n/** What a staff audit code reads as, everywhere it is shown. */\nexport function staffAuditActionLabel(action: string | null | undefined): string {\n const code = action?.trim() ?? ''\n if (!code) return '—'\n return (\n STAFF_AUDIT_ACTION_LABELS[code] ??\n pluginStaffAuditActionLabel(code) ??\n (isActivityCode(code) ? humanizeActivityCode(code) : code)\n )\n}\n\n/** The collections an audit path walks, named for a reader. */\nconst COLLECTION_NOUNS: Readonly<Record<string, string>> = {\n orgs: 'Organization',\n hosts: 'Site',\n users: 'Account',\n members: 'Member',\n invites: 'Invitation',\n screens: 'Page',\n layouts: 'Layout',\n components: 'Component',\n templates: 'Template',\n media: 'Media',\n emailDeliveries: 'Email',\n coupons: 'Coupon',\n flags: 'Feature flag',\n plugins: 'Plugin',\n subscriptions: 'Subscription',\n}\n\n/** `orgs/a/aiJobs/b` → `{ orgs: 'a', aiJobs: 'b' }`, in walk order. */\nfunction pathPairs(path: string): Array<[string, string]> {\n const segments = path.split('/').filter(Boolean)\n const pairs: Array<[string, string]> = []\n for (let at = 0; at < segments.length; at += 2) {\n pairs.push([segments[at] ?? '', segments[at + 1] ?? ''])\n }\n return pairs\n}\n\n/** The stored audit row, read defensively. */\nexport interface StaffAuditEntryLike {\n action?: string | null\n target?: string | null\n subjectUid?: string | null\n reason?: string | null\n note?: string | null\n /** The state the act left; AI rows carry `{ label, hostId, credits }`. */\n after?: Record<string, unknown> | null\n}\n\nconst str = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\nconst num = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\n/** What an audit act did, in words, and the words it was about. */\nexport function describeStaffAudit(\n entry: StaffAuditEntryLike,\n names: ActivityNames = {},\n): ActivityDescription {\n const code = str(entry.action)\n const path = str(entry.target)\n const after = entry.after ?? {}\n const pairs = path && path.includes('/') ? pathPairs(path) : []\n const idOf = (collection: string) => pairs.find(([name]) => name === collection)?.[1] || null\n const orgId = idOf('orgs')\n // A plugin's job collection (the AI plugin's jobs) names the job the row\n // links to; core knows it only through the plugin's declaration.\n const jobPair = pairs.find(([name]) => pluginStaffAuditCollection(name)?.job)\n const jobId = jobPair?.[1] || null\n const hostId = str(after['hostId']) ?? idOf('hosts')\n const uid = idOf('users') ?? str(entry.subjectUid)\n const label = str(after['label'])\n // A plugin may word the row from what the act left: the AI plugin names\n // what a job made (`Created page Home with Aglyn AI`).\n const declared = code ? pluginStaffAuditDescribe(code, after) : undefined\n const action = declared?.action ?? staffAuditActionLabel(code)\n\n const site = hostId ? (names.hosts?.[hostId] ?? null) : null\n const org = orgId ? (names.orgs?.[orgId] ?? null) : null\n const person = uid ? (names.users?.[uid] ?? null) : null\n const last = pairs[pairs.length - 1]\n const parts: string[] = []\n if (site) parts.push(site)\n else if (org) parts.push(org)\n if (jobPair) parts.push(label ?? pluginStaffAuditCollection(jobPair[0])?.noun ?? 'Job')\n else if (last && last[0] === 'users') parts.push(person ?? 'Account')\n else if (last && last[0] !== 'orgs' && last[0] !== 'hosts') {\n parts.push(\n COLLECTION_NOUNS[last[0]] ??\n pluginStaffAuditCollection(last[0])?.noun ??\n activityTypeLabel(last[0]),\n )\n }\n if (!parts.length) {\n if (last) parts.push(COLLECTION_NOUNS[last[0]] ?? pluginStaffAuditCollection(last[0])?.noun ?? 'Item')\n else if (path) parts.push(isActivityCode(path) || /^[\\w-]{16,}$/.test(path) ? 'Platform' : path)\n else parts.push('—')\n }\n\n const result = str(after['result']) ?? str(after['status']) ?? declared?.result ?? null\n\n return {\n action,\n target: parts.join(' · '),\n why: orgOverrideReasonSummary(entry.reason ?? null, entry.note ?? null) ?? str(entry.note),\n credits: num(after['credits']),\n result,\n code,\n path,\n orgId,\n hostId,\n jobId,\n uid,\n }\n}\n\n/** A stored activity row, read defensively, with where it was read from. */\nexport interface ActivityRowLike {\n action?: string | null\n target?: (ActivityTargetLike & { jobId?: string; credits?: number }) | null\n /** `host` or `org`: which log the row came from. */\n scopeType?: string\n scopeId?: string\n}\n\n/**\n * An activity row as the lists show it. Where is the site when the row came\n * from a site's log, else the organization.\n */\nexport function describeActivity(\n entry: ActivityRowLike,\n names: ActivityNames = {},\n): ActivityDescription {\n const stored = str(entry.action)\n const code = isActivityCode(stored) ? stored : null\n const target = entry.target ?? null\n const hostId = entry.scopeType === 'host' ? (entry.scopeId ?? null) : null\n const orgId = entry.scopeType === 'org' ? (entry.scopeId ?? null) : null\n const site = hostId ? (names.hosts?.[hostId] ?? null) : null\n const type = str(target?.type)\n const jobId = isPluginJobTargetType(type) ? str(target?.id) : str(target?.jobId)\n const noun = type ? (pluginActivityTargetLabel(type) ?? activityTypeLabel(type)) : null\n const item = str(target?.name) ?? noun\n const parts = [site, item].filter((part): part is string => Boolean(part))\n return {\n action: activityActionSentence(stored ?? undefined, target) || '—',\n target: parts.join(' · ') || '—',\n why: null,\n credits: num(target?.credits),\n result: null,\n code,\n path: type ? `${type}${target?.id ? `/${target.id}` : ''}` : null,\n orgId,\n hostId,\n jobId,\n uid: type === 'member' ? str(target?.id) : null,\n }\n}\n"],"names":["activityActionLabel","activityPrimaryText","activityTypeLabel","orgOverrideReasonSummary","isPluginJobTargetType","pluginActivityActionSentence","pluginActivityTargetLabel","pluginStaffAuditActionLabel","pluginStaffAuditCollection","pluginStaffAuditDescribe","activityTargetPhrase","target","noun","type","lower","charAt","toLowerCase","slice","name","trim","activityActionSentence","action","stored","sentence","replace","activityRowText","entry","isActivityCode","test","STAFF_AUDIT_ACTION_LABELS","NAMESPACE_LABELS","org","orgs","user","host","words","segment","humanizeActivityCode","code","head","rest","split","filter","Boolean","lead","c","toUpperCase","length","map","join","staffAuditActionLabel","COLLECTION_NOUNS","hosts","users","members","invites","screens","layouts","components","templates","media","emailDeliveries","coupons","flags","plugins","subscriptions","pathPairs","path","segments","pairs","at","push","str","value","num","Number","isFinite","describeStaffAudit","names","idOf","label","after","includes","collection","find","orgId","jobPair","job","jobId","hostId","uid","subjectUid","declared","undefined","site","person","last","parts","result","why","reason","note","credits","describeActivity","scopeType","scopeId","id","item","part"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC,GAED,SACEA,mBAAmB,EACnBC,mBAAmB,EACnBC,iBAAiB,QAGZ,0BAAsB;AAC7B,SAASC,w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ClC,MAAMqF,QAAQ;QAACH;QAAMa;KAAK,CAACjE,MAAM,CAAC,CAACkE,OAAyBjE,QAAQiE;IACpE,OAAO;QACLvF,QAAQD,uBAAuBE,iBAAAA,SAAUuE,WAAWlF,WAAW;QAC/DA,QAAQsF,MAAMhD,IAAI,CAAC,UAAU;QAC7BkD,KAAK;QACLG,SAAS5B,IAAI/D,0BAAAA,OAAQ2F,OAAO;QAC5BJ,QAAQ;QACR5D;QACA6B,MAAMtD,OAAO,GAAGA,OAAOF,CAAAA,0BAAAA,OAAQ+F,EAAE,IAAG,CAAC,CAAC,EAAE/F,OAAO+F,EAAE,EAAE,GAAG,IAAI,GAAG;QAC7DrB;QACAI;QACAD;QACAE,KAAK7E,SAAS,WAAW2D,IAAI7D,0BAAAA,OAAQ+F,EAAE,IAAI;IAC7C;AACF"}
1
+ {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/activity-labels.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 * ONE LABEL MAP FOR EVERY ACTIVITY AND AUDIT LIST (AGL-3660).\n *\n * Two logs feed the console's lists. The activity logs\n * (`orgs/{id}/activity`, `hosts/{id}/activity`) store a prose sentence or a\n * plugin's code plus a `{ type, id, name }` target. The staff audit trail\n * (`adminAudit`) stores a dotted code (`ai.job.output`, `org.override`) and\n * a Firestore PATH as its target (`orgs/abc/aiJobs/xyz`). The staff tables\n * printed both raw, so a reader saw `ai.job.output` next to\n * `orgs/9fK…/aiJobs/Qe2…` and had to know the schema to read their own\n * audit trail.\n *\n * Every list now draws its words from here: an action as a sentence\n * (`Created page Home with Aglyn AI`), a target as the site and the item,\n * and — for an audit row — why, the credits it spent and what came of it.\n * The raw code and path are kept on the description, for a tooltip and for\n * the staff details dialog, and never as the visible text.\n */\n\nimport {\n activityActionLabel,\n activityPrimaryText,\n activityTypeLabel,\n type ActivityEntryLike,\n type ActivityTargetLike,\n} from './activity-presenter'\nimport { orgOverrideReasonSummary } from './org-override-reason'\nimport {\n isPluginJobTargetType,\n pluginActivityActionSentence,\n pluginActivityTargetLabel,\n pluginStaffAuditActionLabel,\n pluginStaffAuditCollection,\n pluginStaffAuditDescribe,\n} from '../plugin-manager/plugin-activity-actions'\n\n/** What a list row and the details dialog show for one entry. */\nexport interface ActivityDescription {\n /** The act, as a sentence. Never a code. */\n action: string\n /** What it was done to, in words: the site and the item. Never a path. */\n target: string\n /** Why it was done, when the writer recorded a reason. */\n why: string | null\n /** AI credits it spent, when it spent any. */\n credits: number | null\n /** What came of it, when the writer recorded an outcome. */\n result: string | null\n /** The stored code, when the action was one — for a tooltip and staff. */\n code: string | null\n /** The stored target path (audit) or `type/id` (activity) — staff only. */\n path: string | null\n /** The organization the entry concerns, when it names one. */\n orgId: string | null\n /** The site the entry concerns, when it names one. */\n hostId: string | null\n /** The plugin job behind the entry (an AI job), when there is one. */\n jobId: string | null\n /** The account the entry concerns, when it names one. */\n uid: string | null\n}\n\n/** Names a route resolved for the ids an entry carries. */\nexport interface ActivityNames {\n /** Organization name by org id. */\n orgs?: Readonly<Record<string, string | null | undefined>>\n /** Site name by host id. */\n hosts?: Readonly<Record<string, string | null | undefined>>\n /** An account's address (or name) by uid. */\n users?: Readonly<Record<string, string | null | undefined>>\n}\n\n/** `screen` → `page`, `Home` → `page Home`: the noun a sentence uses. */\nexport function activityTargetPhrase(target: ActivityTargetLike | null | undefined): string {\n const noun = activityTypeLabel(target?.type)\n const lower = noun === 'Item' ? 'item' : noun.charAt(0).toLowerCase() + noun.slice(1)\n const name = target?.name?.trim()\n return name ? `${lower} ${name}` : lower\n}\n\n/**\n * An activity row's action as a sentence about its target. A plugin code\n * with a declared sentence fills it (`Created {target} with Aglyn AI`); any\n * other code reads as its label, and a prose action as itself.\n */\nexport function activityActionSentence(\n action: string | undefined,\n target?: ActivityTargetLike | null,\n): string {\n const stored = action?.trim() ?? ''\n const sentence = pluginActivityActionSentence(stored)\n if (sentence) return sentence.replace('{target}', activityTargetPhrase(target))\n return activityActionLabel(stored)\n}\n\n/**\n * A one-column feed's line: the sentence when the code declares one, else\n * the action with its target's name (`Saved the screen — Home`).\n */\nexport function activityRowText(entry: ActivityEntryLike): string {\n const stored = entry.action?.trim() ?? ''\n return pluginActivityActionSentence(stored)\n ? activityActionSentence(stored, entry.target)\n : activityPrimaryText(entry)\n}\n\n/** Whether a stored action is a dotted code rather than a sentence. */\nexport function isActivityCode(action: unknown): action is string {\n return typeof action === 'string' && /^[a-z][\\w-]*(\\.[\\w-]+)+$/i.test(action.trim())\n}\n\n/*==========================================\n * THE STAFF AUDIT TRAIL'S WORDS.\n *\n * Every code core's doors write. A plugin's doors declare their own through\n * `staffAuditLabels` (the AI plugin's `ai.job.*`), and a code neither knows\n * is humanized from its segments rather than shown raw, so a new writer\n * reads as `Billing: invoice paid` until somebody names it properly.\n *==========================================*/\nexport const STAFF_AUDIT_ACTION_LABELS: Readonly<Record<string, string>> = {\n 'account.closed.self': 'Closed their own account',\n 'account.exported.self': 'Exported their own account data',\n 'ai-usage.exported': 'Exported AI usage',\n 'billing.assistOverage.setCap': 'Set the AI overage ceiling',\n 'billing.assistOverage.setHardCap': 'Set the AI stop-at-band switch',\n 'billing.autoLocked': 'Locked automatically for billing',\n 'billing.bundle-link-minted': 'Made a bundle checkout link',\n 'billing.collaboratorAllocation': 'Changed collaborator seats',\n 'billing.dispute.opened': 'Payment dispute opened',\n 'billing.disputeClosed': 'Payment dispute closed',\n 'billing.disputeOpened': 'Payment dispute opened',\n 'billing.disputeUnattributed': 'Unattributed payment dispute',\n 'billing.invoice': 'Invoice event',\n 'billing.invoice.closed': 'Invoice closed',\n 'billing.invoice.failed': 'Invoice payment failed',\n 'billing.invoice.paid': 'Invoice paid',\n 'billing.manage': 'Opened billing management',\n 'billing.orphanedSubscription': 'Found a subscription with no workspace',\n 'billing.paymentFailed': 'Payment failed',\n 'billing.paymentMethod.changed': 'Changed the payment method',\n 'billing.platformDisputeLost': 'Lost a payment dispute',\n 'billing.platformInvoiceUncollectible': 'Invoice marked uncollectible',\n 'billing.registerAllocation': 'Changed register allocation',\n 'billing.storageOverage.setCap': 'Set the storage overage ceiling',\n 'billing.subscriptionCanceled': 'Subscription canceled',\n 'billing.usage': 'Recorded usage',\n 'billing.usageBudget.set': 'Set the usage budget',\n 'billing.view': 'Viewed billing',\n 'billing.webhookInert': 'Ignored a billing webhook',\n 'billing.webhookSignatureRejected': 'Rejected a billing webhook signature',\n 'broadcast.send': 'Sent a broadcast',\n 'client-build.preview-sent': 'Sent a client build preview',\n 'contact.phone.erased': 'Erased a phone number',\n 'contact.suppression.recorded': 'Added a contact suppression',\n 'contact.suppression.released': 'Released a contact suppression',\n 'coupon.create': 'Created a coupon',\n 'coupon.promotion_code.update': 'Updated a promotion code',\n 'data.transfer.export': 'Exported data',\n 'data.transfer.plan': 'Planned a data transfer',\n 'email.history-imported': 'Imported email history',\n 'email.message-viewed': 'Viewed an email message',\n 'email.sending-domains.reap': 'Removed unused sending domains',\n 'email.suppression.release': 'Released an email suppression',\n 'emailSendRate.update': 'Changed the email send rate',\n 'erasure.runBatch': 'Ran an erasure batch',\n 'erasures.replayed': 'Replayed erasures',\n 'firestore.export': 'Exported the database',\n 'firstPartyHosts.update': 'Changed first-party sites',\n 'flags.update': 'Changed feature flags',\n 'freeWorkspaceCap.update': 'Changed the free workspace cap',\n 'host.deleted': 'Deleted a site',\n 'host.domain.released': 'Released a domain',\n 'host.reattach-domain': 'Reattached a domain',\n 'host.set-subdomain': 'Changed a site address',\n 'host.transfer': 'Transferred a site',\n 'host.usageLevel': 'Set the site usage level',\n 'lockdown.lock': 'Locked the workspace down',\n 'lockdown.payouts-pause': 'Paused payouts',\n 'lockdown.payouts-restore': 'Restored payouts',\n 'lockdown.renewals-pause': 'Paused renewals',\n 'lockdown.renewals-resume': 'Resumed renewals',\n 'lockdown.resend-notice': 'Resent the lockdown notice',\n 'maintenance.auditArchive.run': 'Archived the audit log',\n 'maintenance.reapArtifacts.run': 'Removed stale build artifacts',\n 'maintenance.reverifyPlugins.run': 'Re-verified plugins',\n 'operatorAlerts.test': 'Sent a test operator alert',\n 'operatorAlerts.update': 'Changed operator alerts',\n 'org.acquisition-viewed': 'Viewed where the organization came from',\n 'org.auditLog': 'Viewed the organization audit log',\n 'org.discount.apply': 'Applied a discount',\n 'org.discount.remove': 'Removed a discount',\n 'org.enterprise.provision': 'Provisioned enterprise billing',\n 'org.erase-failed': 'Organization erasure failed',\n 'org.erased': 'Erased the organization',\n 'org.erasureCanceled': 'Canceled the organization erasure',\n 'org.erasureRequested': 'Requested organization erasure',\n 'org.exported': 'Exported the organization',\n 'org.name': 'Renamed the organization',\n 'org.note': 'Added a staff note',\n 'org.override': 'Overrode the plan',\n 'org.refund': 'Issued a refund',\n 'org.seatAddons.changed': 'Changed seat add-ons',\n 'org.sso.enforceSignInMethods': 'Changed enforced sign-in methods',\n 'org.sso.jit': 'Changed single sign-on provisioning',\n 'org.subscription-cancel': 'Canceled the subscription',\n 'org.subscriptionStarted.settle': 'Settled a new subscription',\n 'org.successManagerCleared': 'Removed the success manager',\n 'org.successManagerSet': 'Assigned a success manager',\n 'org.upgradeProposal.propose': 'Proposed an upgrade',\n 'org.upgradeProposal.withdraw': 'Withdrew an upgrade proposal',\n 'org.usageLevel': 'Set the workspace usage level',\n 'orgs.unverified.reap': 'Removed unverified organizations',\n 'person.erased': 'Erased a person',\n 'person.erasure-requested': 'Requested erasure of a person',\n 'plan.name': 'Renamed a plan',\n 'plugins.artifacts.reap': 'Removed stale plugin builds',\n 'plugins.remoteServer.load': 'Loaded a remote plugin server',\n 'plugins.verification.decline': 'Declined a plugin verification',\n 'plugins.verifier.regression': 'Plugin verifier regression',\n 'security.pageSecurityHold': 'Put a page on security hold',\n 'security.paymentFraudHold': 'Put a workspace on hold for payment fraud',\n 'security.staffGranted': 'Granted staff access',\n 'site.package.apply': 'Applied a site package',\n 'site.package.undo': 'Undid a site package',\n 'sso.domain.driftDetected': 'Single sign-on domain drift detected',\n 'staff.evidence': 'Recorded evidence',\n 'staff.paymentFailed': 'Payment failed (staff notice)',\n 'staff.planChanged': 'Plan changed (staff notice)',\n 'staff.subscriptionCanceled': 'Subscription canceled (staff notice)',\n 'staff.subscriptionStarted': 'Subscription started (staff notice)',\n 'systemEmail.staffSend': 'Sent a system email',\n 'systemEmail.test': 'Sent a test system email',\n 'taxFilingConfig.clear': 'Cleared the tax filing settings',\n 'taxFilingConfig.update': 'Changed the tax filing settings',\n 'taxablePurchases.clear': 'Cleared taxable purchases',\n 'taxablePurchases.update': 'Changed taxable purchases',\n 'user.acquisition-viewed': 'Viewed where the account came from',\n 'user.erased': 'Erased the account',\n 'user.impersonate': 'Signed in as the account',\n 'user.nativeAppCheck': 'Verified the desktop app for the account',\n 'user.nativeAppSignIn': 'Signed in to the app through the console',\n 'user.sendPasswordReset': 'Sent a password reset',\n 'user.setAdAudienceOptOut': 'Changed the ad audience opt-out',\n 'user.setPassword': 'Set the password',\n 'user.signOutDevice': 'Signed a device out',\n 'user.updateProfile': 'Updated the profile',\n 'user.usageLevel': 'Set the account usage level',\n}\n\n/** Leading namespaces as a reader names them. */\nconst NAMESPACE_LABELS: Readonly<Record<string, string>> = {\n org: 'Organization',\n orgs: 'Organizations',\n user: 'Account',\n host: 'Site',\n}\n\n/** `paymentMethod` → `payment method`, `reattach-domain` → `reattach domain`. */\nfunction words(segment: string): string {\n return segment\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/[-_]+/g, ' ')\n .toLowerCase()\n .trim()\n}\n\n/** A code nobody named, as words: `billing.invoice.paid` → `Billing: invoice paid`. */\nexport function humanizeActivityCode(code: string): string {\n const [head = '', ...rest] = code.trim().split('.').filter(Boolean)\n const lead = NAMESPACE_LABELS[head] ?? words(head).replace(/^./, (c) => c.toUpperCase())\n if (!rest.length) return lead\n return `${lead}: ${rest.map(words).join(' ')}`\n}\n\n/** What a staff audit code reads as, everywhere it is shown. */\nexport function staffAuditActionLabel(action: string | null | undefined): string {\n const code = action?.trim() ?? ''\n if (!code) return '—'\n return (\n STAFF_AUDIT_ACTION_LABELS[code] ??\n pluginStaffAuditActionLabel(code) ??\n (isActivityCode(code) ? humanizeActivityCode(code) : code)\n )\n}\n\n/** The collections an audit path walks, named for a reader. */\nconst COLLECTION_NOUNS: Readonly<Record<string, string>> = {\n orgs: 'Organization',\n hosts: 'Site',\n users: 'Account',\n members: 'Member',\n invites: 'Invitation',\n screens: 'Page',\n layouts: 'Layout',\n components: 'Component',\n templates: 'Template',\n media: 'Media',\n emailDeliveries: 'Email',\n coupons: 'Coupon',\n flags: 'Feature flag',\n plugins: 'Plugin',\n subscriptions: 'Subscription',\n}\n\n/** `orgs/a/aiJobs/b` → `{ orgs: 'a', aiJobs: 'b' }`, in walk order. */\nfunction pathPairs(path: string): Array<[string, string]> {\n const segments = path.split('/').filter(Boolean)\n const pairs: Array<[string, string]> = []\n for (let at = 0; at < segments.length; at += 2) {\n pairs.push([segments[at] ?? '', segments[at + 1] ?? ''])\n }\n return pairs\n}\n\n/** The stored audit row, read defensively. */\nexport interface StaffAuditEntryLike {\n action?: string | null\n target?: string | null\n subjectUid?: string | null\n reason?: string | null\n note?: string | null\n /** The state the act left; AI rows carry `{ label, hostId, credits }`. */\n after?: Record<string, unknown> | null\n}\n\nconst str = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\nconst num = (value: unknown): number | null =>\n typeof value === 'number' && Number.isFinite(value) ? value : null\n\n/** What an audit act did, in words, and the words it was about. */\nexport function describeStaffAudit(\n entry: StaffAuditEntryLike,\n names: ActivityNames = {},\n): ActivityDescription {\n const code = str(entry.action)\n const path = str(entry.target)\n const after = entry.after ?? {}\n const pairs = path && path.includes('/') ? pathPairs(path) : []\n const idOf = (collection: string) => pairs.find(([name]) => name === collection)?.[1] || null\n const orgId = idOf('orgs')\n // A plugin's job collection (the AI plugin's jobs) names the job the row\n // links to; core knows it only through the plugin's declaration.\n const jobPair = pairs.find(([name]) => pluginStaffAuditCollection(name)?.job)\n const jobId = jobPair?.[1] || null\n const hostId = str(after['hostId']) ?? idOf('hosts')\n const uid = idOf('users') ?? str(entry.subjectUid)\n const label = str(after['label'])\n // A plugin may word the row from what the act left: the AI plugin names\n // what a job made (`Created page Home with Aglyn AI`).\n const declared = code ? pluginStaffAuditDescribe(code, after) : undefined\n const action = declared?.action ?? staffAuditActionLabel(code)\n\n const site = hostId ? (names.hosts?.[hostId] ?? null) : null\n const org = orgId ? (names.orgs?.[orgId] ?? null) : null\n const person = uid ? (names.users?.[uid] ?? null) : null\n const last = pairs[pairs.length - 1]\n const parts: string[] = []\n if (site) parts.push(site)\n else if (org) parts.push(org)\n if (jobPair) parts.push(label ?? pluginStaffAuditCollection(jobPair[0])?.noun ?? 'Job')\n else if (last && last[0] === 'users') parts.push(person ?? 'Account')\n else if (last && last[0] !== 'orgs' && last[0] !== 'hosts') {\n parts.push(\n COLLECTION_NOUNS[last[0]] ??\n pluginStaffAuditCollection(last[0])?.noun ??\n activityTypeLabel(last[0]),\n )\n }\n if (!parts.length) {\n if (last) parts.push(COLLECTION_NOUNS[last[0]] ?? pluginStaffAuditCollection(last[0])?.noun ?? 'Item')\n else if (path) parts.push(isActivityCode(path) || /^[\\w-]{16,}$/.test(path) ? 'Platform' : path)\n else parts.push('—')\n }\n\n const result = str(after['result']) ?? str(after['status']) ?? declared?.result ?? null\n\n return {\n action,\n target: parts.join(' · '),\n why: orgOverrideReasonSummary(entry.reason ?? null, entry.note ?? null) ?? str(entry.note),\n credits: num(after['credits']),\n result,\n code,\n path,\n orgId,\n hostId,\n jobId,\n uid,\n }\n}\n\n/** A stored activity row, read defensively, with where it was read from. */\nexport interface ActivityRowLike {\n action?: string | null\n target?: (ActivityTargetLike & { jobId?: string; credits?: number }) | null\n /** `host` or `org`: which log the row came from. */\n scopeType?: string\n scopeId?: string\n}\n\n/**\n * An activity row as the lists show it. Where is the site when the row came\n * from a site's log, else the organization.\n */\nexport function describeActivity(\n entry: ActivityRowLike,\n names: ActivityNames = {},\n): ActivityDescription {\n const stored = str(entry.action)\n const code = isActivityCode(stored) ? stored : null\n const target = entry.target ?? null\n const hostId = entry.scopeType === 'host' ? (entry.scopeId ?? null) : null\n const orgId = entry.scopeType === 'org' ? (entry.scopeId ?? null) : null\n const site = hostId ? (names.hosts?.[hostId] ?? null) : null\n const type = str(target?.type)\n const jobId = isPluginJobTargetType(type) ? str(target?.id) : str(target?.jobId)\n const noun = type ? (pluginActivityTargetLabel(type) ?? activityTypeLabel(type)) : null\n const item = str(target?.name) ?? noun\n const parts = [site, item].filter((part): part is string => Boolean(part))\n return {\n action: activityActionSentence(stored ?? undefined, target) || '—',\n target: parts.join(' · ') || '—',\n why: null,\n credits: num(target?.credits),\n result: null,\n code,\n path: type ? `${type}${target?.id ? `/${target.id}` : ''}` : null,\n orgId,\n hostId,\n jobId,\n uid: type === 'member' ? str(target?.id) : null,\n }\n}\n"],"names":["activityActionLabel","activityPrimaryText","activityTypeLabel","orgOverrideReasonSummary","isPluginJobTargetType","pluginActivityActionSentence","pluginActivityTargetLabel","pluginStaffAuditActionLabel","pluginStaffAuditCollection","pluginStaffAuditDescribe","activityTargetPhrase","target","noun","type","lower","charAt","toLowerCase","slice","name","trim","activityActionSentence","action","stored","sentence","replace","activityRowText","entry","isActivityCode","test","STAFF_AUDIT_ACTION_LABELS","NAMESPACE_LABELS","org","orgs","user","host","words","segment","humanizeActivityCode","code","head","rest","split","filter","Boolean","lead","c","toUpperCase","length","map","join","staffAuditActionLabel","COLLECTION_NOUNS","hosts","users","members","invites","screens","layouts","components","templates","media","emailDeliveries","coupons","flags","plugins","subscriptions","pathPairs","path","segments","pairs","at","push","str","value","num","Number","isFinite","describeStaffAudit","names","idOf","label","after","includes","collection","find","orgId","jobPair","job","jobId","hostId","uid","subjectUid","declared","undefined","site","person","last","parts","result","why","reason","note","credits","describeActivity","scopeType","scopeId","id","item","part"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;CAiBC,GAED,SACEA,mBAAmB,EACnBC,mBAAmB,EACnBC,iBAAiB,QAGZ,0BAAsB;AAC7B,SAASC,wBAAwB,QAAQ,2BAAuB;AAChE,SACEC,qBAAqB,EACrBC,4BAA4B,EAC5BC,yBAAyB,EACzBC,2BAA2B,EAC3BC,0BAA0B,EAC1BC,wBAAwB,QACnB,+CAA2C;AAsClD,uEAAuE,GACvE,OAAO,SAASC,qBAAqBC,MAA6C;QAGnEA;IAFb,MAAMC,OAAOV,kBAAkBS,0BAAAA,OAAQE,IAAI;IAC3C,MAAMC,QAAQF,SAAS,SAAS,SAASA,KAAKG,MAAM,CAAC,GAAGC,WAAW,KAAKJ,KAAKK,KAAK,CAAC;IACnF,MAAMC,OAAOP,2BAAAA,eAAAA,OAAQO,IAAI,qBAAZP,aAAcQ,IAAI;IAC/B,OAAOD,OAAO,GAAGJ,MAAM,CAAC,EAAEI,MAAM,GAAGJ;AACrC;AAEA;;;;CAIC,GACD,OAAO,SAASM,uBACdC,MAA0B,EAC1BV,MAAkC;;IAElC,MAAMW,iBAASD,0BAAAA,OAAQF,IAAI,qBAAM;IACjC,MAAMI,WAAWlB,6BAA6BiB;IAC9C,IAAIC,UAAU,OAAOA,SAASC,OAAO,CAAC,YAAYd,qBAAqBC;IACvE,OAAOX,oBAAoBsB;AAC7B;AAEA;;;CAGC,GACD,OAAO,SAASG,gBAAgBC,KAAwB;;QACvCA;IAAf,MAAMJ,kBAASI,gBAAAA,MAAML,MAAM,qBAAZK,cAAcP,IAAI,qBAAM;IACvC,OAAOd,6BAA6BiB,UAChCF,uBAAuBE,QAAQI,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,YAAa,CAACW,OAAO,mBAAI,OAAQ;IACxD,MAAM5E,OAAO2D,IAAI7D,0BAAAA,OAAQE,IAAI;IAC7B,MAAM2E,QAAQpF,sBAAsBS,QAAQ2D,IAAI7D,0BAAAA,OAAQ+F,EAAE,IAAIlC,IAAI7D,0BAAAA,OAAQ6E,KAAK;IAC/E,MAAM5E,OAAOC,QAAQP,6BAAAA,0BAA0BO,iBAA1BP,6BAAmCJ,kBAAkBW,QAAS;IACnF,MAAM8F,QAAOnC,OAAAA,IAAI7D,0BAAAA,OAAQO,IAAI,aAAhBsD,OAAqB5D;IAClC,MAAMqF,QAAQ;QAACH;QAAMa;KAAK,CAACjE,MAAM,CAAC,CAACkE,OAAyBjE,QAAQiE;IACpE,OAAO;QACLvF,QAAQD,uBAAuBE,iBAAAA,SAAUuE,WAAWlF,WAAW;QAC/DA,QAAQsF,MAAMhD,IAAI,CAAC,UAAU;QAC7BkD,KAAK;QACLG,SAAS5B,IAAI/D,0BAAAA,OAAQ2F,OAAO;QAC5BJ,QAAQ;QACR5D;QACA6B,MAAMtD,OAAO,GAAGA,OAAOF,CAAAA,0BAAAA,OAAQ+F,EAAE,IAAG,CAAC,CAAC,EAAE/F,OAAO+F,EAAE,EAAE,GAAG,IAAI,GAAG;QAC7DrB;QACAI;QACAD;QACAE,KAAK7E,SAAS,WAAW2D,IAAI7D,0BAAAA,OAAQ+F,EAAE,IAAI;IAC7C;AACF"}
@@ -86,7 +86,7 @@
86
86
  * for, so a new month simply stops matching. A cap whose lift depends on a
87
87
  * write is a cap that stays engaged when the writer fails.
88
88
  */
89
- import type { AglynOrgBilling } from '../foundation';
89
+ import type { AglynOrgBilling, OrgBandwidthCap } from '../foundation';
90
90
  /**
91
91
  * The month key the marker is stamped with: UTC `YYYY-MM`, the same shape as
92
92
  * `utcMonthKey` and the `orgs/{id}/usage/{month}` document id, and the
@@ -135,6 +135,70 @@ export declare const BANDWIDTH_CAP_RETRY_AFTER_SECONDS = 3600;
135
135
  * the incident.
136
136
  */
137
137
  export declare function bandwidthCapEngaged(org: Partial<AglynOrgBilling> | null | undefined, now?: Date): boolean;
138
+ /**
139
+ * How long the ONE-TIME grace keeps a site online past its band (AGL-4232):
140
+ * the first time a site goes over, ever, it stays up this long so its owner
141
+ * can upgrade before visitors are turned away.
142
+ */
143
+ export declare const BANDWIDTH_CAP_GRACE_MS: number;
144
+ /**
145
+ * When the grace ends, while one is running for this org this month; `null`
146
+ * when the org is not over its band, is already paused, or never had one.
147
+ * The owner's surfaces read this to say "upgrade or your site pauses on …".
148
+ */
149
+ export declare function bandwidthCapGraceUntil(org: Partial<AglynOrgBilling> | null | undefined, now?: Date): number | null;
150
+ /**
151
+ * The marker a writer stamps when the cap engages (AGL-1967/2155, AGL-4232):
152
+ * the month and its diagnostics, plus the grace window when the org's sites
153
+ * have never had one. ONE shape for every writer, so a reader cannot tell
154
+ * which of them stamped it.
155
+ */
156
+ export declare function bandwidthCapMarker(options: {
157
+ month: string;
158
+ nowMs: number;
159
+ pageViews: number;
160
+ includedPageViews: number;
161
+ /** When the grace this engagement carries ends; null for none. */
162
+ graceUntil: number | null;
163
+ }): OrgBandwidthCap;
164
+ /** A grace stamp as stored: epoch ms, or anything else meaning "never". */
165
+ type GraceStamped = {
166
+ bandwidthGraceUsedAt?: unknown;
167
+ } | null | undefined;
168
+ /**
169
+ * The grace an engagement carries (AGL-4232), from the workspace's own stamp
170
+ * (`orgs/{id}.bandwidthGraceUsedAt`) and its sites' stamps as read: a NEW one
171
+ * when neither the workspace nor any of its sites has ever had it, the one
172
+ * ALREADY RUNNING when a stamp is still inside its window (a grace granted on
173
+ * the 29th that runs into the next month), else none.
174
+ *
175
+ * Both stamps are required absent so deleting the site and making a new one
176
+ * does not re-arm it: the grace is given once per workspace's sites.
177
+ */
178
+ export declare function bandwidthGraceForEngagement(hosts: ReadonlyArray<GraceStamped>, nowMs: number, org?: GraceStamped): {
179
+ graceUntil: number | null;
180
+ grants: boolean;
181
+ };
182
+ /**
183
+ * Whether an org's sites are owed the one-time grace by their own stamps: it
184
+ * has at least one site, and none of them has ever had it
185
+ * (`AglynHost.bandwidthGraceUsedAt`). The workspace's stamp is asked beside
186
+ * it by {@link bandwidthGraceForEngagement}.
187
+ */
188
+ export declare function bandwidthGraceAvailable(hosts: ReadonlyArray<GraceStamped>): boolean;
189
+ /** When a `YYYY-MM` month ends: midnight UTC on the 1st of the next. */
190
+ export declare function bandwidthCapMonthEndMs(month: string): number;
191
+ /**
192
+ * Whether a grace ends only after the month it was granted in (AGL-4232).
193
+ * Then no pause comes: the new month's count starts at zero, and the site
194
+ * pauses only when it next passes the band, with no grace left.
195
+ */
196
+ export declare function bandwidthGraceOutlastsMonth(graceUntil: number, month: string): boolean;
197
+ /**
198
+ * The grace deadline as the owner reads it: an unambiguous UTC date and
199
+ * time, e.g. "Thursday, November 19 at 3:04 PM UTC".
200
+ */
201
+ export declare function formatBandwidthGraceDeadline(ms: number): string;
138
202
  /**
139
203
  * Should the cap be ENGAGED for this org-month? The writer's half of the
140
204
  * question, kept beside the reader's so the two cannot drift apart.
@@ -159,6 +223,39 @@ export declare function bandwidthCapShouldEngage(options: {
159
223
  * the two cannot disagree about which plans the cap is for.
160
224
  */
161
225
  export declare function bandwidthCapApplies(org: Partial<AglynOrgBilling> | null | undefined): boolean;
226
+ /**
227
+ * The one sentence every grace message carries (AGL-4232): the abuse ceiling
228
+ * stays the cost bound during a grace, so a surge far past the band can still
229
+ * pause the site before the deadline. Said, so the deadline is never a
230
+ * promise the ceiling breaks.
231
+ */
232
+ export declare const BANDWIDTH_GRACE_SURGE_SENTENCE = "An unusually large surge of traffic can still pause it before then.";
233
+ /**
234
+ * What the OWNER is told when a grace starts (AGL-4232), in the console and by
235
+ * email: the deadline in plain words, with the way past it. `{site}` is
236
+ * filled by the notifier from the site it reads. `used` is the writer's own
237
+ * account of what was used (page views, or traffic including media).
238
+ * `carried` is a grace granted earlier that still runs as the site goes over
239
+ * again in a new month: the same deadline, said again, since it is this
240
+ * month's news.
241
+ */
242
+ export declare function bandwidthGraceOwnerNotice(options: {
243
+ graceUntil: number;
244
+ /** The `YYYY-MM` the cap engaged for, which decides whether a pause comes. */
245
+ month: string;
246
+ used: string;
247
+ resumesOn: string;
248
+ carried?: boolean;
249
+ }): BandwidthCapNotice;
250
+ /**
251
+ * What the OWNER is told when a site is paused with no grace, or when its
252
+ * grace has ended (AGL-4232): in the console and by email, from whichever
253
+ * writer saw it. `{site}` is filled by the notifier.
254
+ */
255
+ export declare function bandwidthPausedOwnerNotice(options: {
256
+ used: string;
257
+ resumesOn: string;
258
+ }): BandwidthCapNotice;
162
259
  /** What a visitor sees on a capped site. */
163
260
  export interface BandwidthCapNotice {
164
261
  title: string;
@@ -192,3 +289,4 @@ export declare function bandwidthCapNotice(): BandwidthCapNotice;
192
289
  * status discriminates nothing and this code is the whole discriminator.
193
290
  */
194
291
  export declare const BANDWIDTH_CAP_CODE = "bandwidth-cap";
292
+ export {};
@@ -84,7 +84,9 @@
84
84
  * Nothing ever CLEARS the marker either: it names the month it was written
85
85
  * for, so a new month simply stops matching. A cap whose lift depends on a
86
86
  * write is a cap that stays engaged when the writer fails.
87
- */ import { isCustomPricedPlan, planMetersInfraOverage, resolveEffectivePlan, resolveOrgEntitlements } from "./plan-entitlements.js";
87
+ */ import { _ as _extends } from "@swc/helpers/_/_extends";
88
+ import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
89
+ import { isCustomPricedPlan, planMetersInfraOverage, resolveEffectivePlan, resolveOrgEntitlements } from "./plan-entitlements.js";
88
90
  /**
89
91
  * The month key the marker is stamped with: UTC `YYYY-MM`, the same shape as
90
92
  * `utcMonthKey` and the `orgs/{id}/usage/{month}` document id, and the
@@ -138,7 +140,108 @@
138
140
  if (!Number.isFinite(resolveOrgEntitlements(org).bandwidthGb)) return false;
139
141
  const cap = org.bandwidthCap;
140
142
  if (!cap || typeof cap !== 'object') return false;
141
- return cap.month === bandwidthCapMonthKey(now);
143
+ if (cap.month !== bandwidthCapMonthKey(now)) return false;
144
+ // The one-time grace (AGL-4232): engaged, but not refusing until it ends.
145
+ // Nothing writes at that moment; every reader re-derives it from the clock.
146
+ return !(typeof cap.graceUntil === 'number' && now.getTime() < cap.graceUntil);
147
+ }
148
+ /**
149
+ * How long the ONE-TIME grace keeps a site online past its band (AGL-4232):
150
+ * the first time a site goes over, ever, it stays up this long so its owner
151
+ * can upgrade before visitors are turned away.
152
+ */ export const BANDWIDTH_CAP_GRACE_MS = 72 * 60 * 60 * 1000;
153
+ /**
154
+ * When the grace ends, while one is running for this org this month; `null`
155
+ * when the org is not over its band, is already paused, or never had one.
156
+ * The owner's surfaces read this to say "upgrade or your site pauses on …".
157
+ */ export function bandwidthCapGraceUntil(org, now = new Date()) {
158
+ const cap = org == null ? void 0 : org.bandwidthCap;
159
+ if (!cap || typeof cap !== 'object' || cap.month !== bandwidthCapMonthKey(now)) return null;
160
+ if (typeof cap.graceUntil !== 'number' || now.getTime() >= cap.graceUntil) return null;
161
+ // Only where the cap would refuse were there no grace: an upgraded org has
162
+ // nothing to be warned about.
163
+ const { graceUntil: _running } = cap, withoutGrace = _object_without_properties_loose(cap, [
164
+ "graceUntil"
165
+ ]);
166
+ return bandwidthCapEngaged(_extends({}, org, {
167
+ bandwidthCap: withoutGrace
168
+ }), now) ? cap.graceUntil : null;
169
+ }
170
+ /**
171
+ * The marker a writer stamps when the cap engages (AGL-1967/2155, AGL-4232):
172
+ * the month and its diagnostics, plus the grace window when the org's sites
173
+ * have never had one. ONE shape for every writer, so a reader cannot tell
174
+ * which of them stamped it.
175
+ */ export function bandwidthCapMarker(options) {
176
+ return _extends({
177
+ month: options.month,
178
+ engagedAt: options.nowMs,
179
+ pageViews: Math.round(options.pageViews),
180
+ includedPageViews: Math.round(options.includedPageViews)
181
+ }, options.graceUntil !== null ? {
182
+ graceUntil: options.graceUntil
183
+ } : {});
184
+ }
185
+ const graceStamp = (doc)=>typeof (doc == null ? void 0 : doc.bandwidthGraceUsedAt) === 'number' ? doc.bandwidthGraceUsedAt : 0;
186
+ /**
187
+ * The grace an engagement carries (AGL-4232), from the workspace's own stamp
188
+ * (`orgs/{id}.bandwidthGraceUsedAt`) and its sites' stamps as read: a NEW one
189
+ * when neither the workspace nor any of its sites has ever had it, the one
190
+ * ALREADY RUNNING when a stamp is still inside its window (a grace granted on
191
+ * the 29th that runs into the next month), else none.
192
+ *
193
+ * Both stamps are required absent so deleting the site and making a new one
194
+ * does not re-arm it: the grace is given once per workspace's sites.
195
+ */ export function bandwidthGraceForEngagement(hosts, nowMs, org) {
196
+ if (bandwidthGraceAvailable(hosts) && graceStamp(org) === 0) {
197
+ return {
198
+ graceUntil: nowMs + BANDWIDTH_CAP_GRACE_MS,
199
+ grants: true
200
+ };
201
+ }
202
+ const latest = Math.max(graceStamp(org), ...hosts.map(graceStamp));
203
+ const running = latest + BANDWIDTH_CAP_GRACE_MS;
204
+ return {
205
+ graceUntil: latest > 0 && nowMs < running ? running : null,
206
+ grants: false
207
+ };
208
+ }
209
+ /**
210
+ * Whether an org's sites are owed the one-time grace by their own stamps: it
211
+ * has at least one site, and none of them has ever had it
212
+ * (`AglynHost.bandwidthGraceUsedAt`). The workspace's stamp is asked beside
213
+ * it by {@link bandwidthGraceForEngagement}.
214
+ */ export function bandwidthGraceAvailable(hosts) {
215
+ return hosts.length > 0 && hosts.every((host)=>graceStamp(host) === 0);
216
+ }
217
+ /** When a `YYYY-MM` month ends: midnight UTC on the 1st of the next. */ export function bandwidthCapMonthEndMs(month) {
218
+ const [year, monthIndex] = month.split('-').map(Number);
219
+ return Date.UTC(year, monthIndex, 1);
220
+ }
221
+ /**
222
+ * Whether a grace ends only after the month it was granted in (AGL-4232).
223
+ * Then no pause comes: the new month's count starts at zero, and the site
224
+ * pauses only when it next passes the band, with no grace left.
225
+ */ export function bandwidthGraceOutlastsMonth(graceUntil, month) {
226
+ return graceUntil >= bandwidthCapMonthEndMs(month);
227
+ }
228
+ /**
229
+ * The grace deadline as the owner reads it: an unambiguous UTC date and
230
+ * time, e.g. "Thursday, November 19 at 3:04 PM UTC".
231
+ */ export function formatBandwidthGraceDeadline(ms) {
232
+ const date = new Date(ms);
233
+ const day = date.toLocaleDateString('en-US', {
234
+ weekday: 'long',
235
+ month: 'long',
236
+ day: 'numeric',
237
+ timeZone: 'UTC'
238
+ });
239
+ const time = date.toLocaleTimeString('en-US', {
240
+ hour: 'numeric',
241
+ minute: '2-digit',
242
+ timeZone: 'UTC'
243
+ });
244
+ return `${day} at ${time} UTC`;
142
245
  }
143
246
  /**
144
247
  * Should the cap be ENGAGED for this org-month? The writer's half of the
@@ -174,6 +277,45 @@
174
277
  includedBandwidthGb: resolveOrgEntitlements(org).bandwidthGb
175
278
  });
176
279
  }
280
+ /**
281
+ * The one sentence every grace message carries (AGL-4232): the abuse ceiling
282
+ * stays the cost bound during a grace, so a surge far past the band can still
283
+ * pause the site before the deadline. Said, so the deadline is never a
284
+ * promise the ceiling breaks.
285
+ */ export const BANDWIDTH_GRACE_SURGE_SENTENCE = 'An unusually large surge of traffic can still pause it before then.';
286
+ /**
287
+ * What the OWNER is told when a grace starts (AGL-4232), in the console and by
288
+ * email: the deadline in plain words, with the way past it. `{site}` is
289
+ * filled by the notifier from the site it reads. `used` is the writer's own
290
+ * account of what was used (page views, or traffic including media).
291
+ * `carried` is a grace granted earlier that still runs as the site goes over
292
+ * again in a new month: the same deadline, said again, since it is this
293
+ * month's news.
294
+ */ export function bandwidthGraceOwnerNotice(options) {
295
+ // A grace begun in a month's last 72 hours outlasts it: the count starts
296
+ // again on the 1st, so no pause comes, and saying a date would be false.
297
+ if (bandwidthGraceOutlastsMonth(options.graceUntil, options.month)) {
298
+ return {
299
+ title: '{site} is past its monthly traffic limit and stays online',
300
+ body: `{site} has used ${options.used} this month. It stays online: the ` + `month ends before its extra time would, and its count starts again ` + `on ${options.resumesOn}. Nothing is charged for the extra traffic. ` + 'This extra time is given once and has now been used, so the next time ' + 'your sites pass their limit they pause straight away. An unusually large ' + 'surge of traffic can still pause it before the month ends. Upgrade in ' + 'Billing to keep it online whatever its traffic.'
301
+ };
302
+ }
303
+ const deadline = formatBandwidthGraceDeadline(options.graceUntil);
304
+ return {
305
+ title: `Upgrade or {site} pauses on ${deadline}`,
306
+ body: `{site} has used ${options.used} this month. ` + (options.carried ? `It stays online until ${deadline}, when the extra time it was already given ends. ` : `It stays online until ${deadline}. `) + 'Upgrade in Billing before then to keep it online; if you ' + `don't, visitors see a "temporarily unavailable" notice from then until ` + `${options.resumesOn}. ${BANDWIDTH_GRACE_SURGE_SENTENCE} Nothing is charged ` + 'for the extra traffic. This extra time is given once, so the next time your ' + 'sites pass their limit they pause straight away.'
307
+ };
308
+ }
309
+ /**
310
+ * What the OWNER is told when a site is paused with no grace, or when its
311
+ * grace has ended (AGL-4232): in the console and by email, from whichever
312
+ * writer saw it. `{site}` is filled by the notifier.
313
+ */ export function bandwidthPausedOwnerNotice(options) {
314
+ return {
315
+ title: '{site} paused — monthly traffic limit reached',
316
+ body: `{site} has used ${options.used} this month, so visitors see a ` + `"temporarily unavailable" notice instead of its pages until ` + `${options.resumesOn}. Nothing is charged for the extra traffic. The site ` + 'comes back on its own then, or as soon as you upgrade in Billing.'
317
+ };
318
+ }
177
319
  /**
178
320
  * The visitor's sentence.
179
321
  *
@@ -192,9 +334,11 @@
192
334
  * support cannot lift it. Reusing the RENDERING channel (the 503 notice page)
193
335
  * while keeping the WORDS separate is the split that keeps both honest.
194
336
  */ export function bandwidthCapNotice() {
337
+ // NEUTRAL (AGL-4232): nothing about limits, plans, traffic or pricing —
338
+ // those are the owner's to read in the console, not a visitor's.
195
339
  return {
196
- title: 'Over the monthly traffic limit',
197
- body: 'This site has used all of the traffic included with it this month, ' + 'so its pages are paused until the start of next month. Nothing is ' + 'wrong with your connection, and nothing here has been removed.'
340
+ title: 'Temporarily unavailable',
341
+ body: 'This site is temporarily unavailable.'
198
342
  };
199
343
  }
200
344
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../libs/aglyn/src/lib/app-utils/bandwidth-cap.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 * The free plan's BANDWIDTH HARD CAP (AGL-1967 / AGL-2070 / AGL-2155).\n *\n * Enforced from before public signups, so the cap is proven under real\n * traffic while the cohort is small and a mistake is cheap. The requirement\n * this module exists to make true: the free/hobby tier hard-caps, so that it\n * always actually stays free.\n *\n * Until this shipped, bandwidth was the ONE billable dimension with no\n * runtime refusal anywhere. Media ingress, forms, contacts, datasets, API and\n * seats all hard-stop on free; `bandwidthGb: 5` appeared only in the plan\n * table, in reporting arithmetic and in UI. A free site that went viral\n * served every page and Aglyn paid the egress with no ceiling.\n *\n * ## Why a MARKER on the org doc, and not a check\n *\n * The obvious implementation — read the page-view counter before rendering —\n * is the one thing this cap must not do. Page views are counted AFTER the\n * fact, by a client beacon into `hosts/{id}/analytics/{day}`; consulting them\n * per render would put a Firestore read on the hot path of every public page\n * on the platform, paid by every PAYING customer too, to answer a question\n * only free orgs can ever fail. That is the exact cost the whole ISR/cache\n * design exists to avoid.\n *\n * So the decision is made where the arithmetic already happens, and its\n * verdict is denormalized onto the org document as {@link OrgBandwidthCap}.\n * The serving path then reads it from `getOrgBilling`, the org doc it ALREADY\n * loads and caches for 60 seconds as \"the suspension gate and every\n * entitlement input for the render\". **The cap costs zero additional reads.**\n *\n * ### TWO writers, and neither is on the render path (AGL-2413)\n *\n * 1. `apps/tenant/app/api/analytics/collect` — the beacon that WRITES the\n * page-view counter, on its existing 1-in-200 sample. It already sums this\n * month with this query and already loads this org doc for the abuse\n * ceiling, so the cap rides both for free.\n * 2. `api/billing/usage-alerts` — the daily sweep, which sums page views\n * ORG-WIDE across up to 100 hosts and is therefore the backstop for any\n * org running more than one site.\n *\n * The beacon is the one that matters, and it exists because the sweep alone\n * was not a cap at all: it skips every org with no `plan` field, and\n * `createOrganization` writes none — so for the whole never-subscribed free\n * tier the marker had never once been written. The general lesson: **a cap\n * that lives only in a scheduled sweep stops existing the moment the sweep\n * does not run.** Every other free dimension refuses at the\n * point of use; this one now does too.\n *\n * ### The latency, stated plainly\n *\n * The beacon closes the window to the sampling slop — at most\n * (200 x instances) page views past the band, against a free band of ~8,700 —\n * so on the common single-site free org the cap engages within a couple of\n * hundred views. It is still not a per-request throttle, and the honest way to\n * describe it is \"a free site cannot run away\", not \"a free site cannot serve\n * byte 5,368,709,121\". Do not close the remaining slop by adding a read to the\n * RENDER path; the place to close it is the CDN, which is Vercel configuration\n * and not a repo change.\n *\n * ### It RELEASES immediately, though\n *\n * Asymmetric on purpose, and this is why {@link bandwidthCapEngaged} re-reads\n * the plan rather than trusting the marker alone. An org that upgrades starts\n * serving again on the next org-doc TTL — about 60 seconds — without waiting\n * for any cron to run or any flag to be cleared. Making somebody who has just\n * paid wait until tomorrow morning for their site to come back is the failure\n * mode that would make this feature worse than the hole it closes.\n *\n * Nothing ever CLEARS the marker either: it names the month it was written\n * for, so a new month simply stops matching. A cap whose lift depends on a\n * write is a cap that stays engaged when the writer fails.\n */\n\nimport type { AglynOrgBilling, OrgBandwidthCap } from '../foundation'\nimport {\n isCustomPricedPlan,\n planMetersInfraOverage,\n resolveEffectivePlan,\n resolveOrgEntitlements,\n} from './plan-entitlements'\n\n/**\n * The month key the marker is stamped with: UTC `YYYY-MM`, the same shape as\n * `utcMonthKey` and the `orgs/{id}/usage/{month}` document id, and the\n * same key `usage-alerts` dedupes its own guards by. One month boundary\n * across the platform — a cap that reset on a different day from the counter\n * it is derived from would engage against last month's traffic.\n */\nexport function bandwidthCapMonthKey(now: Date = new Date()): string {\n return now.toISOString().slice(0, 7)\n}\n\n/**\n * How long a crawler or uptime check is told to wait.\n *\n * NOT \"until the month rolls over\", which is the arithmetically correct\n * answer and can be three weeks. The site can come back at any moment — the\n * owner upgrades and the release path above restores it in about a minute —\n * so a multi-week `Retry-After` would tell Google to stop looking long after\n * the site was serving again. An hour is short enough to be wrong in the\n * recoverable direction.\n */\nexport const BANDWIDTH_CAP_RETRY_AFTER_SECONDS = 3600\n\n/**\n * Is this org's serving currently refused by the free-plan bandwidth cap?\n *\n * THREE conditions, and the second and third are the ones that matter:\n *\n * 1. the marker names the CURRENT month (a stale marker is not a cap);\n * 2. the org's plan does not meter infrastructure overage — i.e. it is the\n * free plan, or a paid plan held as a staff comp (AGL-3034), which has no\n * subscription to bill past the band either. Paid plans BILL bandwidth\n * past the band and are never cut off; that promise is older than this\n * cap and this function is where it is kept. Re-derived from the CURRENT\n * plan on every read, which is what releases an upgraded org without a\n * write;\n * 3. the plan is not custom-priced, and its band is finite. Enterprise also\n * answers false to `planMetersInfraOverage` — its price is negotiated —\n * and since 2026-09-07 its band is a FINITE fallback (twice Agency's), so\n * \"unmetered and finite\" would describe a contracted customer exactly as\n * it describes a free one. Its traffic is paid for by agreement, not by\n * invoice, and this cap is the free plan's rule alone: an enterprise org\n * carrying a marker some future writer left behind is never refused.\n * Belt and braces: today's writer cannot produce that marker, and this\n * makes it impossible rather than merely unreachable.\n *\n * Fail OPEN on anything unrecognised. A missing org, a malformed marker or a\n * plan this build cannot read all serve the site: an unreadable org doc is an\n * outage, and taking a customer's website down over one is not a cap, it is\n * the incident.\n */\nexport function bandwidthCapEngaged(\n org: Partial<AglynOrgBilling> | null | undefined,\n now: Date = new Date(),\n): boolean {\n if (!org) return false\n if (planMetersInfraOverage(org)) return false\n if (isCustomPricedPlan(resolveEffectivePlan(org))) return false\n if (!Number.isFinite(resolveOrgEntitlements(org).bandwidthGb)) return false\n const cap = org.bandwidthCap\n if (!cap || typeof cap !== 'object') return false\n return cap.month === bandwidthCapMonthKey(now)\n}\n\n/**\n * Should the cap be ENGAGED for this org-month? The writer's half of the\n * question, kept beside the reader's so the two cannot drift apart.\n *\n * Takes the measured figure and the band rather than reading anything, so the\n * cron passes in the very numbers it alerts on. `>` and not `>=`: an org\n * exactly at its band has used what it was given and is not over it.\n */\nexport function bandwidthCapShouldEngage(options: {\n org: Partial<AglynOrgBilling> | null | undefined\n usedBandwidthGb: number\n includedBandwidthGb: number\n}): boolean {\n const { org, usedBandwidthGb, includedBandwidthGb } = options\n if (planMetersInfraOverage(org)) return false\n // The reader's third condition, kept in step: a custom-priced plan is paid\n // for by agreement and is never paused, whatever its band resolves to.\n if (isCustomPricedPlan(resolveEffectivePlan(org))) return false\n if (!Number.isFinite(includedBandwidthGb) || !(includedBandwidthGb > 0)) {\n return false\n }\n return usedBandwidthGb > includedBandwidthGb\n}\n\n/**\n * Could this org's traffic EVER engage the cap — is it on a plan that stops\n * at its band rather than billing past it (AGL-3474)?\n *\n * {@link bandwidthCapShouldEngage} with the usage left out, for a writer that\n * has to decide whether measuring is worth its reads at all: the media CDN\n * totals an org's month only when this is true, so a paying org's video costs\n * no read to meter. Answered by the same predicate rather than restated, so\n * the two cannot disagree about which plans the cap is for.\n */\nexport function bandwidthCapApplies(\n org: Partial<AglynOrgBilling> | null | undefined,\n): boolean {\n return bandwidthCapShouldEngage({\n org,\n usedBandwidthGb: Number.POSITIVE_INFINITY,\n includedBandwidthGb: resolveOrgEntitlements(org).bandwidthGb,\n })\n}\n\n/** What a visitor sees on a capped site. */\nexport interface BandwidthCapNotice {\n title: string\n body: string\n}\n\n/**\n * The visitor's sentence.\n *\n * Constrained the same way the form abuse-ceiling copy is (AGL-1666), and for\n * the same reason: the person reading it is a stranger to the site, so it\n * must not disclose the owner's plan, their bill, or anything about their\n * account beyond the one fact that makes the page they asked for absent. It\n * says what happened, that it is not their fault and not permanent, and when\n * it ends — and then stops. \"Upgrade your plan\" belongs in the owner's\n * console and their inbox, which is where the usage alert already puts it,\n * not on a page shown to their readers.\n *\n * Deliberately NOT routed through `lockdownNotice`. A lockdown is the panic\n * button — staff-set, security or billing, \"contact support\" — and its copy\n * would be a lie here in both directions: nobody took this site down and\n * support cannot lift it. Reusing the RENDERING channel (the 503 notice page)\n * while keeping the WORDS separate is the split that keeps both honest.\n */\nexport function bandwidthCapNotice(): BandwidthCapNotice {\n return {\n title: 'Over the monthly traffic limit',\n body:\n 'This site has used all of the traffic included with it this month, ' +\n 'so its pages are paused until the start of next month. Nothing is ' +\n 'wrong with your connection, and nothing here has been removed.',\n }\n}\n\n/**\n * The refusal code on the machine-readable half of the verdict, so a caller\n * can tell a capped site from a locked one. The two answer the same HTTP\n * status from the same notice page on purpose — a 503 with `Retry-After` is\n * the only status that tells a crawler \"come back\", where a 402 or a 403\n * risks a customer's site being de-indexed over one busy month — so the\n * status discriminates nothing and this code is the whole discriminator.\n */\nexport const BANDWIDTH_CAP_CODE = 'bandwidth-cap'\n"],"names":["isCustomPricedPlan","planMetersInfraOverage","resolveEffectivePlan","resolveOrgEntitlements","bandwidthCapMonthKey","now","Date","toISOString","slice","BANDWIDTH_CAP_RETRY_AFTER_SECONDS","bandwidthCapEngaged","org","Number","isFinite","bandwidthGb","cap","bandwidthCap","month","bandwidthCapShouldEngage","options","usedBandwidthGb","includedBandwidthGb","bandwidthCapApplies","POSITIVE_INFINITY","bandwidthCapNotice","title","body","BANDWIDTH_CAP_CODE"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuEC,GAGD,SACEA,kBAAkB,EAClBC,sBAAsB,EACtBC,oBAAoB,EACpBC,sBAAsB,QACjB,yBAAqB;AAE5B;;;;;;CAMC,GACD,OAAO,SAASC,qBAAqBC,MAAY,IAAIC,MAAM;IACzD,OAAOD,IAAIE,WAAW,GAAGC,KAAK,CAAC,GAAG;AACpC;AAEA;;;;;;;;;CASC,GACD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right 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 * The free plan's BANDWIDTH HARD CAP (AGL-1967 / AGL-2070 / AGL-2155).\n *\n * Enforced from before public signups, so the cap is proven under real\n * traffic while the cohort is small and a mistake is cheap. The requirement\n * this module exists to make true: the free/hobby tier hard-caps, so that it\n * always actually stays free.\n *\n * Until this shipped, bandwidth was the ONE billable dimension with no\n * runtime refusal anywhere. Media ingress, forms, contacts, datasets, API and\n * seats all hard-stop on free; `bandwidthGb: 5` appeared only in the plan\n * table, in reporting arithmetic and in UI. A free site that went viral\n * served every page and Aglyn paid the egress with no ceiling.\n *\n * ## Why a MARKER on the org doc, and not a check\n *\n * The obvious implementation — read the page-view counter before rendering —\n * is the one thing this cap must not do. Page views are counted AFTER the\n * fact, by a client beacon into `hosts/{id}/analytics/{day}`; consulting them\n * per render would put a Firestore read on the hot path of every public page\n * on the platform, paid by every PAYING customer too, to answer a question\n * only free orgs can ever fail. That is the exact cost the whole ISR/cache\n * design exists to avoid.\n *\n * So the decision is made where the arithmetic already happens, and its\n * verdict is denormalized onto the org document as {@link OrgBandwidthCap}.\n * The serving path then reads it from `getOrgBilling`, the org doc it ALREADY\n * loads and caches for 60 seconds as \"the suspension gate and every\n * entitlement input for the render\". **The cap costs zero additional reads.**\n *\n * ### TWO writers, and neither is on the render path (AGL-2413)\n *\n * 1. `apps/tenant/app/api/analytics/collect` — the beacon that WRITES the\n * page-view counter, on its existing 1-in-200 sample. It already sums this\n * month with this query and already loads this org doc for the abuse\n * ceiling, so the cap rides both for free.\n * 2. `api/billing/usage-alerts` — the daily sweep, which sums page views\n * ORG-WIDE across up to 100 hosts and is therefore the backstop for any\n * org running more than one site.\n *\n * The beacon is the one that matters, and it exists because the sweep alone\n * was not a cap at all: it skips every org with no `plan` field, and\n * `createOrganization` writes none — so for the whole never-subscribed free\n * tier the marker had never once been written. The general lesson: **a cap\n * that lives only in a scheduled sweep stops existing the moment the sweep\n * does not run.** Every other free dimension refuses at the\n * point of use; this one now does too.\n *\n * ### The latency, stated plainly\n *\n * The beacon closes the window to the sampling slop — at most\n * (200 x instances) page views past the band, against a free band of ~8,700 —\n * so on the common single-site free org the cap engages within a couple of\n * hundred views. It is still not a per-request throttle, and the honest way to\n * describe it is \"a free site cannot run away\", not \"a free site cannot serve\n * byte 5,368,709,121\". Do not close the remaining slop by adding a read to the\n * RENDER path; the place to close it is the CDN, which is Vercel configuration\n * and not a repo change.\n *\n * ### It RELEASES immediately, though\n *\n * Asymmetric on purpose, and this is why {@link bandwidthCapEngaged} re-reads\n * the plan rather than trusting the marker alone. An org that upgrades starts\n * serving again on the next org-doc TTL — about 60 seconds — without waiting\n * for any cron to run or any flag to be cleared. Making somebody who has just\n * paid wait until tomorrow morning for their site to come back is the failure\n * mode that would make this feature worse than the hole it closes.\n *\n * Nothing ever CLEARS the marker either: it names the month it was written\n * for, so a new month simply stops matching. A cap whose lift depends on a\n * write is a cap that stays engaged when the writer fails.\n */\n\nimport type { AglynOrgBilling, OrgBandwidthCap } from '../foundation'\nimport {\n isCustomPricedPlan,\n planMetersInfraOverage,\n resolveEffectivePlan,\n resolveOrgEntitlements,\n} from './plan-entitlements'\n\n/**\n * The month key the marker is stamped with: UTC `YYYY-MM`, the same shape as\n * `utcMonthKey` and the `orgs/{id}/usage/{month}` document id, and the\n * same key `usage-alerts` dedupes its own guards by. One month boundary\n * across the platform — a cap that reset on a different day from the counter\n * it is derived from would engage against last month's traffic.\n */\nexport function bandwidthCapMonthKey(now: Date = new Date()): string {\n return now.toISOString().slice(0, 7)\n}\n\n/**\n * How long a crawler or uptime check is told to wait.\n *\n * NOT \"until the month rolls over\", which is the arithmetically correct\n * answer and can be three weeks. The site can come back at any moment — the\n * owner upgrades and the release path above restores it in about a minute —\n * so a multi-week `Retry-After` would tell Google to stop looking long after\n * the site was serving again. An hour is short enough to be wrong in the\n * recoverable direction.\n */\nexport const BANDWIDTH_CAP_RETRY_AFTER_SECONDS = 3600\n\n/**\n * Is this org's serving currently refused by the free-plan bandwidth cap?\n *\n * THREE conditions, and the second and third are the ones that matter:\n *\n * 1. the marker names the CURRENT month (a stale marker is not a cap);\n * 2. the org's plan does not meter infrastructure overage — i.e. it is the\n * free plan, or a paid plan held as a staff comp (AGL-3034), which has no\n * subscription to bill past the band either. Paid plans BILL bandwidth\n * past the band and are never cut off; that promise is older than this\n * cap and this function is where it is kept. Re-derived from the CURRENT\n * plan on every read, which is what releases an upgraded org without a\n * write;\n * 3. the plan is not custom-priced, and its band is finite. Enterprise also\n * answers false to `planMetersInfraOverage` — its price is negotiated —\n * and since 2026-09-07 its band is a FINITE fallback (twice Agency's), so\n * \"unmetered and finite\" would describe a contracted customer exactly as\n * it describes a free one. Its traffic is paid for by agreement, not by\n * invoice, and this cap is the free plan's rule alone: an enterprise org\n * carrying a marker some future writer left behind is never refused.\n * Belt and braces: today's writer cannot produce that marker, and this\n * makes it impossible rather than merely unreachable.\n *\n * Fail OPEN on anything unrecognised. A missing org, a malformed marker or a\n * plan this build cannot read all serve the site: an unreadable org doc is an\n * outage, and taking a customer's website down over one is not a cap, it is\n * the incident.\n */\nexport function bandwidthCapEngaged(\n org: Partial<AglynOrgBilling> | null | undefined,\n now: Date = new Date(),\n): boolean {\n if (!org) return false\n if (planMetersInfraOverage(org)) return false\n if (isCustomPricedPlan(resolveEffectivePlan(org))) return false\n if (!Number.isFinite(resolveOrgEntitlements(org).bandwidthGb)) return false\n const cap = org.bandwidthCap\n if (!cap || typeof cap !== 'object') return false\n if (cap.month !== bandwidthCapMonthKey(now)) return false\n // The one-time grace (AGL-4232): engaged, but not refusing until it ends.\n // Nothing writes at that moment; every reader re-derives it from the clock.\n return !(typeof cap.graceUntil === 'number' && now.getTime() < cap.graceUntil)\n}\n\n/**\n * How long the ONE-TIME grace keeps a site online past its band (AGL-4232):\n * the first time a site goes over, ever, it stays up this long so its owner\n * can upgrade before visitors are turned away.\n */\nexport const BANDWIDTH_CAP_GRACE_MS = 72 * 60 * 60 * 1000\n\n/**\n * When the grace ends, while one is running for this org this month; `null`\n * when the org is not over its band, is already paused, or never had one.\n * The owner's surfaces read this to say \"upgrade or your site pauses on …\".\n */\nexport function bandwidthCapGraceUntil(\n org: Partial<AglynOrgBilling> | null | undefined,\n now: Date = new Date(),\n): number | null {\n const cap = org?.bandwidthCap\n if (!cap || typeof cap !== 'object' || cap.month !== bandwidthCapMonthKey(now)) return null\n if (typeof cap.graceUntil !== 'number' || now.getTime() >= cap.graceUntil) return null\n // Only where the cap would refuse were there no grace: an upgraded org has\n // nothing to be warned about.\n const { graceUntil: _running, ...withoutGrace } = cap\n return bandwidthCapEngaged({ ...org, bandwidthCap: withoutGrace }, now) ? cap.graceUntil : null\n}\n\n/**\n * The marker a writer stamps when the cap engages (AGL-1967/2155, AGL-4232):\n * the month and its diagnostics, plus the grace window when the org's sites\n * have never had one. ONE shape for every writer, so a reader cannot tell\n * which of them stamped it.\n */\nexport function bandwidthCapMarker(options: {\n month: string\n nowMs: number\n pageViews: number\n includedPageViews: number\n /** When the grace this engagement carries ends; null for none. */\n graceUntil: number | null\n}): OrgBandwidthCap {\n return {\n month: options.month,\n engagedAt: options.nowMs,\n pageViews: Math.round(options.pageViews),\n includedPageViews: Math.round(options.includedPageViews),\n ...(options.graceUntil !== null ? { graceUntil: options.graceUntil } : {}),\n }\n}\n\n/** A grace stamp as stored: epoch ms, or anything else meaning \"never\". */\ntype GraceStamped = { bandwidthGraceUsedAt?: unknown } | null | undefined\n\nconst graceStamp = (doc: GraceStamped): number =>\n typeof doc?.bandwidthGraceUsedAt === 'number' ? doc.bandwidthGraceUsedAt : 0\n\n/**\n * The grace an engagement carries (AGL-4232), from the workspace's own stamp\n * (`orgs/{id}.bandwidthGraceUsedAt`) and its sites' stamps as read: a NEW one\n * when neither the workspace nor any of its sites has ever had it, the one\n * ALREADY RUNNING when a stamp is still inside its window (a grace granted on\n * the 29th that runs into the next month), else none.\n *\n * Both stamps are required absent so deleting the site and making a new one\n * does not re-arm it: the grace is given once per workspace's sites.\n */\nexport function bandwidthGraceForEngagement(\n hosts: ReadonlyArray<GraceStamped>,\n nowMs: number,\n org?: GraceStamped,\n): { graceUntil: number | null; grants: boolean } {\n if (bandwidthGraceAvailable(hosts) && graceStamp(org) === 0) {\n return { graceUntil: nowMs + BANDWIDTH_CAP_GRACE_MS, grants: true }\n }\n const latest = Math.max(graceStamp(org), ...hosts.map(graceStamp))\n const running = latest + BANDWIDTH_CAP_GRACE_MS\n return { graceUntil: latest > 0 && nowMs < running ? running : null, grants: false }\n}\n\n/**\n * Whether an org's sites are owed the one-time grace by their own stamps: it\n * has at least one site, and none of them has ever had it\n * (`AglynHost.bandwidthGraceUsedAt`). The workspace's stamp is asked beside\n * it by {@link bandwidthGraceForEngagement}.\n */\nexport function bandwidthGraceAvailable(hosts: ReadonlyArray<GraceStamped>): boolean {\n return hosts.length > 0 && hosts.every((host) => graceStamp(host) === 0)\n}\n\n/** When a `YYYY-MM` month ends: midnight UTC on the 1st of the next. */\nexport function bandwidthCapMonthEndMs(month: string): number {\n const [year, monthIndex] = month.split('-').map(Number)\n return Date.UTC(year, monthIndex, 1)\n}\n\n/**\n * Whether a grace ends only after the month it was granted in (AGL-4232).\n * Then no pause comes: the new month's count starts at zero, and the site\n * pauses only when it next passes the band, with no grace left.\n */\nexport function bandwidthGraceOutlastsMonth(graceUntil: number, month: string): boolean {\n return graceUntil >= bandwidthCapMonthEndMs(month)\n}\n\n/**\n * The grace deadline as the owner reads it: an unambiguous UTC date and\n * time, e.g. \"Thursday, November 19 at 3:04 PM UTC\".\n */\nexport function formatBandwidthGraceDeadline(ms: number): string {\n const date = new Date(ms)\n const day = date.toLocaleDateString('en-US', {\n weekday: 'long',\n month: 'long',\n day: 'numeric',\n timeZone: 'UTC',\n })\n const time = date.toLocaleTimeString('en-US', {\n hour: 'numeric',\n minute: '2-digit',\n timeZone: 'UTC',\n })\n return `${day} at ${time} UTC`\n}\n\n/**\n * Should the cap be ENGAGED for this org-month? The writer's half of the\n * question, kept beside the reader's so the two cannot drift apart.\n *\n * Takes the measured figure and the band rather than reading anything, so the\n * cron passes in the very numbers it alerts on. `>` and not `>=`: an org\n * exactly at its band has used what it was given and is not over it.\n */\nexport function bandwidthCapShouldEngage(options: {\n org: Partial<AglynOrgBilling> | null | undefined\n usedBandwidthGb: number\n includedBandwidthGb: number\n}): boolean {\n const { org, usedBandwidthGb, includedBandwidthGb } = options\n if (planMetersInfraOverage(org)) return false\n // The reader's third condition, kept in step: a custom-priced plan is paid\n // for by agreement and is never paused, whatever its band resolves to.\n if (isCustomPricedPlan(resolveEffectivePlan(org))) return false\n if (!Number.isFinite(includedBandwidthGb) || !(includedBandwidthGb > 0)) {\n return false\n }\n return usedBandwidthGb > includedBandwidthGb\n}\n\n/**\n * Could this org's traffic EVER engage the cap — is it on a plan that stops\n * at its band rather than billing past it (AGL-3474)?\n *\n * {@link bandwidthCapShouldEngage} with the usage left out, for a writer that\n * has to decide whether measuring is worth its reads at all: the media CDN\n * totals an org's month only when this is true, so a paying org's video costs\n * no read to meter. Answered by the same predicate rather than restated, so\n * the two cannot disagree about which plans the cap is for.\n */\nexport function bandwidthCapApplies(\n org: Partial<AglynOrgBilling> | null | undefined,\n): boolean {\n return bandwidthCapShouldEngage({\n org,\n usedBandwidthGb: Number.POSITIVE_INFINITY,\n includedBandwidthGb: resolveOrgEntitlements(org).bandwidthGb,\n })\n}\n\n/**\n * The one sentence every grace message carries (AGL-4232): the abuse ceiling\n * stays the cost bound during a grace, so a surge far past the band can still\n * pause the site before the deadline. Said, so the deadline is never a\n * promise the ceiling breaks.\n */\nexport const BANDWIDTH_GRACE_SURGE_SENTENCE =\n 'An unusually large surge of traffic can still pause it before then.'\n\n/**\n * What the OWNER is told when a grace starts (AGL-4232), in the console and by\n * email: the deadline in plain words, with the way past it. `{site}` is\n * filled by the notifier from the site it reads. `used` is the writer's own\n * account of what was used (page views, or traffic including media).\n * `carried` is a grace granted earlier that still runs as the site goes over\n * again in a new month: the same deadline, said again, since it is this\n * month's news.\n */\nexport function bandwidthGraceOwnerNotice(options: {\n graceUntil: number\n /** The `YYYY-MM` the cap engaged for, which decides whether a pause comes. */\n month: string\n used: string\n resumesOn: string\n carried?: boolean\n}): BandwidthCapNotice {\n // A grace begun in a month's last 72 hours outlasts it: the count starts\n // again on the 1st, so no pause comes, and saying a date would be false.\n if (bandwidthGraceOutlastsMonth(options.graceUntil, options.month)) {\n return {\n title: '{site} is past its monthly traffic limit and stays online',\n body:\n `{site} has used ${options.used} this month. It stays online: the ` +\n `month ends before its extra time would, and its count starts again ` +\n `on ${options.resumesOn}. Nothing is charged for the extra traffic. ` +\n 'This extra time is given once and has now been used, so the next time ' +\n 'your sites pass their limit they pause straight away. An unusually large ' +\n 'surge of traffic can still pause it before the month ends. Upgrade in ' +\n 'Billing to keep it online whatever its traffic.',\n }\n }\n const deadline = formatBandwidthGraceDeadline(options.graceUntil)\n return {\n title: `Upgrade or {site} pauses on ${deadline}`,\n body:\n `{site} has used ${options.used} this month. ` +\n (options.carried\n ? `It stays online until ${deadline}, when the extra time it was already given ends. `\n : `It stays online until ${deadline}. `) +\n 'Upgrade in Billing before then to keep it online; if you ' +\n `don't, visitors see a \"temporarily unavailable\" notice from then until ` +\n `${options.resumesOn}. ${BANDWIDTH_GRACE_SURGE_SENTENCE} Nothing is charged ` +\n 'for the extra traffic. This extra time is given once, so the next time your ' +\n 'sites pass their limit they pause straight away.',\n }\n}\n\n/**\n * What the OWNER is told when a site is paused with no grace, or when its\n * grace has ended (AGL-4232): in the console and by email, from whichever\n * writer saw it. `{site}` is filled by the notifier.\n */\nexport function bandwidthPausedOwnerNotice(options: {\n used: string\n resumesOn: string\n}): BandwidthCapNotice {\n return {\n title: '{site} paused — monthly traffic limit reached',\n body:\n `{site} has used ${options.used} this month, so visitors see a ` +\n `\"temporarily unavailable\" notice instead of its pages until ` +\n `${options.resumesOn}. Nothing is charged for the extra traffic. The site ` +\n 'comes back on its own then, or as soon as you upgrade in Billing.',\n }\n}\n\n/** What a visitor sees on a capped site. */\nexport interface BandwidthCapNotice {\n title: string\n body: string\n}\n\n/**\n * The visitor's sentence.\n *\n * Constrained the same way the form abuse-ceiling copy is (AGL-1666), and for\n * the same reason: the person reading it is a stranger to the site, so it\n * must not disclose the owner's plan, their bill, or anything about their\n * account beyond the one fact that makes the page they asked for absent. It\n * says what happened, that it is not their fault and not permanent, and when\n * it ends — and then stops. \"Upgrade your plan\" belongs in the owner's\n * console and their inbox, which is where the usage alert already puts it,\n * not on a page shown to their readers.\n *\n * Deliberately NOT routed through `lockdownNotice`. A lockdown is the panic\n * button — staff-set, security or billing, \"contact support\" — and its copy\n * would be a lie here in both directions: nobody took this site down and\n * support cannot lift it. Reusing the RENDERING channel (the 503 notice page)\n * while keeping the WORDS separate is the split that keeps both honest.\n */\nexport function bandwidthCapNotice(): BandwidthCapNotice {\n // NEUTRAL (AGL-4232): nothing about limits, plans, traffic or pricing —\n // those are the owner's to read in the console, not a visitor's.\n return {\n title: 'Temporarily unavailable',\n body: 'This site is temporarily unavailable.',\n }\n}\n\n/**\n * The refusal code on the machine-readable half of the verdict, so a caller\n * can tell a capped site from a locked one. The two answer the same HTTP\n * status from the same notice page on purpose — a 503 with `Retry-After` is\n * the only status that tells a crawler \"come back\", where a 402 or a 403\n * risks a customer's site being de-indexed over one busy month — so the\n * status discriminates nothing and this code is the whole discriminator.\n */\nexport const BANDWIDTH_CAP_CODE = 'bandwidth-cap'\n"],"names":["isCustomPricedPlan","planMetersInfraOverage","resolveEffectivePlan","resolveOrgEntitlements","bandwidthCapMonthKey","now","Date","toISOString","slice","BANDWIDTH_CAP_RETRY_AFTER_SECONDS","bandwidthCapEngaged","org","Number","isFinite","bandwidthGb","cap","bandwidthCap","month","graceUntil","getTime","BANDWIDTH_CAP_GRACE_MS","bandwidthCapGraceUntil","_running","withoutGrace","bandwidthCapMarker","options","engagedAt","nowMs","pageViews","Math","round","includedPageViews","graceStamp","doc","bandwidthGraceUsedAt","bandwidthGraceForEngagement","hosts","bandwidthGraceAvailable","grants","latest","max","map","running","length","every","host","bandwidthCapMonthEndMs","year","monthIndex","split","UTC","bandwidthGraceOutlastsMonth","formatBandwidthGraceDeadline","ms","date","day","toLocaleDateString","weekday","timeZone","time","toLocaleTimeString","hour","minute","bandwidthCapShouldEngage","usedBandwidthGb","includedBandwidthGb","bandwidthCapApplies","POSITIVE_INFINITY","BANDWIDTH_GRACE_SURGE_SENTENCE","bandwidthGraceOwnerNotice","title","body","used","resumesOn","deadline","carried","bandwidthPausedOwnerNotice","bandwidthCapNotice","BANDWIDTH_CAP_CODE"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuEC;;AAGD,SACEA,kBAAkB,EAClBC,sBAAsB,EACtBC,oBAAoB,EACpBC,sBAAsB,QACjB,yBAAqB;AAE5B;;;;;;CAMC,GACD,OAAO,SAASC,qBAAqBC,MAAY,IAAIC,MAAM;IACzD,OAAOD,IAAIE,WAAW,GAAGC,KAAK,CAAC,GAAG;AACpC;AAEA;;;;;;;;;CASC,GACD,OAAO,MAAMC,oCAAoC,KAAI;AAErD;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BC,GACD,OAAO,SAASC,oBACdC,GAAgD,EAChDN,MAAY,IAAIC,MAAM;IAEtB,IAAI,CAACK,KAAK,OAAO;IACjB,IAAIV,uBAAuBU,MAAM,OAAO;IACxC,IAAIX,mBAAmBE,qBAAqBS,OAAO,OAAO;IAC1D,IAAI,CAACC,OAAOC,QAAQ,CAACV,uBA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