@aglyn/plugins-marketplace 1.10.0 → 1.12.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 (81) hide show
  1. package/package.json +14 -14
  2. package/src/lib/components/listing-content.component.js +78 -36
  3. package/src/lib/components/listing-content.component.js.map +1 -1
  4. package/src/lib/components/listing-detail-page.component.js +22 -9
  5. package/src/lib/components/listing-detail-page.component.js.map +1 -1
  6. package/src/lib/components/listing-review-status.component.d.ts +8 -0
  7. package/src/lib/components/listing-review-status.component.js +23 -3
  8. package/src/lib/components/listing-review-status.component.js.map +1 -1
  9. package/src/lib/components/listing-verification-request.component.d.ts +8 -0
  10. package/src/lib/components/listing-verification-request.component.js +12 -5
  11. package/src/lib/components/listing-verification-request.component.js.map +1 -1
  12. package/src/lib/components/marketplace-hub.component.js +2 -1
  13. package/src/lib/components/marketplace-hub.component.js.map +1 -1
  14. package/src/lib/components/org-seller-panel.component.d.ts +10 -0
  15. package/src/lib/components/org-seller-panel.component.js +26 -4
  16. package/src/lib/components/org-seller-panel.component.js.map +1 -1
  17. package/src/lib/components/starter-picker-shelf.component.js +13 -8
  18. package/src/lib/components/starter-picker-shelf.component.js.map +1 -1
  19. package/src/lib/declarations.d.ts +2 -1
  20. package/src/lib/declarations.js +5 -1
  21. package/src/lib/declarations.js.map +1 -1
  22. package/src/lib/model/marketplace-publisher-permissions.d.ts +26 -0
  23. package/src/lib/model/marketplace-publisher-permissions.js +64 -0
  24. package/src/lib/model/marketplace-publisher-permissions.js.map +1 -0
  25. package/src/lib/model/marketplace.js +2 -1
  26. package/src/lib/model/marketplace.js.map +1 -1
  27. package/src/lib/model/own-listing.d.ts +52 -0
  28. package/src/lib/model/own-listing.js +72 -0
  29. package/src/lib/model/own-listing.js.map +1 -0
  30. package/src/lib/model/starter-query.js +2 -0
  31. package/src/lib/model/starter-query.js.map +1 -1
  32. package/src/lib/server/connect.js +11 -5
  33. package/src/lib/server/connect.js.map +1 -1
  34. package/src/lib/server/install-dataset-schema.js +10 -2
  35. package/src/lib/server/install-dataset-schema.js.map +1 -1
  36. package/src/lib/server/install-email-starter.js +8 -2
  37. package/src/lib/server/install-email-starter.js.map +1 -1
  38. package/src/lib/server/install-email-template.js +8 -2
  39. package/src/lib/server/install-email-template.js.map +1 -1
  40. package/src/lib/server/install-layout.js +8 -2
  41. package/src/lib/server/install-layout.js.map +1 -1
  42. package/src/lib/server/install-plugin.js +24 -20
  43. package/src/lib/server/install-plugin.js.map +1 -1
  44. package/src/lib/server/install-template.js +8 -5
  45. package/src/lib/server/install-template.js.map +1 -1
  46. package/src/lib/server/install-theme.js +8 -2
  47. package/src/lib/server/install-theme.js.map +1 -1
  48. package/src/lib/server/install.js +10 -5
  49. package/src/lib/server/install.js.map +1 -1
  50. package/src/lib/server/listing-versions.js +24 -9
  51. package/src/lib/server/listing-versions.js.map +1 -1
  52. package/src/lib/server/own-listing.d.ts +46 -0
  53. package/src/lib/server/own-listing.js +52 -0
  54. package/src/lib/server/own-listing.js.map +1 -0
  55. package/src/lib/server/preview-image.d.ts +1 -1
  56. package/src/lib/server/preview-image.js +9 -8
  57. package/src/lib/server/preview-image.js.map +1 -1
  58. package/src/lib/server/publish-plugin.js +17 -19
  59. package/src/lib/server/publish-plugin.js.map +1 -1
  60. package/src/lib/server/publisher-permissions.d.ts +63 -0
  61. package/src/lib/server/publisher-permissions.js +51 -0
  62. package/src/lib/server/publisher-permissions.js.map +1 -0
  63. package/src/lib/server/publisher-profile-save.d.ts +4 -2
  64. package/src/lib/server/publisher-profile-save.js +12 -5
  65. package/src/lib/server/publisher-profile-save.js.map +1 -1
  66. package/src/lib/server/publisher-profile.d.ts +18 -6
  67. package/src/lib/server/publisher-profile.js +19 -8
  68. package/src/lib/server/publisher-profile.js.map +1 -1
  69. package/src/lib/server/reviews.js +6 -5
  70. package/src/lib/server/reviews.js.map +1 -1
  71. package/src/lib/server/sale-risk.d.ts +0 -6
  72. package/src/lib/server/sale-risk.js +0 -9
  73. package/src/lib/server/sale-risk.js.map +1 -1
  74. package/src/lib/server/sale.js +10 -9
  75. package/src/lib/server/sale.js.map +1 -1
  76. package/src/lib/server/site-starter-source.js +43 -17
  77. package/src/lib/server/site-starter-source.js.map +1 -1
  78. package/src/lib/server/update-artifact.js +11 -4
  79. package/src/lib/server/update-artifact.js.map +1 -1
  80. package/src/lib/server/verification-request.js +23 -7
  81. package/src/lib/server/verification-request.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/marketplace.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 * Marketplace marketplace v1 (AGL-44): shared types + the server-side\n * sanitization pass that gates publishing a host component definition as a\n * public listing. Pure data module — safe to import from API routes.\n */\n\n// The leaf module, not a barrel: this model is reached from both the browser\n// and API routes, and `@aglyn/aglyn` carries `createContext` (illegal in a\n// Server Component) while `@aglyn/aglyn/server` carries `node:fs` (illegal in\n// the browser). Neither is safe from here; the deep path has no dependencies.\nimport {\n isFirstPartyMediaSrc,\n MEDIA_REF_PREFIX,\n} from '@aglyn/aglyn/app-utils/media-ref'\nimport { marketplaceMinPriceUsd } from './listing-price-floor'\nimport type { InstallableArtifactType as MarketplaceArtifactType } from '@aglyn/aglyn/app-utils/artifact-provenance'\nimport type { ListingVerificationRequest } from './listing-verification'\nimport {\n offeredPluginVersion,\n type PluginRevocation,\n} from '@aglyn/aglyn/app-utils/plugin-manifest'\n// Visibility lives in core (AGL-876), for the same reason the artifact-type\n// union and the verification policy do: the console's listing route asks the\n// question and `scope:app` may not depend on `aglyn:addons`. Imported AND\n// re-exported — `installTargetsFor` and `listingArtifactLabel` below call\n// `listingArtifactType` locally, and a bare `export … from` binds nothing.\n// The write-deny classification (AGL-1361) rides along for the same reason:\n// it is a statement about the fields this policy reads, and the guard that\n// enforces it lives in core beside the rules parser.\nimport {\n isListingBrowsable,\n isListingDeleted,\n isPrivateListing,\n LISTING_CLIENT_WRITABLE_FIELDS,\n LISTING_UNPERSISTED_FIELDS,\n listingArtifactType,\n} from './listing-visibility'\n\nexport {\n isListingBrowsable,\n isListingDeleted,\n isPrivateListing,\n LISTING_CLIENT_WRITABLE_FIELDS,\n LISTING_UNPERSISTED_FIELDS,\n listingArtifactType,\n}\n\n/**\n * `profiles/{uid}` — a person's public identity.\n *\n * NOT a publisher identity as of AGL-652: publishing is org-only, and the\n * marketplace presence lives on `publisherProfiles/{orgId}` below. This doc\n * survives because it is also the support forum's author identity, which\n * renders poster names from `displayName`.\n */\nexport interface MarketplaceProfile {\n handle: string\n displayName: string\n bio?: string\n avatarUrl?: string\n}\n\n/**\n * `publisherProfiles/{orgId}` — an organization's marketplace presence\n * (AGL-652). Publishing is org-only: an org publishes, an org gets paid, and\n * the org is who buyers see. Keyed by org id so authorization is a plain org\n * role check with no ownership indirection.\n *\n * `stripeAccountId` / `stripeChargesEnabled` / `stripeAccountLivemode` are\n * written only by the Connect route via the Admin SDK and are frozen from\n * client writes by the rules — they decide who receives money, and\n * `stripeAccountLivemode` is a gate INPUT (AGL-2471), so a client that could\n * write it could re-open the hole by asserting its own readiness.\n */\nexport interface MarketplacePublisherProfile {\n /** Unique marketplace handle; reserved in `publisherHandles/{handle}`. */\n handle: string\n displayName: string\n bio?: string\n avatarUrl?: string\n website?: string\n /** Server-only. */\n stripeAccountId?: string\n /** Server-only; true once Connect onboarding can accept charges. */\n stripeChargesEnabled?: boolean\n /**\n * Server-only; which Stripe world the account belongs to (AGL-2471).\n * `true` = live, `false` = test, ABSENT = never established — and on a live\n * deployment absent refuses the sale, because a payout destination whose\n * mode nobody verified is exactly what shipped three unusable storefronts.\n */\n stripeAccountLivemode?: boolean\n}\n\n/**\n * `publisherHandles/{handle}` — uniqueness reservation for publisher handles,\n * mirroring `orgSlugs` (AGL-652). Without it two publishers could claim the\n * same handle, which the marketplace URL space cannot represent. `movedTo`\n * tombstones a renamed handle so old links can still resolve.\n */\nexport interface PublisherHandleReservation {\n orgId: string\n movedTo?: string\n}\n\n/**\n * Publisher handles share the org-slug shape: 3–30 chars, lowercase\n * alphanumeric plus internal hyphens. Single source of truth — the two\n * marketplace pages historically applied two subtly different regexes to the\n * same field (AGL-653).\n */\nexport const PUBLISHER_HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/\n\nexport function isValidPublisherHandle(handle: string): boolean {\n return PUBLISHER_HANDLE_PATTERN.test(handle)\n}\n\n/**\n * `marketplaceListings/{listingId}` — public component listing. Version\n * snapshots live in the `versions/{n}` subcollection; installs copy a pinned\n * version into `hosts/{hostId}/components` so the existing drawer/graft\n * pipeline applies unchanged.\n */\nexport interface MarketplaceListing {\n profileId: string\n displayName: string\n description?: string\n category?: string\n /**\n * What this listing publishes (AGL-654). One discriminator for every\n * artifact type — the previous scheme split across two orthogonal fields\n * (`type: 'component'|'plugin'` plus a separate `kind: 'template'`), so a\n * template was \"kind template with no type\" and each installer branched on\n * whichever field it happened to care about. That does not survive adding\n * layouts, dataset schemas and email templates.\n *\n * Read it through `listingArtifactType()`, never directly — listings\n * written before this field still carry only the legacy pair.\n */\n artifactType?: MarketplaceArtifactType\n /** @deprecated Legacy discriminator; use `artifactType` (AGL-654). */\n type?: 'component' | 'plugin'\n /** @deprecated Legacy discriminator; use `artifactType` (AGL-654). */\n kind?: 'template'\n latestVersion: number | string\n /** Plugin manifest id, for `type: 'plugin'` listings (AGL-45). */\n pluginId?: string\n /** One-time price in whole USD; 0/absent = free (AGL-46). */\n priceUsd?: number\n deletedAt?: unknown\n // Listing content (AGL-430, Strapi Market parity) — publisher-authored,\n // rendered on the marketplace detail page. All optional; validated by\n // validateListingContent on the API path and SANITIZED at render time\n // (the doc is publisher-writable, so renderers never trust it).\n logoUrl?: string\n screenshots?: string[]\n /** Markdown documentation shown on the listing page (no raw HTML). */\n readme?: string\n homepageUrl?: string\n repositoryUrl?: string\n /** SPDX-ish license label, e.g. \"MIT\". */\n license?: string\n categories?: string[]\n /**\n * Marketplace review lifecycle (AGL-432). Absent = legacy listing,\n * treated as 'listed'. New plugin listings start 'submitted'; staff move\n * them through the queue. Only 'listed'/'verified' (or legacy) plugin\n * listings appear in browse for non-owners.\n */\n reviewStatus?: ListingReviewStatus\n /**\n * The publisher's standing ask for the Verified badge (AGL-1217).\n *\n * Its own field, never a `reviewStatus` member — see\n * {@link ListingVerificationRequest}. Server-owned: the publisher route only\n * moves it to `pending`/`withdrawn`, and only staff can decide it. Asking\n * never grants anything; the checklist gate on `verify` stays the one route\n * to the badge.\n */\n verificationRequest?: ListingVerificationRequest\n // Server-managed. These were written by the publish/install/review paths\n // but never declared, so callers reached for `as any` (AGL-654).\n /** Publishing org id — the publisher profile's doc id (AGL-652). */\n publisherOrgId?: string\n /** Source component for a `component` listing. */\n sourceComponentId?: string\n /** Source site for a `template` listing. */\n sourceHostId?: string\n /**\n * Source site for a `siteStarter` listing (AGL-4049): the one-listing-per-\n * source key `publish-starter` looks up. Its own field, never `sourceHostId`:\n * the template, layout and theme doors write that one and key on it with a\n * `limit(1)`, so a shared key would cross a site's starter with its template.\n */\n sourceStarterHostId?: string\n /**\n * The platform published it (AGL-4049). Server-owned and ordering only: the\n * starter picker lists these first. No door, price or checkout branches on\n * it; the seed and staff write it, a publish never does.\n */\n official?: boolean\n /**\n * A site starter's facets (AGL-4049), stamped from its payload by\n * `siteStarterFacetFields` so a starter search can match them. Server-owned:\n * they describe the stored version, so a client rewrite would list a\n * starter under a kind, theme or page count it does not create.\n */\n starterKind?: string | null\n starterBase?: string | null\n starterFonts?: string | null\n starterPages?: number\n starterMode?: 'base' | 'ai'\n /** Incremented by the install API; frozen from client writes. */\n installCount?: number\n /**\n * How many installs are LIVE right now — `installCount`'s sibling, and\n * undeclared here until AGL-1420 went looking for it.\n *\n * That omission was the whole bug. AGL-1361's coverage guard builds the\n * listing's field universe from this interface, the rules deny-list and the\n * resolvers, so a server-owned field in none of the three is not classified\n * as exposed — it is INVISIBLE to the guard, which is a worse failure than\n * being classified wrongly. `installCount` was denied and this was not, so\n * the sibling counter a publisher-org owner/admin could write was the one\n * the browse grid and the listing header print to buyers.\n *\n * Written by the install/uninstall routes and by AGL-1419's derivation.\n */\n activeInstalls?: number\n /**\n * AGL-1419's derived-count cache: the pin count as last verified, the wall\n * clock it was verified at, and the per-version split.\n *\n * Server-owned for a stronger reason than the counters themselves. They are\n * not merely a number that could be wrong — `verifiedLivePins` treats the\n * triple as FRESH when `pinnedActiveInstalls === activeInstalls` and the\n * timestamp is inside the TTL, and then returns `pinnedVersionInstalls`\n * without querying anything. A client that could write all four could pin\n * the cache open on numbers it chose and suppress the re-derivation that\n * exists to bring a count back down.\n */\n pinnedActiveInstalls?: number\n pinsVerifiedAtMs?: number\n pinnedVersionInstalls?: Record<string, number>\n previewImageUrl?: string\n screenCount?: number\n versionHistory?: Array<{ version: number | string; publishedAt?: unknown }>\n createdAt?: unknown\n updatedAt?: unknown\n /** Staff review audit (AGL-432); server-owned (AGL-651). */\n reviewedBy?: string\n reviewedAt?: unknown\n rejectionReason?: string\n /**\n * What the marketplace lists query by (AGL-3321), derived by the server\n * from the fields above after every write (`listingQueryFields`,\n * `refreshListingQueryFields`) and denied to clients.\n */\n nameLower?: string\n nameTokens?: string[]\n nameReversed?: string\n browseAudience?: string[]\n browseTokens?: string[]\n takenDown?: boolean\n /**\n * The publishing workspace is locked (AGL-3365): the listing is out of\n * browse, search and its page until the lift clears it. Written only by\n * the lockdown's marketplace participant, which clears exactly the\n * listings it stamped; server-owned.\n */\n workspaceLockedAt?: unknown\n}\n\n/**\n * Everything an org can publish to the marketplace (AGL-654): every kind of\n * content the platform can install.\n *\n * The union is core's `InstallableArtifactType` — installed content is read by\n * surfaces that are not the marketplace, through the provenance stamp — and is\n * re-exported here under the name publishing code has always used.\n */\nexport type { MarketplaceArtifactType }\n\nexport {\n ARTIFACT_TYPE_LABELS,\n INSTALL_TARGETS,\n type InstallPin,\n type InstallTarget,\n LISTING_CATEGORIES,\n type OrgInstallSite,\n type OrgInstallSummary,\n type PluginInstallState,\n resolveOrgInstallSummary,\n resolvePluginInstallState,\n resolveUninstallTargets,\n type UninstallTarget,\n} from './marketplace-catalog'\nimport { ARTIFACT_TYPE_LABELS, INSTALL_TARGETS, type InstallPin, type InstallTarget, LISTING_CATEGORIES } from './marketplace-catalog'\n\n/** The friendly artifact-type label for a listing (AGL-864). */\nexport function listingArtifactLabel(listing: {\n artifactType?: string\n type?: string\n kind?: string\n}): string {\n return ARTIFACT_TYPE_LABELS[listingArtifactType(listing)] ?? 'Component'\n}\n\n/** Targets a listing can be installed to, defaulting to host-only. */\nexport function installTargetsFor(listing: {\n artifactType?: string\n type?: string\n kind?: string\n}): readonly InstallTarget[] {\n return INSTALL_TARGETS[listingArtifactType(listing)] ?? ['host']\n}\n\n\n/** How the admin chose to target an install from the org marketplace. */\nexport type InstallTargeting = 'all-sites' | 'selected-sites'\n\n/** One concrete install operation: an org pin, or a pin on a named host. */\nexport interface InstallPlanStep {\n scope: InstallTarget\n /** Present iff `scope === 'host'`. */\n hostId?: string\n}\n\n/**\n * Turns a targeting choice into the concrete install operations for a listing\n * (AGL-773), honoring what each artifact type physically supports (see\n * {@link INSTALL_TARGETS}).\n *\n * The rules aren't uniform, and the picker must not promise what an artifact\n * can't do:\n * - **Org-pinnable** (plugin, datasetSchema) + \"all sites\" → a SINGLE org pin,\n * which also covers sites created later.\n * - **Host-scoped** (component, template, layout, emailTemplate) has no org\n * pin, so \"all sites\" fans out to every CURRENT host — new sites are NOT\n * covered automatically. The UI has to say so.\n * - \"Selected sites\" is always host pins, even for an org-pinnable artifact:\n * the admin named specific sites, so honor that literally — UNLESS the\n * artifact can't host-pin at all (datasetSchema), where the per-site choice\n * is meaningless and collapses to the org pin.\n */\nexport function resolveInstallPlan(\n listing: { artifactType?: string; type?: string; kind?: string },\n targeting: InstallTargeting,\n hosts: {\n selectedHostIds: readonly string[]\n allHostIds: readonly string[]\n },\n): InstallPlanStep[] {\n const targets = installTargetsFor(listing)\n const canOrgPin = targets.includes('org')\n const canHostPin = targets.includes('host')\n if (targeting === 'all-sites') {\n if (canOrgPin) return [{ scope: 'org' }]\n return hosts.allHostIds.map((hostId) => ({ scope: 'host', hostId }))\n }\n // selected-sites\n if (!canHostPin) return [{ scope: 'org' }]\n return hosts.selectedHostIds.map((hostId) => ({ scope: 'host', hostId }))\n}\n\nexport type ListingReviewStatus =\n | 'submitted'\n | 'in_review'\n | 'listed'\n | 'verified'\n | 'rejected'\n\n/**\n * Verification requests lived in core from AGL-1217 because the console's\n * STAFF REVIEW ROUTE needed the policy and `scope:app` may not depend on\n * `aglyn:addons`. That route is the plugin's own surface since `38c4b533c`,\n * so the reason expired with it and the module came home (AGL-3080).\n *\n * Still re-exported from here, which is the part that did not change:\n * publishing code keeps one import site whether the policy is a lib away or\n * a file away.\n */\nexport {\n VERIFICATION_BLOCK_MESSAGES,\n VERIFICATION_DECLINE_COOLDOWN_DAYS,\n timestampMs,\n verificationRequestBlock,\n} from './listing-verification'\nexport type {\n ListingVerificationRequest,\n TimestampLike,\n VerifiableListing,\n VerificationRequestBlock,\n VerificationRequestState,\n} from './listing-verification'\n\n\n/**\n * Per-VERSION review state (AGL-966).\n *\n * Approval is a statement about specific bytes, so it lives on the version\n * doc beside the verifier verdict and the review checklist — both already\n * keyed to sha256. It used to live on the listing, which meant a publisher\n * could get v1.0.0 verified and then ship v1.0.1 containing anything: the\n * listing kept its status, the queue never surfaced the update, and\n * installs resolved `latestVersion`.\n */\nexport type PluginVersionReviewState = 'pending' | 'approved' | 'rejected'\n\n/**\n * The LISTING's cached summary of the version it currently offers.\n *\n * A different field from the one above and a different set of values, which is\n * the whole reason it is written down here. `reviewState` lives on the version\n * document and is a verdict about specific bytes;\n * `latestVersionReviewState` lives on the LISTING and exists so browse cards\n * and the listing page can answer \"have the bytes on offer been read?\" without\n * a per-listing subcollection read.\n *\n * `'revoked'` is the value that only ever appears HERE. A kill is not a review\n * verdict: the version keeps the `'approved'` it earned — the staff surface\n * shows \"Disabled\" beside that verdict rather than instead of it, because\n * collapsing the two would erase what the publisher earned — and it is only\n * this listing-level summary that flips, so the \"Reviewed\" chip drops and the\n * caution alert raises while the audit trail stays intact.\n *\n * The practical consequence, and the reason this is a type rather than a\n * comment: the staff review QUEUE keys on the version's `reviewState`, never\n * on this field. Were it to key on this one, every revoked version would\n * reappear in the queue indistinguishable from one awaiting its first review,\n * and a reviewer acting in good faith on a queue they trusted could approve a\n * version somebody had deliberately killed. The two fields are not\n * interchangeable and this names why.\n */\nexport type ListingLatestVersionReviewState =\n | PluginVersionReviewState\n | 'revoked'\n\n\nexport interface ReviewableVersion {\n version?: string\n reviewState?: string\n publishedAt?: { toMillis?: () => number } | null\n}\n\n/** Only approved bytes may be installed. Absent state is NOT approval. */\nexport function isVersionApproved(\n version: { reviewState?: string } | null | undefined,\n): boolean {\n return version?.reviewState === 'approved'\n}\n\n/**\n * Whether an install would hand the viewer UNREVIEWED bytes (AGL-1083).\n *\n * `install-plugin` deliberately lets a publisher install their own\n * unapproved version — you cannot test a version you cannot install, and\n * the AGL-969 checklist asks them to confirm they tested these exact bytes\n * on a site they control. The route reaches that case through\n * `newestApprovedVersion(...) ?? fallback`, where the fallback is\n * `latestVersion` and applies ONLY when the caller owns the listing and no\n * approved version exists at all.\n *\n * Lives here rather than in the listing component because the UI has to\n * describe exactly what the route will do. Two independent readings of\n * \"would this be unreviewed?\" is how the affordance ends up warning about\n * the wrong installs, or staying silent on the right ones.\n *\n * The route's `newest` is `newestInstallableVersion` since AGL-2368 — a\n * revoked version is no longer a candidate, so it no longer suppresses the\n * fallback either. `revocation` is optional because most callers have none;\n * without it this asks the pre-AGL-2368 question, which is the same answer\n * whenever the mirror is current.\n */\nexport function installsUnreviewedFallback(\n listing:\n | {\n profileId?: string\n latestVersion?: string | number\n latestApprovedVersion?: string | number\n }\n | null\n | undefined,\n viewerOrgId: string | null | undefined,\n revocation?: PluginRevocation | null,\n): boolean {\n if (!listing?.profileId || !viewerOrgId) return false\n // Only the publishing org gets the fallback; everyone else is refused.\n if (listing.profileId !== viewerOrgId) return false\n // An INSTALLABLE version exists → the route serves THAT, however much newer\n // the pending one is. Not an unreviewed install. Reading approval alone got\n // this backwards for a revoked listing: the route would fall back to\n // `latestVersion` for the owner and hand over unreviewed bytes, while the\n // page said nothing, because a stopped version still counted as approved.\n if (offeredPluginVersion(listing, revocation)) return false\n return Boolean(String(listing.latestVersion ?? ''))\n}\n\n/**\n * The version a fresh install should pin: newest APPROVED, never\n * `latestVersion`. A pending update is simply not offered, so publishing\n * cannot ship code past review, and the previously approved version keeps\n * installing while the new one waits.\n */\nexport function newestApprovedVersion<T extends ReviewableVersion>(\n versions: readonly T[],\n): T | null {\n const approved = versions.filter((entry) => isVersionApproved(entry))\n if (!approved.length) return null\n return approved.reduce((best, entry) =>\n (entry.publishedAt?.toMillis?.() ?? 0) >\n (best.publishedAt?.toMillis?.() ?? 0)\n ? entry\n : best,\n )\n}\n\n/**\n * What a listing is still missing before it can face the marketplace\n * (AGL-968/994).\n *\n * A private plugin is allowed to be undocumented — its only audience already\n * knows what it is and why it exists. A public one is not: description,\n * README and license are what a stranger deciding whether to run your code\n * has to go on, and they are exactly the fields the review checklist asks\n * about. So going public is gated on the METADATA, never on a re-review —\n * approval is a statement about bytes, and the bytes did not change.\n *\n * Returns the human field names, so the caller can say what to fix rather\n * than just refusing.\n */\nexport function missingPublicListingContent(listing: {\n description?: string\n readme?: string\n license?: string\n}): string[] {\n const missing: string[] = []\n if (!listing.description?.trim()) missing.push('a description')\n if (!listing.readme?.trim()) missing.push('a README')\n if (!listing.license?.trim()) missing.push('a license')\n return missing\n}\n\n\nexport const LISTING_README_MAX_CHARS = 20_000\nexport const LISTING_MAX_SCREENSHOTS = 6\n\nconst HTTPS_URL = /^https:\\/\\/[^\\s]+$/\n\n/**\n * The message every listing IMAGE field returns when it is refused. Names the\n * remedy, because \"must be an https URL\" was true of the value the publisher\n * just typed and told them nothing.\n */\nexport const LISTING_IMAGE_ERROR =\n 'must be an image from your media library — paste a link and the people ' +\n 'browsing your listing would be loading it from a server you control'\n\n/** Length cap shared by every listing URL field. */\nconst LISTING_URL_MAX_CHARS = 500\n\n/**\n * Whether a listing image field is one we will store (AGL-1701).\n *\n * Listing artwork is the one publisher-supplied value that OTHER orgs' users\n * load. It is also, established while fixing this, gated by nothing: review\n * is a statement about a version's bytes (AGL-966), the staff review route\n * never projects `logoUrl`/`screenshots` so a reviewer cannot see them even\n * if the checklist asked, and `update-listing` writes them at any time\n * without touching `reviewStatus` — so a listing can pass review with benign\n * artwork and swap it afterwards while still reading `verified`.\n *\n * Constraining the INPUT rather than sanitizing the output is the whole\n * point: the render sites are three components and an `og:image`, and the\n * next one added would not know to sanitize.\n */\nfunction isListingImageValue(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length <= LISTING_URL_MAX_CHARS &&\n isFirstPartyMediaSrc(value)\n )\n}\n\n/**\n * Whether a value may be a publisher's LOGO (AGL-3260).\n *\n * The listing-image rule, minus the private `media:` reference. A listing's\n * logo may be one because a caller that signs its own links can resolve it;\n * nothing that renders a publisher avatar signs anything, so a reference\n * there would store a value every render site must turn back into the\n * fallback initial — a logo that looks saved and is never seen.\n *\n * `startsWith` rather than `isMediaRef`, for the reason that predicate's own\n * neighbour gives: negating a `value is string` guard on a value already\n * known to be a string leaves the else branch `never`.\n */\nfunction isPublisherAvatarValue(value: unknown): value is string {\n return isListingImageValue(value) && !value.startsWith(MEDIA_REF_PREFIX)\n}\n\n/**\n * Validates publisher-editable listing content (AGL-430). Returns the\n * normalized subset to persist, or an error. Shared by publish and the\n * update-listing action so both paths accept exactly the same shapes.\n *\n * IMAGE fields and LINK fields are validated differently (AGL-1701).\n * `homepageUrl` and `repositoryUrl` stay any-https: they are anchors a reader\n * chooses to follow, and a publisher's homepage living on the publisher's\n * domain is the entire point of the field. `logoUrl` and `screenshots` are\n * `<img src>`, which fetches with no such choice, so those are held to\n * first-party media.\n */\nexport function validateListingContent(input: Record<string, unknown>): {\n ok: boolean\n error?: string\n content?: Partial<MarketplaceListing>\n} {\n const content: Partial<MarketplaceListing> = {}\n for (const key of ['homepageUrl', 'repositoryUrl'] as const) {\n const value = input[key]\n if (value === undefined || value === '') continue\n if (\n typeof value !== 'string' ||\n !HTTPS_URL.test(value) ||\n value.length > LISTING_URL_MAX_CHARS\n ) {\n return { ok: false, error: `${key} must be an https URL` }\n }\n content[key] = value\n }\n const logoUrl = input['logoUrl']\n if (logoUrl !== undefined && logoUrl !== '') {\n if (!isListingImageValue(logoUrl)) {\n return { ok: false, error: `logoUrl ${LISTING_IMAGE_ERROR}` }\n }\n content.logoUrl = logoUrl\n }\n const screenshots = input['screenshots']\n if (screenshots !== undefined) {\n if (\n !Array.isArray(screenshots) ||\n screenshots.length > LISTING_MAX_SCREENSHOTS ||\n screenshots.some((url) => !isListingImageValue(url))\n ) {\n return {\n ok: false,\n error:\n `screenshots must be up to ${LISTING_MAX_SCREENSHOTS} images, and ` +\n `each ${LISTING_IMAGE_ERROR}`,\n }\n }\n content.screenshots = screenshots as string[]\n }\n const readme = input['readme']\n if (readme !== undefined) {\n if (typeof readme !== 'string' || readme.length > LISTING_README_MAX_CHARS) {\n return {\n ok: false,\n error: `readme must be markdown up to ${LISTING_README_MAX_CHARS} chars`,\n }\n }\n if (readme.trim()) content.readme = readme\n }\n const license = input['license']\n if (license !== undefined && license !== '') {\n if (typeof license !== 'string' || license.length > 40) {\n return { ok: false, error: 'license must be a short label (max 40)' }\n }\n content.license = license\n }\n const categories = input['categories']\n if (categories !== undefined) {\n if (\n !Array.isArray(categories) ||\n categories.length > 3 ||\n categories.some((entry) => !LISTING_CATEGORIES.includes(String(entry)))\n ) {\n return {\n ok: false,\n error: 'categories must be up to 3 entries from the fixed taxonomy',\n }\n }\n content.categories = categories.map(String)\n }\n return { ok: true, content }\n}\n\n/**\n * Publisher-profile fields beyond the identity trio (AGL-1009): the logo,\n * the support contact, and a FIXED set of external links. Fixed on purpose —\n * the storefront renders each as a known icon, and a free-form list would\n * turn the trust panel into a link farm.\n */\nexport interface PublisherProfileContent {\n avatarUrl?: string\n website?: string\n supportEmail?: string\n supportUrl?: string\n githubUrl?: string\n xUrl?: string\n linkedinUrl?: string\n}\n\n/** Social keys whose URL must live on the network's own host. */\nconst PUBLISHER_SOCIAL_HOSTS: Record<string, readonly string[]> = {\n githubUrl: ['github.com'],\n xUrl: ['x.com', 'twitter.com'],\n linkedinUrl: ['linkedin.com'],\n}\n\nconst SUPPORT_EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Validates the publisher-profile extras (AGL-1009), sharing\n * `validateListingContent`'s discipline on both of its halves: the LINKS are\n * https only and length capped, the LOGO is first-party media (AGL-3260).\n * Validated on the save route (server-owned like the handle — no client\n * write path carries these). An explicit empty string comes back as `''` so\n * the save route can distinguish \"clear this field\" from \"left untouched\".\n */\nexport function validatePublisherProfileContent(\n input: Record<string, unknown>,\n): { ok: boolean; error?: string; content?: PublisherProfileContent } {\n const content: PublisherProfileContent = {}\n /**\n * THE LOGO IS AN IMAGE FIELD, NOT A LINK FIELD (AGL-3260).\n *\n * It was validated as a link — any https URL — and the panel that edits it\n * only ever offers the media library, which since AGL-1215 hands back the\n * media-id-keyed CDN path (`/api/media/cdn/…`) rather than a storage URL.\n * A root-relative path is not an https URL, so the one value the form could\n * produce was the one value the route refused, and the publisher was told\n * their logo was malformed.\n *\n * Held to the same first-party rule as `logoUrl` and `screenshots` for the\n * reason given there (AGL-1701): this is an `<img src>` that other orgs'\n * users load on every listing's Publisher card, so it fetches with no\n * reader choice. That makes the fix a TIGHTENING as well — a third-party\n * `https://cdn.publisher.example/logo.png` no longer passes.\n */\n const avatarUrl = input['avatarUrl']\n if (avatarUrl !== undefined) {\n if (avatarUrl === '') {\n content.avatarUrl = ''\n } else if (!isPublisherAvatarValue(avatarUrl)) {\n return { ok: false, error: `avatarUrl ${LISTING_IMAGE_ERROR}` }\n } else {\n content.avatarUrl = avatarUrl\n }\n }\n const urlKeys = [\n 'website',\n 'supportUrl',\n 'githubUrl',\n 'xUrl',\n 'linkedinUrl',\n ] as const\n for (const key of urlKeys) {\n const value = input[key]\n if (value === undefined) continue\n if (value === '') {\n content[key] = ''\n continue\n }\n // The same https-or-nothing rule as listing URLs: `javascript:`, `data:`\n // and plain http all fail the one test.\n if (typeof value !== 'string' || !HTTPS_URL.test(value) || value.length > 500) {\n return { ok: false, error: `${key} must be an https URL` }\n }\n const hosts = PUBLISHER_SOCIAL_HOSTS[key]\n if (hosts) {\n let host = ''\n try {\n host = new URL(value).hostname.toLowerCase()\n } catch {\n return { ok: false, error: `${key} must be an https URL` }\n }\n if (!hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`))) {\n return { ok: false, error: `${key} must link to ${hosts[0]}` }\n }\n }\n content[key] = value\n }\n const supportEmail = input['supportEmail']\n if (supportEmail !== undefined) {\n if (supportEmail === '') {\n content.supportEmail = ''\n } else if (\n typeof supportEmail !== 'string' ||\n supportEmail.length > 200 ||\n !SUPPORT_EMAIL.test(supportEmail)\n ) {\n return { ok: false, error: 'supportEmail must be an email address' }\n } else {\n content.supportEmail = supportEmail\n }\n }\n return { ok: true, content }\n}\n\n/**\n * Render-time guard for publisher links (AGL-1009): only an `https://` URL\n * is ever emitted as an href. The save route already refuses anything else,\n * but the doc is client-updatable on its cosmetic fields historically, so\n * the renderer must not trust stored data it did not write.\n */\nexport function safePublisherHref(url: unknown): string | undefined {\n return typeof url === 'string' && /^https:\\/\\//i.test(url) && url.length <= 500\n ? url\n : undefined\n}\n\n/**\n * The same guard for the publisher's LOGO (AGL-3260), which is an `<img src>`\n * rather than an href and so has a different safe set: the media library's\n * root-relative CDN path is the value the picker produces and must render,\n * and a third-party https URL — fine as a link the reader chooses to follow —\n * is exactly what must not be fetched on their behalf.\n */\nexport function safePublisherImageSrc(src: unknown): string | undefined {\n return isPublisherAvatarValue(src) ? src : undefined\n}\n\n/**\n * Platform revenue share on paid listings (AGL-46) — UI COPY ONLY. The\n * checkout route prices from the `marketplaceFeePct` ENTITLEMENT\n * (`resolveMarketplaceFeePct`, AGL-1543), which resolves the effective\n * plan and per-org overrides; these constants exist for seller-facing\n * copy and must be kept in step with the plan table.\n */\nexport const MARKETPLACE_PLATFORM_FEE_PERCENT = 20\n/** Free-plan publishers pay a higher share. See AGL-1543 note above. */\nexport const MARKETPLACE_PLATFORM_FEE_PERCENT_FREE_PLAN = 30\n/** One-time listing price ceiling (whole USD). */\nexport const MARKETPLACE_MAX_PRICE_USD = 1000\n\n/**\n * One-time listing price FLOOR for a PAID listing (whole USD, AGL-2343).\n *\n * Marketplace checkout is a destination charge with no `application_fee_amount`\n * — deliberately, so the sales tax stays with the platform that owes it\n * (AGL-1544) — which means Stripe debits its fee from the PLATFORM's balance.\n * Stripe's fixed 30¢ dominates at low prices, so under this figure the\n * platform's cut is smaller than the cost of collecting it and every sale is a\n * loss. The floor is the cheapest listing price that still clears the cost of\n * processing it.\n *\n * NOT A CHOSEN NUMBER. `marketplaceMinPriceUsd` derives it from the plan\n * table's lowest take rate and the dearest enabled payment method; this is a\n * re-export so that the routes and the console forms cannot quote different\n * minimums at the same publisher. Zero stays legal — a free listing takes no\n * payment and costs nothing to process.\n */\nexport const MARKETPLACE_MIN_PRICE_USD = marketplaceMinPriceUsd()\n\n/**\n * The refusal message for a listing price, or `undefined` when the price may\n * be published (AGL-2343).\n *\n * ONE VALIDATOR FOR SEVEN DOORS. Each publish route used to inline its own\n * range check against the maximum — and `publish-theme.ts` and\n * `publish-layout.ts` had none at all, so a $250,000 theme was publishable.\n * The doors call this, and `publishPreconditionRefusal` calls it too, so a\n * route that forgets is still covered.\n *\n * Takes the price the route already rounded: a listing price is whole dollars\n * everywhere, and a validator that accepted $2.99 would be validating a number\n * that is never stored.\n */\nexport function marketplacePriceRefusal(priceUsd: number): string | undefined {\n if (!Number.isFinite(priceUsd) || priceUsd < 0) {\n return `Price must be 0 (free) or $${MARKETPLACE_MIN_PRICE_USD}–$${MARKETPLACE_MAX_PRICE_USD} USD`\n }\n if (priceUsd > MARKETPLACE_MAX_PRICE_USD) {\n return `Price must be 0 (free) or $${MARKETPLACE_MIN_PRICE_USD}–$${MARKETPLACE_MAX_PRICE_USD} USD`\n }\n // Zero is not \"below the floor\" — it is the free listing, which takes no\n // payment at all and so costs nothing to process.\n if (priceUsd > 0 && priceUsd < MARKETPLACE_MIN_PRICE_USD) {\n return (\n `A paid listing must be at least $${MARKETPLACE_MIN_PRICE_USD} USD — ` +\n `below that, processing the payment costs more than the platform fee ` +\n `on the sale. Use 0 for a free listing.`\n )\n }\n return undefined\n}\n\n/**\n * The rule a node tree meets before it lands on a canvas that did not author\n * it is core's (`@aglyn/aglyn/app-utils/node-definition-sanitizer`, AGL-2939),\n * under neutral names, because a model-generated tree passes through it too.\n * A publisher reads it as the marketplace's rule, so the marketplace re-exports\n * it under the names its publish routes and its docs use.\n */\nexport {\n PORTABLE_COMPONENT_ID_ALLOWLIST as MARKETPLACE_COMPONENT_ID_ALLOWLIST,\n PORTABLE_EMAIL_COMPONENT_ID_ALLOWLIST as MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n PORTABLE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST as MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n sanitizePortableDefinition as sanitizeMarketplaceDefinition,\n portableDefinitionToNested as marketplaceDefinitionToNested,\n PORTABLE_SAFE_HREF as MARKETPLACE_SAFE_HREF,\n PORTABLE_SAFE_SRC as MARKETPLACE_SAFE_SRC,\n PORTABLE_DEFINITION_MAX_BYTES as MARKETPLACE_DEFINITION_MAX_BYTES,\n type PortableDefinitionNodes as MarketplaceDefinitionNodes,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\n/** One row of the listing detail's `What's included` checklist. */\nexport interface ListingInclusion {\n label: string\n /** Whether the row is a positive inclusion or a stated limit. */\n tone: 'included' | 'note'\n}\n\n/** What each artifact type drops into the org when it installs. */\nconst ARTIFACT_INSTALL_RESULT: Record<MarketplaceArtifactType, string> = {\n plugin: 'A plugin, sandboxed on its own origin with a per-plugin CSP',\n component: 'An editable component you can place on any page',\n template: 'Editable pages you can rework in Besigner',\n layout: 'An editable layout you can apply to any page',\n datasetSchema: 'A new empty dataset with its fields already defined',\n emailTemplate: 'An editable email design you can send campaigns from',\n emailStarter:\n 'A new email in your Email templates list, ready to edit and send',\n theme: 'A theme applied to the site you choose',\n siteStarter: 'A new site, created from these pages and this theme',\n}\n\n/**\n * The `WHAT'S INCLUDED` checklist the marketplace listing mockup shows\n * (AGL-2173), derived entirely from facts the listing already carries.\n *\n * The mockup's own bullets — `12 responsive screens`, `Blog & work\n * layouts` — are publisher-authored prose, and nothing collects them:\n * there is no content manifest on a listing or a version, so counting\n * screens would mean inventing a number. What IS knowable is what the\n * install physically does, where it lands, whether it has been reviewed,\n * and under what licence — which is the question a shopper is asking when\n * they read that box.\n *\n * Ordered decision-first: what you get, then where it goes, then the two\n * facts that most often stop an install.\n */\nexport function listingInclusions(\n listing: {\n artifactType?: string\n type?: string\n kind?: string\n license?: string\n priceUsd?: number\n reviewStatus?: string\n },\n options: { reviewedVersion?: boolean } = {},\n): ListingInclusion[] {\n const type = listingArtifactType(listing)\n const rows: ListingInclusion[] = [\n { label: ARTIFACT_INSTALL_RESULT[type] ?? 'An installable artifact', tone: 'included' },\n ]\n const targets = installTargetsFor(listing)\n rows.push({\n label: targets.includes('org')\n ? 'Installs org-wide, covering sites you add later'\n : 'Installs per site — new sites are not covered automatically',\n // The host-only case is a real limit and the picker already has to say\n // so; softening it here would put the caveat only where nobody reads.\n tone: targets.includes('org') ? 'included' : 'note',\n })\n if (options.reviewedVersion) {\n rows.push({\n label: 'This version passed marketplace review',\n tone: 'included',\n })\n }\n if (listing.license) {\n rows.push({ label: `Licensed ${listing.license}`, tone: 'included' })\n }\n rows.push({\n label: Number(listing.priceUsd ?? 0) > 0\n ? 'A one-time purchase — updates to this listing are included'\n : 'Free, including every future update',\n tone: 'included',\n })\n return rows\n}\n\n/**\n * WHO STILL OWNS WHAT THEY BOUGHT — the one predicate (AGL-2158).\n *\n * `hasLivePurchase` (server/purchase-entitlement.ts) is the gate on all eight\n * ways into paid content, and it reads exactly one field: a purchase with\n * `refundedAt` — stamped by the `charge.refunded` and lost-`charge.dispute`\n * doors of the marketplace billing webhook — no longer entitles.\n *\n * The listing page carried its OWN copy of that question,\n * `some(p => p.listingId === listingId)`, with no refund test at all. The two\n * then disagreed on the one buyer they must not disagree on: the refunded\n * one. The page showed \"Purchased\", hid the buy button, and the install\n * routes answered 402 — a buyer who could neither install nor re-purchase.\n *\n * It lives HERE, in the model, rather than in the server module, because the\n * server module is the wrong side of the client/server boundary for a React\n * component and copying four characters of predicate is precisely how the two\n * came apart. This module is context-free by construction (see the header) —\n * importable from a client component, an API route and another plugin alike.\n */\nexport interface PurchaseLiveness {\n /** Stamped when a full refund or a lost dispute un-buys the listing. */\n refundedAt?: unknown\n listingId?: unknown\n /**\n * THE ORGANIZATION THE LICENCE BELONGS TO (AGL-2331).\n *\n * Absent on every purchase written before AGL-2331 — see\n * `purchaseEntitlesOrg` for what that absence means and why it is never\n * treated as \"no licence\".\n */\n buyerOrgId?: unknown\n /** The person who paid. Kept for the receipt trail and the legacy grant. */\n buyerUid?: unknown\n}\n\n/**\n * True when this purchase document still entitles.\n *\n * Deliberately a truthiness test and not `!= null`: `refundedAt` is a\n * Firestore Timestamp on the server, a client Timestamp in the browser and a\n * sentinel in the webhook's own tests, and every one of those is truthy while\n * a missing field (every purchase written before AGL-1546) is not.\n */\nexport function isLivePurchase(\n purchase: PurchaseLiveness | null | undefined,\n): boolean {\n return Boolean(purchase) && !purchase?.refundedAt\n}\n\n/**\n * True when this buyer's purchase documents include a live one for `listingId`.\n *\n * Both callers pass everything they read — the server's query is already\n * narrowed to the listing, the client's is narrowed only to the buyer — so the\n * listing filter belongs inside the shared predicate too, not beside it.\n */\nexport function hasLivePurchaseOf(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n): boolean {\n if (!listingId) return false\n return (purchases ?? []).some(\n (purchase) =>\n purchase?.listingId === listingId && isLivePurchase(purchase),\n )\n}\n/**\n * WHO A PURCHASE LICENSES (AGL-2331).\n *\n * ## The model\n *\n * **A marketplace purchase licenses an ORGANIZATION, not a person.** That is\n * not a new decision — it is the one already published. The Marketplace\n * Publisher Agreement §8.1 says a paid Artifact is licensed \"to the installing\n * organization\", and §2 grants the right to sublicense \"to organizations that\n * install it\". Until now the code enforced a per-PERSON licence instead, and\n * the mismatch cut both ways: an agency developer who is an owner across five\n * client workspaces bought once and installed into all five, and — because the\n * duplicate-purchase guard shares this predicate — could not buy a second\n * licence even when they wanted to. Conforming the code to the published terms\n * is the smaller of the two changes; the alternative amends a version-pinned\n * legal document and stops every publisher until they re-accept it.\n *\n * Three consequences follow, and all three are the point:\n *\n * 1. A licence held by org A does not install into org B. The agency buys per\n * client workspace, which is what the agreement says they are buying.\n * 2. Buying a second licence is a real second sale, not a `409`.\n * 3. Any member of the owning org with `installPlugins` may install what the\n * ORG bought — including colleagues who were not the buyer, and including\n * the buyer's replacement after they leave. A licence that evaporates when\n * one employee's account is deleted is not an organizational licence.\n *\n * ## The legacy grant, and why it never expires\n *\n * A purchase written before this change carries NO `buyerOrgId` — there was\n * no buyer org anywhere in the pipeline to record. Those are real purchases by\n * real customers, and reinterpreting one as \"licensed to no organization\"\n * would revoke access somebody paid for. So a purchase with no `buyerOrgId` at\n * all keeps its ORIGINAL, person-scoped meaning, forever: it entitles the uid\n * that bought it, in every org that uid can install into. Nothing is\n * migrated, nothing is claimed by the first org to use it, and nothing is\n * revoked — the ambiguity resolves in the customer's favour by construction,\n * with no backfill to get right and no window during which a paying customer\n * is locked out.\n *\n * The grandfather is bounded by time rather than policed: it can only ever\n * apply to purchases already written, because from AGL-2331 onward checkout\n * refuses to open a session that does not name a validated buyer org. It is\n * therefore a shrinking set that never grows, not a hole left open.\n *\n * `orgId` may be empty (a site with no owning org). That is not a licence to\n * anything, so only the legacy uid grant can hold — never a `buyerOrgId ===\n * ''` match, which is why the org branch tests for a non-empty string on the\n * document itself rather than comparing the two values directly.\n */\nexport function purchaseEntitlesOrg(\n purchase: PurchaseLiveness | null | undefined,\n actor: { orgId?: string | null; uid?: string | null },\n): boolean {\n if (!isLivePurchase(purchase)) return false\n const purchaseOrgId = purchase?.buyerOrgId\n if (typeof purchaseOrgId === 'string' && purchaseOrgId) {\n return Boolean(actor.orgId) && purchaseOrgId === actor.orgId\n }\n // Legacy: no buyer org was ever recorded, so it means what it meant when it\n // was sold. Never revoked, never migrated.\n return Boolean(actor.uid) && purchase?.buyerUid === actor.uid\n}\n\n/**\n * True when these purchase documents include one that licenses `orgId` for\n * `listingId` — the org-scoped counterpart of `hasLivePurchaseOf`.\n *\n * Same shape and same home as the liveness predicate, and for the same reason\n * (AGL-2158): the install routes, the checkout duplicate guard and the listing\n * page all have to answer \"does this workspace hold a licence\" identically, and\n * the way they came apart last time was four characters of predicate copied\n * into a component.\n */\nexport function hasOrgLicenceOf(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n actor: { orgId?: string | null; uid?: string | null },\n): boolean {\n if (!listingId) return false\n return (purchases ?? []).some(\n (purchase) =>\n purchase?.listingId === listingId && purchaseEntitlesOrg(purchase, actor),\n )\n}\n\n/**\n * Every org id these purchases license for `listingId`, in document order.\n *\n * What the console renders so a buyer can see WHICH workspace a licence they\n * paid for belongs to (AGL-2331) — the question that has no answer at all\n * while entitlement is person-scoped, and the one an agency has to answer\n * before deciding whether it needs another.\n *\n * Legacy person-scoped purchases contribute no org id, because they name\n * none; a caller rendering this list has to say so rather than invent one.\n */\nexport function licensedOrgIdsFor(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n): string[] {\n const seen: string[] = []\n for (const purchase of purchases ?? []) {\n if (purchase?.listingId !== listingId || !isLivePurchase(purchase)) continue\n const orgId = purchase?.buyerOrgId\n if (typeof orgId === 'string' && orgId && !seen.includes(orgId)) {\n seen.push(orgId)\n }\n }\n return seen\n}\n\n"],"names":["isFirstPartyMediaSrc","MEDIA_REF_PREFIX","marketplaceMinPriceUsd","offeredPluginVersion","isListingBrowsable","isListingDeleted","isPrivateListing","LISTING_CLIENT_WRITABLE_FIELDS","LISTING_UNPERSISTED_FIELDS","listingArtifactType","PUBLISHER_HANDLE_PATTERN","isValidPublisherHandle","handle","test","ARTIFACT_TYPE_LABELS","INSTALL_TARGETS","LISTING_CATEGORIES","resolveOrgInstallSummary","resolvePluginInstallState","resolveUninstallTargets","listingArtifactLabel","listing","installTargetsFor","resolveInstallPlan","targeting","hosts","targets","canOrgPin","includes","canHostPin","scope","allHostIds","map","hostId","selectedHostIds","VERIFICATION_BLOCK_MESSAGES","VERIFICATION_DECLINE_COOLDOWN_DAYS","timestampMs","verificationRequestBlock","isVersionApproved","version","reviewState","installsUnreviewedFallback","viewerOrgId","revocation","profileId","Boolean","String","latestVersion","newestApprovedVersion","versions","approved","filter","entry","length","reduce","best","publishedAt","toMillis","missingPublicListingContent","missing","description","trim","push","readme","license","LISTING_README_MAX_CHARS","LISTING_MAX_SCREENSHOTS","HTTPS_URL","LISTING_IMAGE_ERROR","LISTING_URL_MAX_CHARS","isListingImageValue","value","isPublisherAvatarValue","startsWith","validateListingContent","input","content","key","undefined","ok","error","logoUrl","screenshots","Array","isArray","some","url","categories","PUBLISHER_SOCIAL_HOSTS","githubUrl","xUrl","linkedinUrl","SUPPORT_EMAIL","validatePublisherProfileContent","avatarUrl","urlKeys","host","URL","hostname","toLowerCase","allowed","endsWith","supportEmail","safePublisherHref","safePublisherImageSrc","src","MARKETPLACE_PLATFORM_FEE_PERCENT","MARKETPLACE_PLATFORM_FEE_PERCENT_FREE_PLAN","MARKETPLACE_MAX_PRICE_USD","MARKETPLACE_MIN_PRICE_USD","marketplacePriceRefusal","priceUsd","Number","isFinite","PORTABLE_COMPONENT_ID_ALLOWLIST","MARKETPLACE_COMPONENT_ID_ALLOWLIST","PORTABLE_EMAIL_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","PORTABLE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","sanitizePortableDefinition","sanitizeMarketplaceDefinition","portableDefinitionToNested","marketplaceDefinitionToNested","PORTABLE_SAFE_HREF","MARKETPLACE_SAFE_HREF","PORTABLE_SAFE_SRC","MARKETPLACE_SAFE_SRC","PORTABLE_DEFINITION_MAX_BYTES","MARKETPLACE_DEFINITION_MAX_BYTES","ARTIFACT_INSTALL_RESULT","plugin","component","template","layout","datasetSchema","emailTemplate","emailStarter","theme","siteStarter","listingInclusions","options","type","rows","label","tone","reviewedVersion","isLivePurchase","purchase","refundedAt","hasLivePurchaseOf","purchases","listingId","purchaseEntitlesOrg","actor","purchaseOrgId","buyerOrgId","orgId","uid","buyerUid","hasOrgLicenceOf","licensedOrgIdsFor","seen"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;CAIC,GAED,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,8EAA8E;AAC9E,SACEA,oBAAoB,EACpBC,gBAAgB,QACX,mCAAkC;AACzC,SAASC,sBAAsB,QAAQ,2BAAuB;AAG9D,SACEC,oBAAoB,QAEf,yCAAwC;AAC/C,4EAA4E;AAC5E,6EAA6E;AAC7E,0EAA0E;AAC1E,0EAA0E;AAC1E,2EAA2E;AAC3E,4EAA4E;AAC5E,2EAA2E;AAC3E,qDAAqD;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AAOD,kBAAkB,YAAYA,eAAe;QACtD,OAAO9G,QAAQ6G,MAAMG,KAAK,KAAKF,kBAAkBD,MAAMG,KAAK;IAC9D;IACA,4EAA4E;IAC5E,2CAA2C;IAC3C,OAAOhH,QAAQ6G,MAAMI,GAAG,KAAKV,CAAAA,4BAAAA,SAAUW,QAAQ,MAAKL,MAAMI,GAAG;AAC/D;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASE,gBACdT,SAA8E,EAC9EC,SAAiB,EACjBE,KAAqD;IAErD,IAAI,CAACF,WAAW,OAAO;IACvB,OAAO,CAACD,oBAAAA,YAAa,EAAE,EAAElE,IAAI,CAC3B,CAAC+D,WACCA,CAAAA,4BAAAA,SAAUI,SAAS,MAAKA,aAAaC,oBAAoBL,UAAUM;AAEzE;AAEA;;;;;;;;;;CAUC,GACD,OAAO,SAASO,kBACdV,SAA8E,EAC9EC,SAAiB;IAEjB,MAAMU,OAAiB,EAAE;IACzB,KAAK,MAAMd,YAAYG,oBAAAA,YAAa,EAAE,CAAE;QACtC,IAAIH,CAAAA,4BAAAA,SAAUI,SAAS,MAAKA,aAAa,CAACL,eAAeC,WAAW;QACpE,MAAMS,QAAQT,4BAAAA,SAAUQ,UAAU;QAClC,IAAI,OAAOC,UAAU,YAAYA,SAAS,CAACK,KAAKvI,QAAQ,CAACkI,QAAQ;YAC/DK,KAAKpG,IAAI,CAAC+F;QACZ;IACF;IACA,OAAOK;AACT"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/marketplace.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 * Marketplace marketplace v1 (AGL-44): shared types + the server-side\n * sanitization pass that gates publishing a host component definition as a\n * public listing. Pure data module — safe to import from API routes.\n */\n\n// The leaf module, not a barrel: this model is reached from both the browser\n// and API routes, and `@aglyn/aglyn` carries `createContext` (illegal in a\n// Server Component) while `@aglyn/aglyn/server` carries `node:fs` (illegal in\n// the browser). Neither is safe from here; the deep path has no dependencies.\nimport {\n isFirstPartyMediaSrc,\n MEDIA_REF_PREFIX,\n} from '@aglyn/aglyn/app-utils/media-ref'\nimport { marketplaceMinPriceUsd } from './listing-price-floor'\nimport { landsInPublisherWorkspace } from './own-listing'\nimport type { InstallableArtifactType as MarketplaceArtifactType } from '@aglyn/aglyn/app-utils/artifact-provenance'\nimport type { ListingVerificationRequest } from './listing-verification'\nimport {\n offeredPluginVersion,\n type PluginRevocation,\n} from '@aglyn/aglyn/app-utils/plugin-manifest'\n// Visibility lives in core (AGL-876), for the same reason the artifact-type\n// union and the verification policy do: the console's listing route asks the\n// question and `scope:app` may not depend on `aglyn:addons`. Imported AND\n// re-exported — `installTargetsFor` and `listingArtifactLabel` below call\n// `listingArtifactType` locally, and a bare `export … from` binds nothing.\n// The write-deny classification (AGL-1361) rides along for the same reason:\n// it is a statement about the fields this policy reads, and the guard that\n// enforces it lives in core beside the rules parser.\nimport {\n isListingBrowsable,\n isListingDeleted,\n isPrivateListing,\n LISTING_CLIENT_WRITABLE_FIELDS,\n LISTING_UNPERSISTED_FIELDS,\n listingArtifactType,\n} from './listing-visibility'\n\nexport {\n isListingBrowsable,\n isListingDeleted,\n isPrivateListing,\n LISTING_CLIENT_WRITABLE_FIELDS,\n LISTING_UNPERSISTED_FIELDS,\n listingArtifactType,\n}\n\n/**\n * `profiles/{uid}` — a person's public identity.\n *\n * NOT a publisher identity as of AGL-652: publishing is org-only, and the\n * marketplace presence lives on `publisherProfiles/{orgId}` below. This doc\n * survives because it is also the support forum's author identity, which\n * renders poster names from `displayName`.\n */\nexport interface MarketplaceProfile {\n handle: string\n displayName: string\n bio?: string\n avatarUrl?: string\n}\n\n/**\n * `publisherProfiles/{orgId}` — an organization's marketplace presence\n * (AGL-652). Publishing is org-only: an org publishes, an org gets paid, and\n * the org is who buyers see. Keyed by org id so authorization is a plain org\n * role check with no ownership indirection.\n *\n * `stripeAccountId` / `stripeChargesEnabled` / `stripeAccountLivemode` are\n * written only by the Connect route via the Admin SDK and are frozen from\n * client writes by the rules — they decide who receives money, and\n * `stripeAccountLivemode` is a gate INPUT (AGL-2471), so a client that could\n * write it could re-open the hole by asserting its own readiness.\n */\nexport interface MarketplacePublisherProfile {\n /** Unique marketplace handle; reserved in `publisherHandles/{handle}`. */\n handle: string\n displayName: string\n bio?: string\n avatarUrl?: string\n website?: string\n /** Server-only. */\n stripeAccountId?: string\n /** Server-only; true once Connect onboarding can accept charges. */\n stripeChargesEnabled?: boolean\n /**\n * Server-only; which Stripe world the account belongs to (AGL-2471).\n * `true` = live, `false` = test, ABSENT = never established — and on a live\n * deployment absent refuses the sale, because a payout destination whose\n * mode nobody verified is exactly what shipped three unusable storefronts.\n */\n stripeAccountLivemode?: boolean\n}\n\n/**\n * `publisherHandles/{handle}` — uniqueness reservation for publisher handles,\n * mirroring `orgSlugs` (AGL-652). Without it two publishers could claim the\n * same handle, which the marketplace URL space cannot represent. `movedTo`\n * tombstones a renamed handle so old links can still resolve.\n */\nexport interface PublisherHandleReservation {\n orgId: string\n movedTo?: string\n}\n\n/**\n * Publisher handles share the org-slug shape: 3–30 chars, lowercase\n * alphanumeric plus internal hyphens. Single source of truth — the two\n * marketplace pages historically applied two subtly different regexes to the\n * same field (AGL-653).\n */\nexport const PUBLISHER_HANDLE_PATTERN = /^[a-z0-9][a-z0-9-]{1,28}[a-z0-9]$/\n\nexport function isValidPublisherHandle(handle: string): boolean {\n return PUBLISHER_HANDLE_PATTERN.test(handle)\n}\n\n/**\n * `marketplaceListings/{listingId}` — public component listing. Version\n * snapshots live in the `versions/{n}` subcollection; installs copy a pinned\n * version into `hosts/{hostId}/components` so the existing drawer/graft\n * pipeline applies unchanged.\n */\nexport interface MarketplaceListing {\n profileId: string\n displayName: string\n description?: string\n category?: string\n /**\n * What this listing publishes (AGL-654). One discriminator for every\n * artifact type — the previous scheme split across two orthogonal fields\n * (`type: 'component'|'plugin'` plus a separate `kind: 'template'`), so a\n * template was \"kind template with no type\" and each installer branched on\n * whichever field it happened to care about. That does not survive adding\n * layouts, dataset schemas and email templates.\n *\n * Read it through `listingArtifactType()`, never directly — listings\n * written before this field still carry only the legacy pair.\n */\n artifactType?: MarketplaceArtifactType\n /** @deprecated Legacy discriminator; use `artifactType` (AGL-654). */\n type?: 'component' | 'plugin'\n /** @deprecated Legacy discriminator; use `artifactType` (AGL-654). */\n kind?: 'template'\n latestVersion: number | string\n /** Plugin manifest id, for `type: 'plugin'` listings (AGL-45). */\n pluginId?: string\n /** One-time price in whole USD; 0/absent = free (AGL-46). */\n priceUsd?: number\n deletedAt?: unknown\n // Listing content (AGL-430, Strapi Market parity) — publisher-authored,\n // rendered on the marketplace detail page. All optional; validated by\n // validateListingContent on the API path and SANITIZED at render time\n // (the doc is publisher-writable, so renderers never trust it).\n logoUrl?: string\n screenshots?: string[]\n /** Markdown documentation shown on the listing page (no raw HTML). */\n readme?: string\n homepageUrl?: string\n repositoryUrl?: string\n /** SPDX-ish license label, e.g. \"MIT\". */\n license?: string\n categories?: string[]\n /**\n * Marketplace review lifecycle (AGL-432). Absent = legacy listing,\n * treated as 'listed'. New plugin listings start 'submitted'; staff move\n * them through the queue. Only 'listed'/'verified' (or legacy) plugin\n * listings appear in browse for non-owners.\n */\n reviewStatus?: ListingReviewStatus\n /**\n * The publisher's standing ask for the Verified badge (AGL-1217).\n *\n * Its own field, never a `reviewStatus` member — see\n * {@link ListingVerificationRequest}. Server-owned: the publisher route only\n * moves it to `pending`/`withdrawn`, and only staff can decide it. Asking\n * never grants anything; the checklist gate on `verify` stays the one route\n * to the badge.\n */\n verificationRequest?: ListingVerificationRequest\n // Server-managed. These were written by the publish/install/review paths\n // but never declared, so callers reached for `as any` (AGL-654).\n /** Publishing org id — the publisher profile's doc id (AGL-652). */\n publisherOrgId?: string\n /** Source component for a `component` listing. */\n sourceComponentId?: string\n /** Source site for a `template` listing. */\n sourceHostId?: string\n /**\n * Source site for a `siteStarter` listing (AGL-4049): the one-listing-per-\n * source key `publish-starter` looks up. Its own field, never `sourceHostId`:\n * the template, layout and theme doors write that one and key on it with a\n * `limit(1)`, so a shared key would cross a site's starter with its template.\n */\n sourceStarterHostId?: string\n /**\n * The platform published it (AGL-4049). Server-owned and ordering only: the\n * starter picker lists these first. No door, price or checkout branches on\n * it; the seed and staff write it, a publish never does.\n */\n official?: boolean\n /**\n * A site starter's facets (AGL-4049), stamped from its payload by\n * `siteStarterFacetFields` so a starter search can match them. Server-owned:\n * they describe the stored version, so a client rewrite would list a\n * starter under a kind, theme or page count it does not create.\n */\n starterKind?: string | null\n starterBase?: string | null\n starterFonts?: string | null\n starterPages?: number\n starterMode?: 'base' | 'ai'\n /** Incremented by the install API; frozen from client writes. */\n installCount?: number\n /**\n * How many installs are LIVE right now — `installCount`'s sibling, and\n * undeclared here until AGL-1420 went looking for it.\n *\n * That omission was the whole bug. AGL-1361's coverage guard builds the\n * listing's field universe from this interface, the rules deny-list and the\n * resolvers, so a server-owned field in none of the three is not classified\n * as exposed — it is INVISIBLE to the guard, which is a worse failure than\n * being classified wrongly. `installCount` was denied and this was not, so\n * the sibling counter a publisher-org owner/admin could write was the one\n * the browse grid and the listing header print to buyers.\n *\n * Written by the install/uninstall routes and by AGL-1419's derivation.\n */\n activeInstalls?: number\n /**\n * AGL-1419's derived-count cache: the pin count as last verified, the wall\n * clock it was verified at, and the per-version split.\n *\n * Server-owned for a stronger reason than the counters themselves. They are\n * not merely a number that could be wrong — `verifiedLivePins` treats the\n * triple as FRESH when `pinnedActiveInstalls === activeInstalls` and the\n * timestamp is inside the TTL, and then returns `pinnedVersionInstalls`\n * without querying anything. A client that could write all four could pin\n * the cache open on numbers it chose and suppress the re-derivation that\n * exists to bring a count back down.\n */\n pinnedActiveInstalls?: number\n pinsVerifiedAtMs?: number\n pinnedVersionInstalls?: Record<string, number>\n previewImageUrl?: string\n screenCount?: number\n versionHistory?: Array<{ version: number | string; publishedAt?: unknown }>\n createdAt?: unknown\n updatedAt?: unknown\n /** Staff review audit (AGL-432); server-owned (AGL-651). */\n reviewedBy?: string\n reviewedAt?: unknown\n rejectionReason?: string\n /**\n * What the marketplace lists query by (AGL-3321), derived by the server\n * from the fields above after every write (`listingQueryFields`,\n * `refreshListingQueryFields`) and denied to clients.\n */\n nameLower?: string\n nameTokens?: string[]\n nameReversed?: string\n browseAudience?: string[]\n browseTokens?: string[]\n takenDown?: boolean\n /**\n * The publishing workspace is locked (AGL-3365): the listing is out of\n * browse, search and its page until the lift clears it. Written only by\n * the lockdown's marketplace participant, which clears exactly the\n * listings it stamped; server-owned.\n */\n workspaceLockedAt?: unknown\n}\n\n/**\n * Everything an org can publish to the marketplace (AGL-654): every kind of\n * content the platform can install.\n *\n * The union is core's `InstallableArtifactType` — installed content is read by\n * surfaces that are not the marketplace, through the provenance stamp — and is\n * re-exported here under the name publishing code has always used.\n */\nexport type { MarketplaceArtifactType }\n\nexport {\n ARTIFACT_TYPE_LABELS,\n INSTALL_TARGETS,\n type InstallPin,\n type InstallTarget,\n LISTING_CATEGORIES,\n type OrgInstallSite,\n type OrgInstallSummary,\n type PluginInstallState,\n resolveOrgInstallSummary,\n resolvePluginInstallState,\n resolveUninstallTargets,\n type UninstallTarget,\n} from './marketplace-catalog'\nimport { ARTIFACT_TYPE_LABELS, INSTALL_TARGETS, type InstallPin, type InstallTarget, LISTING_CATEGORIES } from './marketplace-catalog'\n\n/** The friendly artifact-type label for a listing (AGL-864). */\nexport function listingArtifactLabel(listing: {\n artifactType?: string\n type?: string\n kind?: string\n}): string {\n return ARTIFACT_TYPE_LABELS[listingArtifactType(listing)] ?? 'Component'\n}\n\n/** Targets a listing can be installed to, defaulting to host-only. */\nexport function installTargetsFor(listing: {\n artifactType?: string\n type?: string\n kind?: string\n}): readonly InstallTarget[] {\n return INSTALL_TARGETS[listingArtifactType(listing)] ?? ['host']\n}\n\n\n/** How the admin chose to target an install from the org marketplace. */\nexport type InstallTargeting = 'all-sites' | 'selected-sites'\n\n/** One concrete install operation: an org pin, or a pin on a named host. */\nexport interface InstallPlanStep {\n scope: InstallTarget\n /** Present iff `scope === 'host'`. */\n hostId?: string\n}\n\n/**\n * Turns a targeting choice into the concrete install operations for a listing\n * (AGL-773), honoring what each artifact type physically supports (see\n * {@link INSTALL_TARGETS}).\n *\n * The rules aren't uniform, and the picker must not promise what an artifact\n * can't do:\n * - **Org-pinnable** (plugin, datasetSchema) + \"all sites\" → a SINGLE org pin,\n * which also covers sites created later.\n * - **Host-scoped** (component, template, layout, emailTemplate) has no org\n * pin, so \"all sites\" fans out to every CURRENT host — new sites are NOT\n * covered automatically. The UI has to say so.\n * - \"Selected sites\" is always host pins, even for an org-pinnable artifact:\n * the admin named specific sites, so honor that literally — UNLESS the\n * artifact can't host-pin at all (datasetSchema), where the per-site choice\n * is meaningless and collapses to the org pin.\n */\nexport function resolveInstallPlan(\n listing: { artifactType?: string; type?: string; kind?: string },\n targeting: InstallTargeting,\n hosts: {\n selectedHostIds: readonly string[]\n allHostIds: readonly string[]\n },\n): InstallPlanStep[] {\n const targets = installTargetsFor(listing)\n const canOrgPin = targets.includes('org')\n const canHostPin = targets.includes('host')\n if (targeting === 'all-sites') {\n if (canOrgPin) return [{ scope: 'org' }]\n return hosts.allHostIds.map((hostId) => ({ scope: 'host', hostId }))\n }\n // selected-sites\n if (!canHostPin) return [{ scope: 'org' }]\n return hosts.selectedHostIds.map((hostId) => ({ scope: 'host', hostId }))\n}\n\nexport type ListingReviewStatus =\n | 'submitted'\n | 'in_review'\n | 'listed'\n | 'verified'\n | 'rejected'\n\n/**\n * Verification requests lived in core from AGL-1217 because the console's\n * STAFF REVIEW ROUTE needed the policy and `scope:app` may not depend on\n * `aglyn:addons`. That route is the plugin's own surface since `38c4b533c`,\n * so the reason expired with it and the module came home (AGL-3080).\n *\n * Still re-exported from here, which is the part that did not change:\n * publishing code keeps one import site whether the policy is a lib away or\n * a file away.\n */\nexport {\n VERIFICATION_BLOCK_MESSAGES,\n VERIFICATION_DECLINE_COOLDOWN_DAYS,\n timestampMs,\n verificationRequestBlock,\n} from './listing-verification'\nexport type {\n ListingVerificationRequest,\n TimestampLike,\n VerifiableListing,\n VerificationRequestBlock,\n VerificationRequestState,\n} from './listing-verification'\n\n\n/**\n * Per-VERSION review state (AGL-966).\n *\n * Approval is a statement about specific bytes, so it lives on the version\n * doc beside the verifier verdict and the review checklist — both already\n * keyed to sha256. It used to live on the listing, which meant a publisher\n * could get v1.0.0 verified and then ship v1.0.1 containing anything: the\n * listing kept its status, the queue never surfaced the update, and\n * installs resolved `latestVersion`.\n */\nexport type PluginVersionReviewState = 'pending' | 'approved' | 'rejected'\n\n/**\n * The LISTING's cached summary of the version it currently offers.\n *\n * A different field from the one above and a different set of values, which is\n * the whole reason it is written down here. `reviewState` lives on the version\n * document and is a verdict about specific bytes;\n * `latestVersionReviewState` lives on the LISTING and exists so browse cards\n * and the listing page can answer \"have the bytes on offer been read?\" without\n * a per-listing subcollection read.\n *\n * `'revoked'` is the value that only ever appears HERE. A kill is not a review\n * verdict: the version keeps the `'approved'` it earned — the staff surface\n * shows \"Disabled\" beside that verdict rather than instead of it, because\n * collapsing the two would erase what the publisher earned — and it is only\n * this listing-level summary that flips, so the \"Reviewed\" chip drops and the\n * caution alert raises while the audit trail stays intact.\n *\n * The practical consequence, and the reason this is a type rather than a\n * comment: the staff review QUEUE keys on the version's `reviewState`, never\n * on this field. Were it to key on this one, every revoked version would\n * reappear in the queue indistinguishable from one awaiting its first review,\n * and a reviewer acting in good faith on a queue they trusted could approve a\n * version somebody had deliberately killed. The two fields are not\n * interchangeable and this names why.\n */\nexport type ListingLatestVersionReviewState =\n | PluginVersionReviewState\n | 'revoked'\n\n\nexport interface ReviewableVersion {\n version?: string\n reviewState?: string\n publishedAt?: { toMillis?: () => number } | null\n}\n\n/** Only approved bytes may be installed. Absent state is NOT approval. */\nexport function isVersionApproved(\n version: { reviewState?: string } | null | undefined,\n): boolean {\n return version?.reviewState === 'approved'\n}\n\n/**\n * Whether an install would hand the viewer UNREVIEWED bytes (AGL-1083).\n *\n * `install-plugin` deliberately lets a publisher install their own\n * unapproved version — you cannot test a version you cannot install, and\n * the AGL-969 checklist asks them to confirm they tested these exact bytes\n * on a site they control. The route reaches that case through\n * `newestApprovedVersion(...) ?? fallback`, where the fallback is\n * `latestVersion` and applies ONLY when the caller owns the listing and no\n * approved version exists at all.\n *\n * Lives here rather than in the listing component because the UI has to\n * describe exactly what the route will do. Two independent readings of\n * \"would this be unreviewed?\" is how the affordance ends up warning about\n * the wrong installs, or staying silent on the right ones.\n *\n * The route's `newest` is `newestInstallableVersion` since AGL-2368 — a\n * revoked version is no longer a candidate, so it no longer suppresses the\n * fallback either. `revocation` is optional because most callers have none;\n * without it this asks the pre-AGL-2368 question, which is the same answer\n * whenever the mirror is current.\n */\nexport function installsUnreviewedFallback(\n listing:\n | {\n profileId?: string\n latestVersion?: string | number\n latestApprovedVersion?: string | number\n }\n | null\n | undefined,\n viewerOrgId: string | null | undefined,\n revocation?: PluginRevocation | null,\n): boolean {\n if (!listing?.profileId || !viewerOrgId) return false\n // Only the publishing org gets the fallback; everyone else is refused.\n if (!landsInPublisherWorkspace(listing.profileId, viewerOrgId)) return false\n // An INSTALLABLE version exists → the route serves THAT, however much newer\n // the pending one is. Not an unreviewed install. Reading approval alone got\n // this backwards for a revoked listing: the route would fall back to\n // `latestVersion` for the owner and hand over unreviewed bytes, while the\n // page said nothing, because a stopped version still counted as approved.\n if (offeredPluginVersion(listing, revocation)) return false\n return Boolean(String(listing.latestVersion ?? ''))\n}\n\n/**\n * The version a fresh install should pin: newest APPROVED, never\n * `latestVersion`. A pending update is simply not offered, so publishing\n * cannot ship code past review, and the previously approved version keeps\n * installing while the new one waits.\n */\nexport function newestApprovedVersion<T extends ReviewableVersion>(\n versions: readonly T[],\n): T | null {\n const approved = versions.filter((entry) => isVersionApproved(entry))\n if (!approved.length) return null\n return approved.reduce((best, entry) =>\n (entry.publishedAt?.toMillis?.() ?? 0) >\n (best.publishedAt?.toMillis?.() ?? 0)\n ? entry\n : best,\n )\n}\n\n/**\n * What a listing is still missing before it can face the marketplace\n * (AGL-968/994).\n *\n * A private plugin is allowed to be undocumented — its only audience already\n * knows what it is and why it exists. A public one is not: description,\n * README and license are what a stranger deciding whether to run your code\n * has to go on, and they are exactly the fields the review checklist asks\n * about. So going public is gated on the METADATA, never on a re-review —\n * approval is a statement about bytes, and the bytes did not change.\n *\n * Returns the human field names, so the caller can say what to fix rather\n * than just refusing.\n */\nexport function missingPublicListingContent(listing: {\n description?: string\n readme?: string\n license?: string\n}): string[] {\n const missing: string[] = []\n if (!listing.description?.trim()) missing.push('a description')\n if (!listing.readme?.trim()) missing.push('a README')\n if (!listing.license?.trim()) missing.push('a license')\n return missing\n}\n\n\nexport const LISTING_README_MAX_CHARS = 20_000\nexport const LISTING_MAX_SCREENSHOTS = 6\n\nconst HTTPS_URL = /^https:\\/\\/[^\\s]+$/\n\n/**\n * The message every listing IMAGE field returns when it is refused. Names the\n * remedy, because \"must be an https URL\" was true of the value the publisher\n * just typed and told them nothing.\n */\nexport const LISTING_IMAGE_ERROR =\n 'must be an image from your media library — paste a link and the people ' +\n 'browsing your listing would be loading it from a server you control'\n\n/** Length cap shared by every listing URL field. */\nconst LISTING_URL_MAX_CHARS = 500\n\n/**\n * Whether a listing image field is one we will store (AGL-1701).\n *\n * Listing artwork is the one publisher-supplied value that OTHER orgs' users\n * load. It is also, established while fixing this, gated by nothing: review\n * is a statement about a version's bytes (AGL-966), the staff review route\n * never projects `logoUrl`/`screenshots` so a reviewer cannot see them even\n * if the checklist asked, and `update-listing` writes them at any time\n * without touching `reviewStatus` — so a listing can pass review with benign\n * artwork and swap it afterwards while still reading `verified`.\n *\n * Constraining the INPUT rather than sanitizing the output is the whole\n * point: the render sites are three components and an `og:image`, and the\n * next one added would not know to sanitize.\n */\nfunction isListingImageValue(value: unknown): value is string {\n return (\n typeof value === 'string' &&\n value.length <= LISTING_URL_MAX_CHARS &&\n isFirstPartyMediaSrc(value)\n )\n}\n\n/**\n * Whether a value may be a publisher's LOGO (AGL-3260).\n *\n * The listing-image rule, minus the private `media:` reference. A listing's\n * logo may be one because a caller that signs its own links can resolve it;\n * nothing that renders a publisher avatar signs anything, so a reference\n * there would store a value every render site must turn back into the\n * fallback initial — a logo that looks saved and is never seen.\n *\n * `startsWith` rather than `isMediaRef`, for the reason that predicate's own\n * neighbour gives: negating a `value is string` guard on a value already\n * known to be a string leaves the else branch `never`.\n */\nfunction isPublisherAvatarValue(value: unknown): value is string {\n return isListingImageValue(value) && !value.startsWith(MEDIA_REF_PREFIX)\n}\n\n/**\n * Validates publisher-editable listing content (AGL-430). Returns the\n * normalized subset to persist, or an error. Shared by publish and the\n * update-listing action so both paths accept exactly the same shapes.\n *\n * IMAGE fields and LINK fields are validated differently (AGL-1701).\n * `homepageUrl` and `repositoryUrl` stay any-https: they are anchors a reader\n * chooses to follow, and a publisher's homepage living on the publisher's\n * domain is the entire point of the field. `logoUrl` and `screenshots` are\n * `<img src>`, which fetches with no such choice, so those are held to\n * first-party media.\n */\nexport function validateListingContent(input: Record<string, unknown>): {\n ok: boolean\n error?: string\n content?: Partial<MarketplaceListing>\n} {\n const content: Partial<MarketplaceListing> = {}\n for (const key of ['homepageUrl', 'repositoryUrl'] as const) {\n const value = input[key]\n if (value === undefined || value === '') continue\n if (\n typeof value !== 'string' ||\n !HTTPS_URL.test(value) ||\n value.length > LISTING_URL_MAX_CHARS\n ) {\n return { ok: false, error: `${key} must be an https URL` }\n }\n content[key] = value\n }\n const logoUrl = input['logoUrl']\n if (logoUrl !== undefined && logoUrl !== '') {\n if (!isListingImageValue(logoUrl)) {\n return { ok: false, error: `logoUrl ${LISTING_IMAGE_ERROR}` }\n }\n content.logoUrl = logoUrl\n }\n const screenshots = input['screenshots']\n if (screenshots !== undefined) {\n if (\n !Array.isArray(screenshots) ||\n screenshots.length > LISTING_MAX_SCREENSHOTS ||\n screenshots.some((url) => !isListingImageValue(url))\n ) {\n return {\n ok: false,\n error:\n `screenshots must be up to ${LISTING_MAX_SCREENSHOTS} images, and ` +\n `each ${LISTING_IMAGE_ERROR}`,\n }\n }\n content.screenshots = screenshots as string[]\n }\n const readme = input['readme']\n if (readme !== undefined) {\n if (typeof readme !== 'string' || readme.length > LISTING_README_MAX_CHARS) {\n return {\n ok: false,\n error: `readme must be markdown up to ${LISTING_README_MAX_CHARS} chars`,\n }\n }\n if (readme.trim()) content.readme = readme\n }\n const license = input['license']\n if (license !== undefined && license !== '') {\n if (typeof license !== 'string' || license.length > 40) {\n return { ok: false, error: 'license must be a short label (max 40)' }\n }\n content.license = license\n }\n const categories = input['categories']\n if (categories !== undefined) {\n if (\n !Array.isArray(categories) ||\n categories.length > 3 ||\n categories.some((entry) => !LISTING_CATEGORIES.includes(String(entry)))\n ) {\n return {\n ok: false,\n error: 'categories must be up to 3 entries from the fixed taxonomy',\n }\n }\n content.categories = categories.map(String)\n }\n return { ok: true, content }\n}\n\n/**\n * Publisher-profile fields beyond the identity trio (AGL-1009): the logo,\n * the support contact, and a FIXED set of external links. Fixed on purpose —\n * the storefront renders each as a known icon, and a free-form list would\n * turn the trust panel into a link farm.\n */\nexport interface PublisherProfileContent {\n avatarUrl?: string\n website?: string\n supportEmail?: string\n supportUrl?: string\n githubUrl?: string\n xUrl?: string\n linkedinUrl?: string\n}\n\n/** Social keys whose URL must live on the network's own host. */\nconst PUBLISHER_SOCIAL_HOSTS: Record<string, readonly string[]> = {\n githubUrl: ['github.com'],\n xUrl: ['x.com', 'twitter.com'],\n linkedinUrl: ['linkedin.com'],\n}\n\nconst SUPPORT_EMAIL = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/\n\n/**\n * Validates the publisher-profile extras (AGL-1009), sharing\n * `validateListingContent`'s discipline on both of its halves: the LINKS are\n * https only and length capped, the LOGO is first-party media (AGL-3260).\n * Validated on the save route (server-owned like the handle — no client\n * write path carries these). An explicit empty string comes back as `''` so\n * the save route can distinguish \"clear this field\" from \"left untouched\".\n */\nexport function validatePublisherProfileContent(\n input: Record<string, unknown>,\n): { ok: boolean; error?: string; content?: PublisherProfileContent } {\n const content: PublisherProfileContent = {}\n /**\n * THE LOGO IS AN IMAGE FIELD, NOT A LINK FIELD (AGL-3260).\n *\n * It was validated as a link — any https URL — and the panel that edits it\n * only ever offers the media library, which since AGL-1215 hands back the\n * media-id-keyed CDN path (`/api/media/cdn/…`) rather than a storage URL.\n * A root-relative path is not an https URL, so the one value the form could\n * produce was the one value the route refused, and the publisher was told\n * their logo was malformed.\n *\n * Held to the same first-party rule as `logoUrl` and `screenshots` for the\n * reason given there (AGL-1701): this is an `<img src>` that other orgs'\n * users load on every listing's Publisher card, so it fetches with no\n * reader choice. That makes the fix a TIGHTENING as well — a third-party\n * `https://cdn.publisher.example/logo.png` no longer passes.\n */\n const avatarUrl = input['avatarUrl']\n if (avatarUrl !== undefined) {\n if (avatarUrl === '') {\n content.avatarUrl = ''\n } else if (!isPublisherAvatarValue(avatarUrl)) {\n return { ok: false, error: `avatarUrl ${LISTING_IMAGE_ERROR}` }\n } else {\n content.avatarUrl = avatarUrl\n }\n }\n const urlKeys = [\n 'website',\n 'supportUrl',\n 'githubUrl',\n 'xUrl',\n 'linkedinUrl',\n ] as const\n for (const key of urlKeys) {\n const value = input[key]\n if (value === undefined) continue\n if (value === '') {\n content[key] = ''\n continue\n }\n // The same https-or-nothing rule as listing URLs: `javascript:`, `data:`\n // and plain http all fail the one test.\n if (typeof value !== 'string' || !HTTPS_URL.test(value) || value.length > 500) {\n return { ok: false, error: `${key} must be an https URL` }\n }\n const hosts = PUBLISHER_SOCIAL_HOSTS[key]\n if (hosts) {\n let host = ''\n try {\n host = new URL(value).hostname.toLowerCase()\n } catch {\n return { ok: false, error: `${key} must be an https URL` }\n }\n if (!hosts.some((allowed) => host === allowed || host.endsWith(`.${allowed}`))) {\n return { ok: false, error: `${key} must link to ${hosts[0]}` }\n }\n }\n content[key] = value\n }\n const supportEmail = input['supportEmail']\n if (supportEmail !== undefined) {\n if (supportEmail === '') {\n content.supportEmail = ''\n } else if (\n typeof supportEmail !== 'string' ||\n supportEmail.length > 200 ||\n !SUPPORT_EMAIL.test(supportEmail)\n ) {\n return { ok: false, error: 'supportEmail must be an email address' }\n } else {\n content.supportEmail = supportEmail\n }\n }\n return { ok: true, content }\n}\n\n/**\n * Render-time guard for publisher links (AGL-1009): only an `https://` URL\n * is ever emitted as an href. The save route already refuses anything else,\n * but the doc is client-updatable on its cosmetic fields historically, so\n * the renderer must not trust stored data it did not write.\n */\nexport function safePublisherHref(url: unknown): string | undefined {\n return typeof url === 'string' && /^https:\\/\\//i.test(url) && url.length <= 500\n ? url\n : undefined\n}\n\n/**\n * The same guard for the publisher's LOGO (AGL-3260), which is an `<img src>`\n * rather than an href and so has a different safe set: the media library's\n * root-relative CDN path is the value the picker produces and must render,\n * and a third-party https URL — fine as a link the reader chooses to follow —\n * is exactly what must not be fetched on their behalf.\n */\nexport function safePublisherImageSrc(src: unknown): string | undefined {\n return isPublisherAvatarValue(src) ? src : undefined\n}\n\n/**\n * Platform revenue share on paid listings (AGL-46) — UI COPY ONLY. The\n * checkout route prices from the `marketplaceFeePct` ENTITLEMENT\n * (`resolveMarketplaceFeePct`, AGL-1543), which resolves the effective\n * plan and per-org overrides; these constants exist for seller-facing\n * copy and must be kept in step with the plan table.\n */\nexport const MARKETPLACE_PLATFORM_FEE_PERCENT = 20\n/** Free-plan publishers pay a higher share. See AGL-1543 note above. */\nexport const MARKETPLACE_PLATFORM_FEE_PERCENT_FREE_PLAN = 30\n/** One-time listing price ceiling (whole USD). */\nexport const MARKETPLACE_MAX_PRICE_USD = 1000\n\n/**\n * One-time listing price FLOOR for a PAID listing (whole USD, AGL-2343).\n *\n * Marketplace checkout is a destination charge with no `application_fee_amount`\n * — deliberately, so the sales tax stays with the platform that owes it\n * (AGL-1544) — which means Stripe debits its fee from the PLATFORM's balance.\n * Stripe's fixed 30¢ dominates at low prices, so under this figure the\n * platform's cut is smaller than the cost of collecting it and every sale is a\n * loss. The floor is the cheapest listing price that still clears the cost of\n * processing it.\n *\n * NOT A CHOSEN NUMBER. `marketplaceMinPriceUsd` derives it from the plan\n * table's lowest take rate and the dearest enabled payment method; this is a\n * re-export so that the routes and the console forms cannot quote different\n * minimums at the same publisher. Zero stays legal — a free listing takes no\n * payment and costs nothing to process.\n */\nexport const MARKETPLACE_MIN_PRICE_USD = marketplaceMinPriceUsd()\n\n/**\n * The refusal message for a listing price, or `undefined` when the price may\n * be published (AGL-2343).\n *\n * ONE VALIDATOR FOR SEVEN DOORS. Each publish route used to inline its own\n * range check against the maximum — and `publish-theme.ts` and\n * `publish-layout.ts` had none at all, so a $250,000 theme was publishable.\n * The doors call this, and `publishPreconditionRefusal` calls it too, so a\n * route that forgets is still covered.\n *\n * Takes the price the route already rounded: a listing price is whole dollars\n * everywhere, and a validator that accepted $2.99 would be validating a number\n * that is never stored.\n */\nexport function marketplacePriceRefusal(priceUsd: number): string | undefined {\n if (!Number.isFinite(priceUsd) || priceUsd < 0) {\n return `Price must be 0 (free) or $${MARKETPLACE_MIN_PRICE_USD}–$${MARKETPLACE_MAX_PRICE_USD} USD`\n }\n if (priceUsd > MARKETPLACE_MAX_PRICE_USD) {\n return `Price must be 0 (free) or $${MARKETPLACE_MIN_PRICE_USD}–$${MARKETPLACE_MAX_PRICE_USD} USD`\n }\n // Zero is not \"below the floor\" — it is the free listing, which takes no\n // payment at all and so costs nothing to process.\n if (priceUsd > 0 && priceUsd < MARKETPLACE_MIN_PRICE_USD) {\n return (\n `A paid listing must be at least $${MARKETPLACE_MIN_PRICE_USD} USD — ` +\n `below that, processing the payment costs more than the platform fee ` +\n `on the sale. Use 0 for a free listing.`\n )\n }\n return undefined\n}\n\n/**\n * The rule a node tree meets before it lands on a canvas that did not author\n * it is core's (`@aglyn/aglyn/app-utils/node-definition-sanitizer`, AGL-2939),\n * under neutral names, because a model-generated tree passes through it too.\n * A publisher reads it as the marketplace's rule, so the marketplace re-exports\n * it under the names its publish routes and its docs use.\n */\nexport {\n PORTABLE_COMPONENT_ID_ALLOWLIST as MARKETPLACE_COMPONENT_ID_ALLOWLIST,\n PORTABLE_EMAIL_COMPONENT_ID_ALLOWLIST as MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n PORTABLE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST as MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n sanitizePortableDefinition as sanitizeMarketplaceDefinition,\n portableDefinitionToNested as marketplaceDefinitionToNested,\n PORTABLE_SAFE_HREF as MARKETPLACE_SAFE_HREF,\n PORTABLE_SAFE_SRC as MARKETPLACE_SAFE_SRC,\n PORTABLE_DEFINITION_MAX_BYTES as MARKETPLACE_DEFINITION_MAX_BYTES,\n type PortableDefinitionNodes as MarketplaceDefinitionNodes,\n} from '@aglyn/aglyn/app-utils/node-definition-sanitizer'\n\n/** One row of the listing detail's `What's included` checklist. */\nexport interface ListingInclusion {\n label: string\n /** Whether the row is a positive inclusion or a stated limit. */\n tone: 'included' | 'note'\n}\n\n/** What each artifact type drops into the org when it installs. */\nconst ARTIFACT_INSTALL_RESULT: Record<MarketplaceArtifactType, string> = {\n plugin: 'A plugin, sandboxed on its own origin with a per-plugin CSP',\n component: 'An editable component you can place on any page',\n template: 'Editable pages you can rework in Besigner',\n layout: 'An editable layout you can apply to any page',\n datasetSchema: 'A new empty dataset with its fields already defined',\n emailTemplate: 'An editable email design you can send campaigns from',\n emailStarter:\n 'A new email in your Email templates list, ready to edit and send',\n theme: 'A theme applied to the site you choose',\n siteStarter: 'A new site, created from these pages and this theme',\n}\n\n/**\n * The `WHAT'S INCLUDED` checklist the marketplace listing mockup shows\n * (AGL-2173), derived entirely from facts the listing already carries.\n *\n * The mockup's own bullets — `12 responsive screens`, `Blog & work\n * layouts` — are publisher-authored prose, and nothing collects them:\n * there is no content manifest on a listing or a version, so counting\n * screens would mean inventing a number. What IS knowable is what the\n * install physically does, where it lands, whether it has been reviewed,\n * and under what licence — which is the question a shopper is asking when\n * they read that box.\n *\n * Ordered decision-first: what you get, then where it goes, then the two\n * facts that most often stop an install.\n */\nexport function listingInclusions(\n listing: {\n artifactType?: string\n type?: string\n kind?: string\n license?: string\n priceUsd?: number\n reviewStatus?: string\n },\n options: { reviewedVersion?: boolean } = {},\n): ListingInclusion[] {\n const type = listingArtifactType(listing)\n const rows: ListingInclusion[] = [\n { label: ARTIFACT_INSTALL_RESULT[type] ?? 'An installable artifact', tone: 'included' },\n ]\n const targets = installTargetsFor(listing)\n rows.push({\n label: targets.includes('org')\n ? 'Installs org-wide, covering sites you add later'\n : 'Installs per site — new sites are not covered automatically',\n // The host-only case is a real limit and the picker already has to say\n // so; softening it here would put the caveat only where nobody reads.\n tone: targets.includes('org') ? 'included' : 'note',\n })\n if (options.reviewedVersion) {\n rows.push({\n label: 'This version passed marketplace review',\n tone: 'included',\n })\n }\n if (listing.license) {\n rows.push({ label: `Licensed ${listing.license}`, tone: 'included' })\n }\n rows.push({\n label: Number(listing.priceUsd ?? 0) > 0\n ? 'A one-time purchase — updates to this listing are included'\n : 'Free, including every future update',\n tone: 'included',\n })\n return rows\n}\n\n/**\n * WHO STILL OWNS WHAT THEY BOUGHT — the one predicate (AGL-2158).\n *\n * `hasLivePurchase` (server/purchase-entitlement.ts) is the gate on all eight\n * ways into paid content, and it reads exactly one field: a purchase with\n * `refundedAt` — stamped by the `charge.refunded` and lost-`charge.dispute`\n * doors of the marketplace billing webhook — no longer entitles.\n *\n * The listing page carried its OWN copy of that question,\n * `some(p => p.listingId === listingId)`, with no refund test at all. The two\n * then disagreed on the one buyer they must not disagree on: the refunded\n * one. The page showed \"Purchased\", hid the buy button, and the install\n * routes answered 402 — a buyer who could neither install nor re-purchase.\n *\n * It lives HERE, in the model, rather than in the server module, because the\n * server module is the wrong side of the client/server boundary for a React\n * component and copying four characters of predicate is precisely how the two\n * came apart. This module is context-free by construction (see the header) —\n * importable from a client component, an API route and another plugin alike.\n */\nexport interface PurchaseLiveness {\n /** Stamped when a full refund or a lost dispute un-buys the listing. */\n refundedAt?: unknown\n listingId?: unknown\n /**\n * THE ORGANIZATION THE LICENCE BELONGS TO (AGL-2331).\n *\n * Absent on every purchase written before AGL-2331 — see\n * `purchaseEntitlesOrg` for what that absence means and why it is never\n * treated as \"no licence\".\n */\n buyerOrgId?: unknown\n /** The person who paid. Kept for the receipt trail and the legacy grant. */\n buyerUid?: unknown\n}\n\n/**\n * True when this purchase document still entitles.\n *\n * Deliberately a truthiness test and not `!= null`: `refundedAt` is a\n * Firestore Timestamp on the server, a client Timestamp in the browser and a\n * sentinel in the webhook's own tests, and every one of those is truthy while\n * a missing field (every purchase written before AGL-1546) is not.\n */\nexport function isLivePurchase(\n purchase: PurchaseLiveness | null | undefined,\n): boolean {\n return Boolean(purchase) && !purchase?.refundedAt\n}\n\n/**\n * True when this buyer's purchase documents include a live one for `listingId`.\n *\n * Both callers pass everything they read — the server's query is already\n * narrowed to the listing, the client's is narrowed only to the buyer — so the\n * listing filter belongs inside the shared predicate too, not beside it.\n */\nexport function hasLivePurchaseOf(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n): boolean {\n if (!listingId) return false\n return (purchases ?? []).some(\n (purchase) =>\n purchase?.listingId === listingId && isLivePurchase(purchase),\n )\n}\n/**\n * WHO A PURCHASE LICENSES (AGL-2331).\n *\n * ## The model\n *\n * **A marketplace purchase licenses an ORGANIZATION, not a person.** That is\n * not a new decision — it is the one already published. The Marketplace\n * Publisher Agreement §8.1 says a paid Artifact is licensed \"to the installing\n * organization\", and §2 grants the right to sublicense \"to organizations that\n * install it\". Until now the code enforced a per-PERSON licence instead, and\n * the mismatch cut both ways: an agency developer who is an owner across five\n * client workspaces bought once and installed into all five, and — because the\n * duplicate-purchase guard shares this predicate — could not buy a second\n * licence even when they wanted to. Conforming the code to the published terms\n * is the smaller of the two changes; the alternative amends a version-pinned\n * legal document and stops every publisher until they re-accept it.\n *\n * Three consequences follow, and all three are the point:\n *\n * 1. A licence held by org A does not install into org B. The agency buys per\n * client workspace, which is what the agreement says they are buying.\n * 2. Buying a second licence is a real second sale, not a `409`.\n * 3. Any member of the owning org with `installPlugins` may install what the\n * ORG bought — including colleagues who were not the buyer, and including\n * the buyer's replacement after they leave. A licence that evaporates when\n * one employee's account is deleted is not an organizational licence.\n *\n * ## The legacy grant, and why it never expires\n *\n * A purchase written before this change carries NO `buyerOrgId` — there was\n * no buyer org anywhere in the pipeline to record. Those are real purchases by\n * real customers, and reinterpreting one as \"licensed to no organization\"\n * would revoke access somebody paid for. So a purchase with no `buyerOrgId` at\n * all keeps its ORIGINAL, person-scoped meaning, forever: it entitles the uid\n * that bought it, in every org that uid can install into. Nothing is\n * migrated, nothing is claimed by the first org to use it, and nothing is\n * revoked — the ambiguity resolves in the customer's favour by construction,\n * with no backfill to get right and no window during which a paying customer\n * is locked out.\n *\n * The grandfather is bounded by time rather than policed: it can only ever\n * apply to purchases already written, because from AGL-2331 onward checkout\n * refuses to open a session that does not name a validated buyer org. It is\n * therefore a shrinking set that never grows, not a hole left open.\n *\n * `orgId` may be empty (a site with no owning org). That is not a licence to\n * anything, so only the legacy uid grant can hold — never a `buyerOrgId ===\n * ''` match, which is why the org branch tests for a non-empty string on the\n * document itself rather than comparing the two values directly.\n */\nexport function purchaseEntitlesOrg(\n purchase: PurchaseLiveness | null | undefined,\n actor: { orgId?: string | null; uid?: string | null },\n): boolean {\n if (!isLivePurchase(purchase)) return false\n const purchaseOrgId = purchase?.buyerOrgId\n if (typeof purchaseOrgId === 'string' && purchaseOrgId) {\n return Boolean(actor.orgId) && purchaseOrgId === actor.orgId\n }\n // Legacy: no buyer org was ever recorded, so it means what it meant when it\n // was sold. Never revoked, never migrated.\n return Boolean(actor.uid) && purchase?.buyerUid === actor.uid\n}\n\n/**\n * True when these purchase documents include one that licenses `orgId` for\n * `listingId` — the org-scoped counterpart of `hasLivePurchaseOf`.\n *\n * Same shape and same home as the liveness predicate, and for the same reason\n * (AGL-2158): the install routes, the checkout duplicate guard and the listing\n * page all have to answer \"does this workspace hold a licence\" identically, and\n * the way they came apart last time was four characters of predicate copied\n * into a component.\n */\nexport function hasOrgLicenceOf(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n actor: { orgId?: string | null; uid?: string | null },\n): boolean {\n if (!listingId) return false\n return (purchases ?? []).some(\n (purchase) =>\n purchase?.listingId === listingId && purchaseEntitlesOrg(purchase, actor),\n )\n}\n\n/**\n * Every org id these purchases license for `listingId`, in document order.\n *\n * What the console renders so a buyer can see WHICH workspace a licence they\n * paid for belongs to (AGL-2331) — the question that has no answer at all\n * while entitlement is person-scoped, and the one an agency has to answer\n * before deciding whether it needs another.\n *\n * Legacy person-scoped purchases contribute no org id, because they name\n * none; a caller rendering this list has to say so rather than invent one.\n */\nexport function licensedOrgIdsFor(\n purchases: readonly (PurchaseLiveness | null | undefined)[] | null | undefined,\n listingId: string,\n): string[] {\n const seen: string[] = []\n for (const purchase of purchases ?? []) {\n if (purchase?.listingId !== listingId || !isLivePurchase(purchase)) continue\n const orgId = purchase?.buyerOrgId\n if (typeof orgId === 'string' && orgId && !seen.includes(orgId)) {\n seen.push(orgId)\n }\n }\n return seen\n}\n\n"],"names":["isFirstPartyMediaSrc","MEDIA_REF_PREFIX","marketplaceMinPriceUsd","landsInPublisherWorkspace","offeredPluginVersion","isListingBrowsable","isListingDeleted","isPrivateListing","LISTING_CLIENT_WRITABLE_FIELDS","LISTING_UNPERSISTED_FIELDS","listingArtifactType","PUBLISHER_HANDLE_PATTERN","isValidPublisherHandle","handle","test","ARTIFACT_TYPE_LABELS","INSTALL_TARGETS","LISTING_CATEGORIES","resolveOrgInstallSummary","resolvePluginInstallState","resolveUninstallTargets","listingArtifactLabel","listing","installTargetsFor","resolveInstallPlan","targeting","hosts","targets","canOrgPin","includes","canHostPin","scope","allHostIds","map","hostId","selectedHostIds","VERIFICATION_BLOCK_MESSAGES","VERIFICATION_DECLINE_COOLDOWN_DAYS","timestampMs","verificationRequestBlock","isVersionApproved","version","reviewState","installsUnreviewedFallback","viewerOrgId","revocation","profileId","Boolean","String","latestVersion","newestApprovedVersion","versions","approved","filter","entry","length","reduce","best","publishedAt","toMillis","missingPublicListingContent","missing","description","trim","push","readme","license","LISTING_README_MAX_CHARS","LISTING_MAX_SCREENSHOTS","HTTPS_URL","LISTING_IMAGE_ERROR","LISTING_URL_MAX_CHARS","isListingImageValue","value","isPublisherAvatarValue","startsWith","validateListingContent","input","content","key","undefined","ok","error","logoUrl","screenshots","Array","isArray","some","url","categories","PUBLISHER_SOCIAL_HOSTS","githubUrl","xUrl","linkedinUrl","SUPPORT_EMAIL","validatePublisherProfileContent","avatarUrl","urlKeys","host","URL","hostname","toLowerCase","allowed","endsWith","supportEmail","safePublisherHref","safePublisherImageSrc","src","MARKETPLACE_PLATFORM_FEE_PERCENT","MARKETPLACE_PLATFORM_FEE_PERCENT_FREE_PLAN","MARKETPLACE_MAX_PRICE_USD","MARKETPLACE_MIN_PRICE_USD","marketplacePriceRefusal","priceUsd","Number","isFinite","PORTABLE_COMPONENT_ID_ALLOWLIST","MARKETPLACE_COMPONENT_ID_ALLOWLIST","PORTABLE_EMAIL_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","PORTABLE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","sanitizePortableDefinition","sanitizeMarketplaceDefinition","portableDefinitionToNested","marketplaceDefinitionToNested","PORTABLE_SAFE_HREF","MARKETPLACE_SAFE_HREF","PORTABLE_SAFE_SRC","MARKETPLACE_SAFE_SRC","PORTABLE_DEFINITION_MAX_BYTES","MARKETPLACE_DEFINITION_MAX_BYTES","ARTIFACT_INSTALL_RESULT","plugin","component","template","layout","datasetSchema","emailTemplate","emailStarter","theme","siteStarter","listingInclusions","options","type","rows","label","tone","reviewedVersion","isLivePurchase","purchase","refundedAt","hasLivePurchaseOf","purchases","listingId","purchaseEntitlesOrg","actor","purchaseOrgId","buyerOrgId","orgId","uid","buyerUid","hasOrgLicenceOf","licensedOrgIdsFor","seen"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;CAIC,GAED,6EAA6E;AAC7E,2EAA2E;AAC3E,8EAA8E;AAC9E,8EAA8E;AAC9E,SACEA,oBAAoB,EACpBC,gBAAgB,QACX,mCAAkC;AACzC,SAASC,sBAAsB,QAAQ,2BAAuB;AAC9D,SAASC,yBAAyB,QAAQ,mBAAe;AAGzD,SACEC,oBAAoB,QAEf,yCAAwC;AAC/C,4EAA4E;AAC5E,6EAA6E;AAC7E,0EAA0E;AAC1E,0EAA0E;AAC1E,2EAA2E;AAC3E,4EAA4E;AAC5E,2EAA2E;AAC3E,qDAAqD;AACrD,SACEC,kBAAkB,EAClBC,gBAAgB,EAChBC,gBAAgB,EAChBC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,mBAAmB,QACd,0BAAsB;AAE7B,SACEL,kBAAkB,EAClBC,gBAAgB,EAChBC,gBAAgB,EAChBC,8BAA8B,EAC9BC,0BAA0B,EAC1BC,mBAAmB,KACpB;AA4DD;;;;;CAKC,GACD,OAAO,MAAMC,2BAA2B,oCAAmC;AAE3E,OAAO,SAASC,uBAAuBC,MAAc;IACnD,OAAOF,yBAAyBG,IAAI,CAACD;AACvC;AAwKA,SACEE,oBAAoB,EACpBC,eAAe,EAGfC,kBAAkB,EAIlBC,wBAAwB,EACxBC,yBAAyB,EACzBC,uBAAuB,QAElB,2BAAuB;AAC9B,SAASL,oBAAoB,EAAEC,eAAe,EAAuCC,kBAAkB,QAAQ,2BAAuB;AAEt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SAASO,kBACdV,SAA8E,EAC9EC,SAAiB;IAEjB,MAAMU,OAAiB,EAAE;IACzB,KAAK,MAAMd,YAAYG,oBAAAA,YAAa,EAAE,CAAE;QACtC,IAAIH,CAAAA,4BAAAA,SAAUI,SAAS,MAAKA,aAAa,CAACL,eAAeC,WAAW;QACpE,MAAMS,QAAQT,4BAAAA,SAAUQ,UAAU;QAClC,IAAI,OAAOC,UAAU,YAAYA,SAAS,CAACK,KAAKvI,QAAQ,CAACkI,QAAQ;YAC/DK,KAAKpG,IAAI,CAAC+F;QACZ;IACF;IACA,OAAOK;AACT"}
@@ -0,0 +1,52 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /**
18
+ * Whether an install lands in the workspace that publishes the listing.
19
+ *
20
+ * `publisherOrgId` is the listing's `profileId` (listings are org-owned,
21
+ * AGL-652). `targetOrgId` is the workspace the install lands in, resolved
22
+ * server-side from the site, never from a request body. A listing with no
23
+ * publisher is nobody's, so it lands in nobody's workspace.
24
+ */
25
+ export declare function landsInPublisherWorkspace(publisherOrgId: unknown, targetOrgId: unknown): boolean;
26
+ /**
27
+ * The own-listing waiver: a member of the publishing workspace, installing
28
+ * into that workspace. It waives the payment, and lets the publisher install
29
+ * its own private listing (and, for plugins and starters, a version still
30
+ * in review). Anything else is an install by a buyer.
31
+ */
32
+ export declare function isOwnListingInstall(facts: {
33
+ publisherOrgId: unknown;
34
+ targetOrgId: unknown;
35
+ /** `isPublisherMember` for the person asking, in the publishing workspace. */
36
+ publisherMember: boolean;
37
+ }): boolean;
38
+ /**
39
+ * A member of the publishing workspace, buying for any other workspace: the
40
+ * sale refuses them whichever workspace it is for (`server/sale.ts`, AGL-3365),
41
+ * so the console switches Buy off for them rather than let them find out
42
+ * afterward. On the publisher's own sites there is nothing to buy: the waiver
43
+ * above makes it free, so this is false there.
44
+ */
45
+ export declare function isPublisherMemberElsewhere(facts: {
46
+ publisherOrgId: unknown;
47
+ targetOrgId: unknown;
48
+ /** `isPublisherMember` for the person asking, in the publishing workspace. */
49
+ publisherMember: boolean;
50
+ }): boolean;
51
+ /** Why Buy is off for a member of the publishing workspace, in one sentence. */
52
+ export declare function publisherMemberBuyReason(publisherName: unknown): string;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /**
17
+ * A publisher's own listing, on its own sites (AGL-2484, AGL-4047).
18
+ *
19
+ * The members of the workspace that publishes a listing install it free on
20
+ * that workspace's own sites, for every listing type, and only there. The
21
+ * same people installing it into another workspace are buyers in that
22
+ * workspace like anyone else: it needs a licence there, or a purchase.
23
+ *
24
+ * Two facts make the waiver, and both are needed:
25
+ *
26
+ * - the person belongs to the publishing workspace (a fact about who
27
+ * published it, read by `isPublisherMember`, never a permission); and
28
+ * - the install lands in that same workspace.
29
+ *
30
+ * Plugins and site starters have asked both since AGL-2484. The other
31
+ * install doors asked only the first, so a member could put the
32
+ * workspace's paid listing on a client's site for free. Every door now
33
+ * decides through this one definition (`server/own-listing.ts`), and the
34
+ * console asks the same "lands in the publisher's workspace" half before it
35
+ * offers an install without a purchase.
36
+ *
37
+ * Context-free: no Firestore, so the console can ask it too.
38
+ */ /** A workspace id as stored, or the empty string for anything else. */ const workspaceIdOf = (value)=>typeof value === 'string' ? value : '';
39
+ /**
40
+ * Whether an install lands in the workspace that publishes the listing.
41
+ *
42
+ * `publisherOrgId` is the listing's `profileId` (listings are org-owned,
43
+ * AGL-652). `targetOrgId` is the workspace the install lands in, resolved
44
+ * server-side from the site, never from a request body. A listing with no
45
+ * publisher is nobody's, so it lands in nobody's workspace.
46
+ */ export function landsInPublisherWorkspace(publisherOrgId, targetOrgId) {
47
+ const publisher = workspaceIdOf(publisherOrgId);
48
+ return publisher !== '' && workspaceIdOf(targetOrgId) === publisher;
49
+ }
50
+ /**
51
+ * The own-listing waiver: a member of the publishing workspace, installing
52
+ * into that workspace. It waives the payment, and lets the publisher install
53
+ * its own private listing (and, for plugins and starters, a version still
54
+ * in review). Anything else is an install by a buyer.
55
+ */ export function isOwnListingInstall(facts) {
56
+ return facts.publisherMember === true && landsInPublisherWorkspace(facts.publisherOrgId, facts.targetOrgId);
57
+ }
58
+ /**
59
+ * A member of the publishing workspace, buying for any other workspace: the
60
+ * sale refuses them whichever workspace it is for (`server/sale.ts`, AGL-3365),
61
+ * so the console switches Buy off for them rather than let them find out
62
+ * afterward. On the publisher's own sites there is nothing to buy: the waiver
63
+ * above makes it free, so this is false there.
64
+ */ export function isPublisherMemberElsewhere(facts) {
65
+ return facts.publisherMember === true && !landsInPublisherWorkspace(facts.publisherOrgId, facts.targetOrgId);
66
+ }
67
+ /** Why Buy is off for a member of the publishing workspace, in one sentence. */ export function publisherMemberBuyReason(publisherName) {
68
+ const name = typeof publisherName === 'string' ? publisherName.trim() : '';
69
+ return `Someone in this workspace who isn't in ${name || 'the publishing workspace'} needs to buy it.`;
70
+ }
71
+
72
+ //# sourceMappingURL=own-listing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/own-listing.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 * A publisher's own listing, on its own sites (AGL-2484, AGL-4047).\n *\n * The members of the workspace that publishes a listing install it free on\n * that workspace's own sites, for every listing type, and only there. The\n * same people installing it into another workspace are buyers in that\n * workspace like anyone else: it needs a licence there, or a purchase.\n *\n * Two facts make the waiver, and both are needed:\n *\n * - the person belongs to the publishing workspace (a fact about who\n * published it, read by `isPublisherMember`, never a permission); and\n * - the install lands in that same workspace.\n *\n * Plugins and site starters have asked both since AGL-2484. The other\n * install doors asked only the first, so a member could put the\n * workspace's paid listing on a client's site for free. Every door now\n * decides through this one definition (`server/own-listing.ts`), and the\n * console asks the same \"lands in the publisher's workspace\" half before it\n * offers an install without a purchase.\n *\n * Context-free: no Firestore, so the console can ask it too.\n */\n\n/** A workspace id as stored, or the empty string for anything else. */\nconst workspaceIdOf = (value: unknown): string =>\n typeof value === 'string' ? value : ''\n\n/**\n * Whether an install lands in the workspace that publishes the listing.\n *\n * `publisherOrgId` is the listing's `profileId` (listings are org-owned,\n * AGL-652). `targetOrgId` is the workspace the install lands in, resolved\n * server-side from the site, never from a request body. A listing with no\n * publisher is nobody's, so it lands in nobody's workspace.\n */\nexport function landsInPublisherWorkspace(\n publisherOrgId: unknown,\n targetOrgId: unknown,\n): boolean {\n const publisher = workspaceIdOf(publisherOrgId)\n return publisher !== '' && workspaceIdOf(targetOrgId) === publisher\n}\n\n/**\n * The own-listing waiver: a member of the publishing workspace, installing\n * into that workspace. It waives the payment, and lets the publisher install\n * its own private listing (and, for plugins and starters, a version still\n * in review). Anything else is an install by a buyer.\n */\nexport function isOwnListingInstall(facts: {\n publisherOrgId: unknown\n targetOrgId: unknown\n /** `isPublisherMember` for the person asking, in the publishing workspace. */\n publisherMember: boolean\n}): boolean {\n return (\n facts.publisherMember === true &&\n landsInPublisherWorkspace(facts.publisherOrgId, facts.targetOrgId)\n )\n}\n\n/**\n * A member of the publishing workspace, buying for any other workspace: the\n * sale refuses them whichever workspace it is for (`server/sale.ts`, AGL-3365),\n * so the console switches Buy off for them rather than let them find out\n * afterward. On the publisher's own sites there is nothing to buy: the waiver\n * above makes it free, so this is false there.\n */\nexport function isPublisherMemberElsewhere(facts: {\n publisherOrgId: unknown\n targetOrgId: unknown\n /** `isPublisherMember` for the person asking, in the publishing workspace. */\n publisherMember: boolean\n}): boolean {\n return (\n facts.publisherMember === true &&\n !landsInPublisherWorkspace(facts.publisherOrgId, facts.targetOrgId)\n )\n}\n\n/** Why Buy is off for a member of the publishing workspace, in one sentence. */\nexport function publisherMemberBuyReason(publisherName: unknown): string {\n const name = typeof publisherName === 'string' ? publisherName.trim() : ''\n return `Someone in this workspace who isn't in ${name || 'the publishing workspace'} needs to buy it.`\n}\n"],"names":["workspaceIdOf","value","landsInPublisherWorkspace","publisherOrgId","targetOrgId","publisher","isOwnListingInstall","facts","publisherMember","isPublisherMemberElsewhere","publisherMemberBuyReason","publisherName","name","trim"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,qEAAqE,GACrE,MAAMA,gBAAgB,CAACC,QACrB,OAAOA,UAAU,WAAWA,QAAQ;AAEtC;;;;;;;CAOC,GACD,OAAO,SAASC,0BACdC,cAAuB,EACvBC,WAAoB;IAEpB,MAAMC,YAAYL,cAAcG;IAChC,OAAOE,cAAc,MAAML,cAAcI,iBAAiBC;AAC5D;AAEA;;;;;CAKC,GACD,OAAO,SAASC,oBAAoBC,KAKnC;IACC,OACEA,MAAMC,eAAe,KAAK,QAC1BN,0BAA0BK,MAAMJ,cAAc,EAAEI,MAAMH,WAAW;AAErE;AAEA;;;;;;CAMC,GACD,OAAO,SAASK,2BAA2BF,KAK1C;IACC,OACEA,MAAMC,eAAe,KAAK,QAC1B,CAACN,0BAA0BK,MAAMJ,cAAc,EAAEI,MAAMH,WAAW;AAEtE;AAEA,8EAA8E,GAC9E,OAAO,SAASM,yBAAyBC,aAAsB;IAC7D,MAAMC,OAAO,OAAOD,kBAAkB,WAAWA,cAAcE,IAAI,KAAK;IACxE,OAAO,CAAC,uCAAuC,EAAED,QAAQ,2BAA2B,iBAAiB,CAAC;AACxG"}
@@ -155,6 +155,8 @@ const idOrNull = (value)=>typeof value === 'string' && value.trim() ? value.trim
155
155
  category: idOrNull(value['category'])
156
156
  }, typeof value['owned'] === 'boolean' ? {
157
157
  owned: value['owned']
158
+ } : {}, typeof value['buyBlockedReason'] === 'string' && value['buyBlockedReason'] ? {
159
+ buyBlockedReason: value['buyBlockedReason']
158
160
  } : {});
159
161
  }
160
162
  /** A map of id to name, keeping only string names under non-empty ids. */ const namesOf = (value)=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/starter-query.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { isSiteStyleId, siteStyleOf } from '@aglyn/aglyn/app-utils/site-styles'\nimport type {\n SiteStarterFacets,\n SiteStarterMode,\n} from '@aglyn/aglyn/app-utils/site-starter'\nimport type { SiteStarterSummary } from '@aglyn/aglyn/plugin-manager/plugin-site-starters'\nimport {\n SITE_STARTER_KNOWN_IDS,\n SITE_STARTER_SEARCH_MAX,\n siteStarterSearchLimit,\n} from './site-starter-listing'\n\n/**\n * The starter search as a request and an answer (AGL-4049): what \"Choose\n * your starter\" asks `GET /api/marketplace/starters`, how the route reads the\n * question back, and how a card words what it shows.\n *\n * Pure and dependency-light on purpose, so the native apps mirror it line for\n * line (phase 5's `StarterQuery`): the same parameters in the same order, the\n * same defensive read of the answer, the same \"Free\" and \"$12\".\n */\n\n/** Where the console asks. */\nexport const STARTER_SEARCH_PATH = '/api/marketplace/starters'\n\n/** The longest search a request carries; the rest is dropped, not refused. */\nexport const STARTER_SEARCH_WORD_MAX = 200\n\n/** The facets a search may narrow to by query parameter, in the order they are written. */\nexport const STARTER_FILTER_KEYS = ['kind', 'base', 'fonts'] as const\nexport type StarterFilterKey = (typeof STARTER_FILTER_KEYS)[number]\n\n/** The names the cards and the filters show for the ids a starter carries. */\nexport interface StarterSearchLabels {\n /** A built-in theme's short name (`material3`) to the name the theme picker shows. */\n base: Record<string, string>\n /** A font pairing id to its families, as a person reads them. */\n fonts: Record<string, string>\n}\n\n/** What the route answers: the starters as summaries, and the names for their ids. */\nexport interface StarterSearchAnswer {\n rows: SiteStarterSummary[]\n labels: StarterSearchLabels\n}\n\n/** One search, as the console and the native apps build it. */\nexport interface StarterQueryInput {\n /** The workspace the site will belong to. */\n orgId: string\n /** How the site will be filled: its pages as they are, or by the AI site start. */\n mode: SiteStarterMode\n /** The person's words, as typed. */\n word?: string\n /** The facets the person narrowed to; an absent one is any. */\n filter?: Partial<SiteStarterFacets>\n /** At most this many; the route caps it. */\n limit?: number\n /**\n * A listing the answer must carry whatever the search finds (AGL-4049):\n * the person's own pick, restored on the way back from buying it, which a\n * search for other words or another mode would not list.\n */\n include?: string | null\n}\n\n/** One search, as the route reads it back, every part checked. */\nexport interface StarterQuery {\n orgId: string\n mode: SiteStarterMode\n word: string\n /** `mode` is always among them, so the source asks for that mode only. */\n filter: Partial<SiteStarterFacets>\n limit: number\n /** The listing to carry whatever the search finds, or `null`. */\n include: string | null\n}\n\nconst ORG_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst LISTING_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst FACET_ID = /^[a-z0-9][a-z0-9-]{0,63}$/\n\nconst trimmed = (value: unknown): string =>\n typeof value === 'string' ? value.trim() : ''\n\n/**\n * The query string for one search, its parameters always in one order —\n * `orgId`, `mode`, `q`, `kind`, `base`, `fonts`, `limit`, `include` — so the\n * same search is the same URL, and a hook can key a request on it.\n */\nexport function starterQueryParams(input: StarterQueryInput): URLSearchParams {\n const params = new URLSearchParams()\n params.set('orgId', trimmed(input.orgId))\n params.set('mode', input.mode === 'ai' ? 'ai' : 'base')\n const word = trimmed(input.word).slice(0, STARTER_SEARCH_WORD_MAX)\n if (word) params.set('q', word)\n for (const key of STARTER_FILTER_KEYS) {\n const value = trimmed(input.filter?.[key])\n if (value) params.set(key, value)\n }\n params.set(\n 'limit',\n String(siteStarterSearchLimit(input.limit ?? SITE_STARTER_SEARCH_MAX) || SITE_STARTER_SEARCH_MAX),\n )\n const include = trimmed(input.include)\n if (LISTING_ID.test(include)) params.set('include', include)\n return params\n}\n\n/**\n * The route's reading of a search, or the refusal it answers with a 400.\n *\n * A base theme or a font pairing is checked against the lists a starter may\n * name (`SITE_STARTER_KNOWN_IDS`), and a kind against the styles a person\n * chooses among (core's `SITE_STYLES`, which are the kinds of site), so a\n * mistyped one is named rather than answered with nothing.\n */\nexport function starterQueryFrom(\n params: URLSearchParams,\n): StarterQuery | { error: string } {\n const orgId = trimmed(params.get('orgId'))\n if (!ORG_ID.test(orgId)) return { error: 'Missing orgId' }\n const askedMode = trimmed(params.get('mode'))\n if (askedMode && askedMode !== 'base' && askedMode !== 'ai') {\n return { error: 'Unknown mode' }\n }\n const mode: SiteStarterMode = askedMode === 'ai' ? 'ai' : 'base'\n const filter: Partial<SiteStarterFacets> = { mode }\n const kind = trimmed(params.get('kind'))\n if (kind) {\n if (!FACET_ID.test(kind) || !isSiteStyleId(kind)) return { error: 'Unknown kind of site' }\n filter.kind = kind\n }\n const base = trimmed(params.get('base'))\n if (base) {\n if (!SITE_STARTER_KNOWN_IDS.bases?.has(base)) return { error: 'Unknown base theme' }\n filter.base = base\n }\n const fonts = trimmed(params.get('fonts'))\n if (fonts) {\n if (!SITE_STARTER_KNOWN_IDS.fonts?.has(fonts)) return { error: 'Unknown font pairing' }\n filter.fonts = fonts\n }\n const include = trimmed(params.get('include'))\n if (include && !LISTING_ID.test(include)) return { error: 'Unknown starter' }\n return {\n orgId,\n mode,\n word: trimmed(params.get('q')).slice(0, STARTER_SEARCH_WORD_MAX),\n filter,\n limit: siteStarterSearchLimit(params.get('limit')) || SITE_STARTER_SEARCH_MAX,\n include: include || null,\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\nconst textOr = (value: unknown, fallback: string): string =>\n typeof value === 'string' ? value : fallback\n\nconst idOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\n\n/**\n * One starter as a card shows it, read field by field, or `null` for a row\n * with no listing id.\n *\n * The route answers each row through this, as the console and the apps read\n * it, so what leaves the server is a summary and nothing else: a source that\n * handed back a paid AI starter's answers, or its pages, would have them\n * dropped here. Each field falls back the way a card needs it to: a missing\n * price is free, a missing picture is none, a page count is a whole number\n * from zero, a mode is `base` unless it says `ai`, and `owned` is kept only\n * where the answer gave it as a yes or a no.\n */\nexport function readStarterSummary(value: unknown): SiteStarterSummary | null {\n if (!isRecord(value)) return null\n const listingId = idOrNull(value['listingId'])\n if (!listingId) return null\n const price = Number(value['priceUsd'])\n const facets = isRecord(value['facets']) ? value['facets'] : {}\n const pages = Number(facets['pages'])\n const preview = value['previewImageUrl']\n return {\n listingId,\n displayName: textOr(value['displayName'], ''),\n description: textOr(value['description'], ''),\n authorName: textOr(value['authorName'], ''),\n official: value['official'] === true,\n priceUsd: Number.isFinite(price) && price > 0 ? price : 0,\n previewImageUrl: typeof preview === 'string' && preview ? preview : null,\n facets: {\n kind: idOrNull(facets['kind']),\n base: idOrNull(facets['base']),\n fonts: idOrNull(facets['fonts']),\n pages: Number.isFinite(pages) && pages > 0 ? Math.floor(pages) : 0,\n mode: facets['mode'] === 'ai' ? 'ai' : 'base',\n },\n category: idOrNull(value['category']),\n // Only where the answer says: absent is \"the search does not know\".\n ...(typeof value['owned'] === 'boolean' ? { owned: value['owned'] } : {}),\n }\n}\n\n/** A map of id to name, keeping only string names under non-empty ids. */\nconst namesOf = (value: unknown): Record<string, string> => {\n if (!isRecord(value)) return {}\n const names: Record<string, string> = {}\n for (const [id, name] of Object.entries(value)) {\n if (id && typeof name === 'string' && name) names[id] = name\n }\n return names\n}\n\n/**\n * The route's answer, read defensively: rows that are not starters are\n * dropped, as is a duplicate of a listing already read, and missing labels\n * are empty. Never throws, whatever it is handed.\n */\nexport function parseStarterSearchAnswer(json: unknown): StarterSearchAnswer {\n const body = isRecord(json) ? json : {}\n const seen = new Set<string>()\n const rows: SiteStarterSummary[] = []\n for (const value of Array.isArray(body['rows']) ? body['rows'] : []) {\n const row = readStarterSummary(value)\n if (!row || seen.has(row.listingId)) continue\n seen.add(row.listingId)\n rows.push(row)\n }\n const labels = isRecord(body['labels']) ? body['labels'] : {}\n return { rows, labels: { base: namesOf(labels['base']), fonts: namesOf(labels['fonts']) } }\n}\n\n/**\n * A starter's price as a card shows it: \"Free\" at zero, whole dollars as\n * \"$12\", and cents only where there are some (\"$12.50\").\n */\nexport function starterPriceLabel(usd: number): string {\n if (!Number.isFinite(usd) || usd <= 0) return 'Free'\n return Number.isInteger(usd) ? `$${usd}` : `$${usd.toFixed(2)}`\n}\n\n/** How many pages a starter creates, as a card says it, or `null` when it does not say. */\nexport function starterPagesLabel(pages: number): string | null {\n if (!Number.isFinite(pages) || pages < 1) return null\n const whole = Math.floor(pages)\n return whole === 1 ? '1 page' : `${whole} pages`\n}\n\n/** One fact a starter's card shows as a chip, keyed so a surface can style each kind its own way. */\nexport interface StarterCardFact {\n key: 'price' | 'official' | 'ai' | 'kind' | 'pages'\n label: string\n}\n\n/**\n * The chips on a starter's card, in the order they are read: the price,\n * every card carrying one (\"Free\" included, so a missing chip never reads as\n * a forgotten price); the platform's name for its own; \"AI\" for a starter the\n * AI site start fills; the kind of site in words; and its page count.\n *\n * The kind is the style's own name for the listing's kind of site (core's\n * `SITE_STYLES`), the same words the kind filters show — never the listing's\n * marketplace category, which for a starter that names no kind is a shelf\n * of the marketplace (`design`), not a kind of site.\n */\nexport function starterCardFacts(row: SiteStarterSummary): StarterCardFact[] {\n const facts: StarterCardFact[] = [{ key: 'price', label: starterPriceLabel(row.priceUsd) }]\n if (row.official) facts.push({ key: 'official', label: PLATFORM_BRAND_NAME })\n if (row.facets.mode === 'ai') facts.push({ key: 'ai', label: 'AI' })\n const kind = siteStyleOf(row.facets.kind)?.name\n if (kind) facts.push({ key: 'kind', label: kind })\n const pages = starterPagesLabel(row.facets.pages)\n if (pages) facts.push({ key: 'pages', label: pages })\n return facts\n}\n\n// ── An AI starter's answers (AGL-4049 phase 4) ─────────────────────────────\n\n/** Where the console reads the answers an AI starter carries. */\nexport const STARTER_ANSWERS_PATH = '/api/marketplace/starters/answers'\n\n/** One AI starter's answers, asked for a workspace. */\nexport interface StarterAnswersQuery {\n orgId: string\n listingId: string\n}\n\n/** What the route answers: the starter's answers, and its facets. */\nexport interface StarterAnswersAnswer {\n answers: Record<string, unknown>\n facets: SiteStarterFacets\n}\n\n/** The query string for one starter's answers, `orgId` then `listingId`. */\nexport function starterAnswersParams(input: StarterAnswersQuery): URLSearchParams {\n const params = new URLSearchParams()\n params.set('orgId', trimmed(input.orgId))\n params.set('listingId', trimmed(input.listingId))\n return params\n}\n\n/**\n * The route's reading of the question, or the refusal a 400 answers with:\n * the workspace, and a listing id as a listing may have one, since it\n * becomes a document path on the way to the listing.\n */\nexport function starterAnswersQueryFrom(params: URLSearchParams): StarterAnswersQuery | { error: string } {\n const orgId = trimmed(params.get('orgId'))\n if (!ORG_ID.test(orgId)) return { error: 'Missing orgId' }\n const listingId = trimmed(params.get('listingId'))\n if (!LISTING_ID.test(listingId)) return { error: 'Unknown starter' }\n return { orgId, listingId }\n}\n\n/**\n * The route's answer, read defensively: the answers as a plain object, and\n * the facets as a summary reads them; `null` for anything without answers.\n */\nexport function readStarterAnswersAnswer(json: unknown): StarterAnswersAnswer | null {\n if (!isRecord(json) || !isRecord(json['answers'])) return null\n const facets = readStarterSummary({ listingId: 'answers', facets: json['facets'] })?.facets\n if (!facets) return null\n return { answers: json['answers'], facets }\n}\n\n/**\n * The one place other than the marketplace a purchase may send its buyer\n * back to (AGL-4049): Create site, reopened on the starter they picked. A\n * name the checkout turns into an address itself, never an address the\n * browser hands it.\n */\nexport const STARTER_CHECKOUT_RETURN = 'create-site'\nexport type StarterCheckoutReturn = typeof STARTER_CHECKOUT_RETURN\n\n/**\n * A checkout body's `return`, read: `create-site`, `null` when it names none\n * (the marketplace, as always), or the refusal a 400 answers with.\n */\nexport function readStarterCheckoutReturn(value: unknown): StarterCheckoutReturn | null | { error: string } {\n if (value === undefined || value === null || value === '') return null\n return value === STARTER_CHECKOUT_RETURN ? STARTER_CHECKOUT_RETURN : { error: 'Unknown return' }\n}\n"],"names":["PLATFORM_BRAND_NAME","isSiteStyleId","siteStyleOf","SITE_STARTER_KNOWN_IDS","SITE_STARTER_SEARCH_MAX","siteStarterSearchLimit","STARTER_SEARCH_PATH","STARTER_SEARCH_WORD_MAX","STARTER_FILTER_KEYS","ORG_ID","LISTING_ID","FACET_ID","trimmed","value","trim","starterQueryParams","input","params","URLSearchParams","set","orgId","mode","word","slice","key","filter","String","limit","include","test","starterQueryFrom","get","error","askedMode","kind","base","bases","has","fonts","isRecord","Array","isArray","textOr","fallback","idOrNull","readStarterSummary","listingId","price","Number","facets","pages","preview","displayName","description","authorName","official","priceUsd","isFinite","previewImageUrl","Math","floor","category","owned","namesOf","names","id","name","Object","entries","parseStarterSearchAnswer","json","body","seen","Set","rows","row","add","push","labels","starterPriceLabel","usd","isInteger","toFixed","starterPagesLabel","whole","starterCardFacts","facts","label","STARTER_ANSWERS_PATH","starterAnswersParams","starterAnswersQueryFrom","readStarterAnswersAnswer","answers","STARTER_CHECKOUT_RETURN","readStarterCheckoutReturn","undefined"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,aAAa,EAAEC,WAAW,QAAQ,qCAAoC;AAM/E,SACEC,sBAAsB,EACtBC,uBAAuB,EACvBC,sBAAsB,QACjB,4BAAwB;AAE/B;;;;;;;;CAQC,GAED,4BAA4B,GAC5B,OAAO,MAAMC,sBAAsB,4BAA2B;AAE9D,4EAA4E,GAC5E,OAAO,MAAMC,0BAA0B,IAAG;AAE1C,yFAAyF,GACzF,OAAO,MAAMC,sBAAsB;IAAC;IAAQ;IAAQ;CAAQ,CAAS;AAiDrE,MAAMC,SAAS;AACf,MAAMC,aAAa;AACnB,MAAMC,WAAW;AAEjB,MAAMC,UAAU,CAACC,QACf,OAAOA,UAAU,WAAWA,MAAMC,IAAI,KAAK;AAE7C;;;;CAIC,GACD,OAAO,SAASC,mBAAmBC,KAAwB;QAYzBA;IAXhC,MAAMC,SAAS,IAAIC;IACnBD,OAAOE,GAAG,CAAC,SAASP,QAAQI,MAAMI,KAAK;IACvCH,OAAOE,GAAG,CAAC,QAAQH,MAAMK,IAAI,KAAK,OAAO,OAAO;IAChD,MAAMC,OAAOV,QAAQI,MAAMM,IAAI,EAAEC,KAAK,CAAC,GAAGhB;IAC1C,IAAIe,MAAML,OAAOE,GAAG,CAAC,KAAKG;IAC1B,KAAK,MAAME,OAAOhB,oBAAqB;YACfQ;QAAtB,MAAMH,QAAQD,SAAQI,gBAAAA,MAAMS,MAAM,qBAAZT,aAAc,CAAC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;;CAGC,GACD,OAAO,SAASC,0BAA0BjF,KAAc;IACtD,IAAIA,UAAUkF,aAAalF,UAAU,QAAQA,UAAU,IAAI,OAAO;IAClE,OAAOA,UAAUgF,0BAA0BA,0BAA0B;QAAE7D,OAAO;IAAiB;AACjG"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/starter-query.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\nimport { isSiteStyleId, siteStyleOf } from '@aglyn/aglyn/app-utils/site-styles'\nimport type {\n SiteStarterFacets,\n SiteStarterMode,\n} from '@aglyn/aglyn/app-utils/site-starter'\nimport type { SiteStarterSummary } from '@aglyn/aglyn/plugin-manager/plugin-site-starters'\nimport {\n SITE_STARTER_KNOWN_IDS,\n SITE_STARTER_SEARCH_MAX,\n siteStarterSearchLimit,\n} from './site-starter-listing'\n\n/**\n * The starter search as a request and an answer (AGL-4049): what \"Choose\n * your starter\" asks `GET /api/marketplace/starters`, how the route reads the\n * question back, and how a card words what it shows.\n *\n * Pure and dependency-light on purpose, so the native apps mirror it line for\n * line (phase 5's `StarterQuery`): the same parameters in the same order, the\n * same defensive read of the answer, the same \"Free\" and \"$12\".\n */\n\n/** Where the console asks. */\nexport const STARTER_SEARCH_PATH = '/api/marketplace/starters'\n\n/** The longest search a request carries; the rest is dropped, not refused. */\nexport const STARTER_SEARCH_WORD_MAX = 200\n\n/** The facets a search may narrow to by query parameter, in the order they are written. */\nexport const STARTER_FILTER_KEYS = ['kind', 'base', 'fonts'] as const\nexport type StarterFilterKey = (typeof STARTER_FILTER_KEYS)[number]\n\n/** The names the cards and the filters show for the ids a starter carries. */\nexport interface StarterSearchLabels {\n /** A built-in theme's short name (`material3`) to the name the theme picker shows. */\n base: Record<string, string>\n /** A font pairing id to its families, as a person reads them. */\n fonts: Record<string, string>\n}\n\n/** What the route answers: the starters as summaries, and the names for their ids. */\nexport interface StarterSearchAnswer {\n rows: SiteStarterSummary[]\n labels: StarterSearchLabels\n}\n\n/** One search, as the console and the native apps build it. */\nexport interface StarterQueryInput {\n /** The workspace the site will belong to. */\n orgId: string\n /** How the site will be filled: its pages as they are, or by the AI site start. */\n mode: SiteStarterMode\n /** The person's words, as typed. */\n word?: string\n /** The facets the person narrowed to; an absent one is any. */\n filter?: Partial<SiteStarterFacets>\n /** At most this many; the route caps it. */\n limit?: number\n /**\n * A listing the answer must carry whatever the search finds (AGL-4049):\n * the person's own pick, restored on the way back from buying it, which a\n * search for other words or another mode would not list.\n */\n include?: string | null\n}\n\n/** One search, as the route reads it back, every part checked. */\nexport interface StarterQuery {\n orgId: string\n mode: SiteStarterMode\n word: string\n /** `mode` is always among them, so the source asks for that mode only. */\n filter: Partial<SiteStarterFacets>\n limit: number\n /** The listing to carry whatever the search finds, or `null`. */\n include: string | null\n}\n\nconst ORG_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst LISTING_ID = /^[A-Za-z0-9_-]{1,128}$/\nconst FACET_ID = /^[a-z0-9][a-z0-9-]{0,63}$/\n\nconst trimmed = (value: unknown): string =>\n typeof value === 'string' ? value.trim() : ''\n\n/**\n * The query string for one search, its parameters always in one order —\n * `orgId`, `mode`, `q`, `kind`, `base`, `fonts`, `limit`, `include` — so the\n * same search is the same URL, and a hook can key a request on it.\n */\nexport function starterQueryParams(input: StarterQueryInput): URLSearchParams {\n const params = new URLSearchParams()\n params.set('orgId', trimmed(input.orgId))\n params.set('mode', input.mode === 'ai' ? 'ai' : 'base')\n const word = trimmed(input.word).slice(0, STARTER_SEARCH_WORD_MAX)\n if (word) params.set('q', word)\n for (const key of STARTER_FILTER_KEYS) {\n const value = trimmed(input.filter?.[key])\n if (value) params.set(key, value)\n }\n params.set(\n 'limit',\n String(siteStarterSearchLimit(input.limit ?? SITE_STARTER_SEARCH_MAX) || SITE_STARTER_SEARCH_MAX),\n )\n const include = trimmed(input.include)\n if (LISTING_ID.test(include)) params.set('include', include)\n return params\n}\n\n/**\n * The route's reading of a search, or the refusal it answers with a 400.\n *\n * A base theme or a font pairing is checked against the lists a starter may\n * name (`SITE_STARTER_KNOWN_IDS`), and a kind against the styles a person\n * chooses among (core's `SITE_STYLES`, which are the kinds of site), so a\n * mistyped one is named rather than answered with nothing.\n */\nexport function starterQueryFrom(\n params: URLSearchParams,\n): StarterQuery | { error: string } {\n const orgId = trimmed(params.get('orgId'))\n if (!ORG_ID.test(orgId)) return { error: 'Missing orgId' }\n const askedMode = trimmed(params.get('mode'))\n if (askedMode && askedMode !== 'base' && askedMode !== 'ai') {\n return { error: 'Unknown mode' }\n }\n const mode: SiteStarterMode = askedMode === 'ai' ? 'ai' : 'base'\n const filter: Partial<SiteStarterFacets> = { mode }\n const kind = trimmed(params.get('kind'))\n if (kind) {\n if (!FACET_ID.test(kind) || !isSiteStyleId(kind)) return { error: 'Unknown kind of site' }\n filter.kind = kind\n }\n const base = trimmed(params.get('base'))\n if (base) {\n if (!SITE_STARTER_KNOWN_IDS.bases?.has(base)) return { error: 'Unknown base theme' }\n filter.base = base\n }\n const fonts = trimmed(params.get('fonts'))\n if (fonts) {\n if (!SITE_STARTER_KNOWN_IDS.fonts?.has(fonts)) return { error: 'Unknown font pairing' }\n filter.fonts = fonts\n }\n const include = trimmed(params.get('include'))\n if (include && !LISTING_ID.test(include)) return { error: 'Unknown starter' }\n return {\n orgId,\n mode,\n word: trimmed(params.get('q')).slice(0, STARTER_SEARCH_WORD_MAX),\n filter,\n limit: siteStarterSearchLimit(params.get('limit')) || SITE_STARTER_SEARCH_MAX,\n include: include || null,\n }\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n !!value && typeof value === 'object' && !Array.isArray(value)\n\nconst textOr = (value: unknown, fallback: string): string =>\n typeof value === 'string' ? value : fallback\n\nconst idOrNull = (value: unknown): string | null =>\n typeof value === 'string' && value.trim() ? value.trim() : null\n\n/**\n * One starter as a card shows it, read field by field, or `null` for a row\n * with no listing id.\n *\n * The route answers each row through this, as the console and the apps read\n * it, so what leaves the server is a summary and nothing else: a source that\n * handed back a paid AI starter's answers, or its pages, would have them\n * dropped here. Each field falls back the way a card needs it to: a missing\n * price is free, a missing picture is none, a page count is a whole number\n * from zero, a mode is `base` unless it says `ai`, and `owned` is kept only\n * where the answer gave it as a yes or a no.\n */\nexport function readStarterSummary(value: unknown): SiteStarterSummary | null {\n if (!isRecord(value)) return null\n const listingId = idOrNull(value['listingId'])\n if (!listingId) return null\n const price = Number(value['priceUsd'])\n const facets = isRecord(value['facets']) ? value['facets'] : {}\n const pages = Number(facets['pages'])\n const preview = value['previewImageUrl']\n return {\n listingId,\n displayName: textOr(value['displayName'], ''),\n description: textOr(value['description'], ''),\n authorName: textOr(value['authorName'], ''),\n official: value['official'] === true,\n priceUsd: Number.isFinite(price) && price > 0 ? price : 0,\n previewImageUrl: typeof preview === 'string' && preview ? preview : null,\n facets: {\n kind: idOrNull(facets['kind']),\n base: idOrNull(facets['base']),\n fonts: idOrNull(facets['fonts']),\n pages: Number.isFinite(pages) && pages > 0 ? Math.floor(pages) : 0,\n mode: facets['mode'] === 'ai' ? 'ai' : 'base',\n },\n category: idOrNull(value['category']),\n // Only where the answer says: absent is \"the search does not know\".\n ...(typeof value['owned'] === 'boolean' ? { owned: value['owned'] } : {}),\n ...(typeof value['buyBlockedReason'] === 'string' && value['buyBlockedReason']\n ? { buyBlockedReason: value['buyBlockedReason'] }\n : {}),\n }\n}\n\n/** A map of id to name, keeping only string names under non-empty ids. */\nconst namesOf = (value: unknown): Record<string, string> => {\n if (!isRecord(value)) return {}\n const names: Record<string, string> = {}\n for (const [id, name] of Object.entries(value)) {\n if (id && typeof name === 'string' && name) names[id] = name\n }\n return names\n}\n\n/**\n * The route's answer, read defensively: rows that are not starters are\n * dropped, as is a duplicate of a listing already read, and missing labels\n * are empty. Never throws, whatever it is handed.\n */\nexport function parseStarterSearchAnswer(json: unknown): StarterSearchAnswer {\n const body = isRecord(json) ? json : {}\n const seen = new Set<string>()\n const rows: SiteStarterSummary[] = []\n for (const value of Array.isArray(body['rows']) ? body['rows'] : []) {\n const row = readStarterSummary(value)\n if (!row || seen.has(row.listingId)) continue\n seen.add(row.listingId)\n rows.push(row)\n }\n const labels = isRecord(body['labels']) ? body['labels'] : {}\n return { rows, labels: { base: namesOf(labels['base']), fonts: namesOf(labels['fonts']) } }\n}\n\n/**\n * A starter's price as a card shows it: \"Free\" at zero, whole dollars as\n * \"$12\", and cents only where there are some (\"$12.50\").\n */\nexport function starterPriceLabel(usd: number): string {\n if (!Number.isFinite(usd) || usd <= 0) return 'Free'\n return Number.isInteger(usd) ? `$${usd}` : `$${usd.toFixed(2)}`\n}\n\n/** How many pages a starter creates, as a card says it, or `null` when it does not say. */\nexport function starterPagesLabel(pages: number): string | null {\n if (!Number.isFinite(pages) || pages < 1) return null\n const whole = Math.floor(pages)\n return whole === 1 ? '1 page' : `${whole} pages`\n}\n\n/** One fact a starter's card shows as a chip, keyed so a surface can style each kind its own way. */\nexport interface StarterCardFact {\n key: 'price' | 'official' | 'ai' | 'kind' | 'pages'\n label: string\n}\n\n/**\n * The chips on a starter's card, in the order they are read: the price,\n * every card carrying one (\"Free\" included, so a missing chip never reads as\n * a forgotten price); the platform's name for its own; \"AI\" for a starter the\n * AI site start fills; the kind of site in words; and its page count.\n *\n * The kind is the style's own name for the listing's kind of site (core's\n * `SITE_STYLES`), the same words the kind filters show — never the listing's\n * marketplace category, which for a starter that names no kind is a shelf\n * of the marketplace (`design`), not a kind of site.\n */\nexport function starterCardFacts(row: SiteStarterSummary): StarterCardFact[] {\n const facts: StarterCardFact[] = [{ key: 'price', label: starterPriceLabel(row.priceUsd) }]\n if (row.official) facts.push({ key: 'official', label: PLATFORM_BRAND_NAME })\n if (row.facets.mode === 'ai') facts.push({ key: 'ai', label: 'AI' })\n const kind = siteStyleOf(row.facets.kind)?.name\n if (kind) facts.push({ key: 'kind', label: kind })\n const pages = starterPagesLabel(row.facets.pages)\n if (pages) facts.push({ key: 'pages', label: pages })\n return facts\n}\n\n// ── An AI starter's answers (AGL-4049 phase 4) ─────────────────────────────\n\n/** Where the console reads the answers an AI starter carries. */\nexport const STARTER_ANSWERS_PATH = '/api/marketplace/starters/answers'\n\n/** One AI starter's answers, asked for a workspace. */\nexport interface StarterAnswersQuery {\n orgId: string\n listingId: string\n}\n\n/** What the route answers: the starter's answers, and its facets. */\nexport interface StarterAnswersAnswer {\n answers: Record<string, unknown>\n facets: SiteStarterFacets\n}\n\n/** The query string for one starter's answers, `orgId` then `listingId`. */\nexport function starterAnswersParams(input: StarterAnswersQuery): URLSearchParams {\n const params = new URLSearchParams()\n params.set('orgId', trimmed(input.orgId))\n params.set('listingId', trimmed(input.listingId))\n return params\n}\n\n/**\n * The route's reading of the question, or the refusal a 400 answers with:\n * the workspace, and a listing id as a listing may have one, since it\n * becomes a document path on the way to the listing.\n */\nexport function starterAnswersQueryFrom(params: URLSearchParams): StarterAnswersQuery | { error: string } {\n const orgId = trimmed(params.get('orgId'))\n if (!ORG_ID.test(orgId)) return { error: 'Missing orgId' }\n const listingId = trimmed(params.get('listingId'))\n if (!LISTING_ID.test(listingId)) return { error: 'Unknown starter' }\n return { orgId, listingId }\n}\n\n/**\n * The route's answer, read defensively: the answers as a plain object, and\n * the facets as a summary reads them; `null` for anything without answers.\n */\nexport function readStarterAnswersAnswer(json: unknown): StarterAnswersAnswer | null {\n if (!isRecord(json) || !isRecord(json['answers'])) return null\n const facets = readStarterSummary({ listingId: 'answers', facets: json['facets'] })?.facets\n if (!facets) return null\n return { answers: json['answers'], facets }\n}\n\n/**\n * The one place other than the marketplace a purchase may send its buyer\n * back to (AGL-4049): Create site, reopened on the starter they picked. A\n * name the checkout turns into an address itself, never an address the\n * browser hands it.\n */\nexport const STARTER_CHECKOUT_RETURN = 'create-site'\nexport type StarterCheckoutReturn = typeof STARTER_CHECKOUT_RETURN\n\n/**\n * A checkout body's `return`, read: `create-site`, `null` when it names none\n * (the marketplace, as always), or the refusal a 400 answers with.\n */\nexport function readStarterCheckoutReturn(value: unknown): StarterCheckoutReturn | null | { error: string } {\n if (value === undefined || value === null || value === '') return null\n return value === STARTER_CHECKOUT_RETURN ? STARTER_CHECKOUT_RETURN : { error: 'Unknown return' }\n}\n"],"names":["PLATFORM_BRAND_NAME","isSiteStyleId","siteStyleOf","SITE_STARTER_KNOWN_IDS","SITE_STARTER_SEARCH_MAX","siteStarterSearchLimit","STARTER_SEARCH_PATH","STARTER_SEARCH_WORD_MAX","STARTER_FILTER_KEYS","ORG_ID","LISTING_ID","FACET_ID","trimmed","value","trim","starterQueryParams","input","params","URLSearchParams","set","orgId","mode","word","slice","key","filter","String","limit","include","test","starterQueryFrom","get","error","askedMode","kind","base","bases","has","fonts","isRecord","Array","isArray","textOr","fallback","idOrNull","readStarterSummary","listingId","price","Number","facets","pages","preview","displayName","description","authorName","official","priceUsd","isFinite","previewImageUrl","Math","floor","category","owned","buyBlockedReason","namesOf","names","id","name","Object","entries","parseStarterSearchAnswer","json","body","seen","Set","rows","row","add","push","labels","starterPriceLabel","usd","isInteger","toFixed","starterPagesLabel","whole","starterCardFacts","facts","label","STARTER_ANSWERS_PATH","starterAnswersParams","starterAnswersQueryFrom","readStarterAnswersAnswer","answers","STARTER_CHECKOUT_RETURN","readStarterCheckoutReturn","undefined"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mBAAmB,QAAQ,wCAAuC;AAC3E,SAASC,aAAa,EAAEC,WAAW,QAAQ,qCAAoC;AAM/E,SACEC,sBAAsB,EACtBC,uBAAuB,EACvBC,sBAA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