@aglyn/plugins-marketplace 1.15.2 → 1.16.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.
- package/package.json +15 -15
- package/src/lib/components/listing-content.component.js +14 -12
- package/src/lib/components/listing-content.component.js.map +1 -1
- package/src/lib/components/site-plugin-connections-card.component.js +4 -3
- package/src/lib/components/site-plugin-connections-card.component.js.map +1 -1
- package/src/lib/model/editor-connections.d.ts +1 -1
- package/src/lib/model/editor-connections.js +13 -2
- package/src/lib/model/editor-connections.js.map +1 -1
- package/src/lib/model/marketplace.d.ts +11 -0
- package/src/lib/model/marketplace.js +12 -2
- package/src/lib/model/marketplace.js.map +1 -1
- package/src/lib/model/plugin-connection-card.d.ts +6 -0
- package/src/lib/model/plugin-connection-card.js +8 -0
- package/src/lib/model/plugin-connection-card.js.map +1 -1
- package/src/lib/model/plugin-connections.d.ts +14 -0
- package/src/lib/model/plugin-connections.js +18 -1
- package/src/lib/model/plugin-connections.js.map +1 -1
- package/src/lib/server/admin-reviews.js +9 -0
- package/src/lib/server/admin-reviews.js.map +1 -1
- package/src/lib/server/admin-trust.js +11 -0
- package/src/lib/server/admin-trust.js.map +1 -1
- package/src/lib/server/connections/site-records-platform.js +8 -5
- package/src/lib/server/connections/site-records-platform.js.map +1 -1
- package/src/lib/server/install-plugin.js +34 -19
- package/src/lib/server/install-plugin.js.map +1 -1
- package/src/lib/server/listing-versions.js +7 -2
- package/src/lib/server/listing-versions.js.map +1 -1
- package/src/lib/server/revoke-cache-drop.d.ts +29 -34
- package/src/lib/server/revoke-cache-drop.js +43 -49
- package/src/lib/server/revoke-cache-drop.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 { 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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ACvB,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 { pluginConnectionsPlanNote } from './plugin-connections'\nimport { PLATFORM_BRAND_NAME } from '@aglyn/aglyn/app-utils/platform-brand'\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/** A plugin version staff signed to run with the site's own code (`trust: 'realm'`). */\nconst REALM_PLUGIN_INSTALL_RESULT = `A plugin, reviewed and signed by ${PLATFORM_BRAND_NAME} to run with your site`\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: {\n reviewedVersion?: boolean\n /**\n * The version on offer is staff-signed to run with the site's own code\n * (`trust: 'realm'`), so \"sandboxed on its own origin\" would be untrue.\n */\n realmTrusted?: boolean\n /**\n * The labels of the services the version on offer declares connections\n * to (AGL-4197). Connecting one needs a plan that includes plugin\n * connections, which a shopper has to know before installing.\n */\n connections?: readonly string[]\n } = {},\n): ListingInclusion[] {\n const type = listingArtifactType(listing)\n const rows: ListingInclusion[] = [\n {\n label:\n type === 'plugin' && options.realmTrusted\n ? REALM_PLUGIN_INSTALL_RESULT\n : ARTIFACT_INSTALL_RESULT[type] ?? 'An installable artifact',\n tone: 'included',\n },\n ]\n const planNote =\n type === 'plugin' ? pluginConnectionsPlanNote(options.connections ?? []) : null\n // Right after what the install produces: it is the fact most likely to stop\n // an install, and a note, not a tick, because it is a limit.\n if (planNote) rows.push({ label: planNote, tone: 'note' })\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","pluginConnectionsPlanNote","PLATFORM_BRAND_NAME","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","REALM_PLUGIN_INSTALL_RESULT","listingInclusions","options","type","rows","label","realmTrusted","tone","planNote","connections","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,0BAAsB;AAChE,SAASC,mBAAmB,QAAQ,wCAAuC;AAC3E,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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AaL,eAAeC;AAE1D;AACA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAiDC,GACD,OAAO,SAASK,oBACdL,QAA6C,EAC7CM,KAAqD;IAErD,IAAI,CAACP,eAAeC,WAAW,OAAO;IACtC,MAAMO,gBAAgBP,4BAAAA,SAAUQ,UAAU;IAC1C,IAAI,OAAOD,kBAAkB,YAAYA,eAAe;QACtD,OAAOlH,QAAQiH,MAAMG,KAAK,KAAKF,kBAAkBD,MAAMG,KAAK;IAC9D;IACA,4EAA4E;IAC5E,2CAA2C;IAC3C,OAAOpH,QAAQiH,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,EAAEtE,IAAI,CAC3B,CAACmE,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,KAAK3I,QAAQ,CAACsI,QAAQ;YAC/DK,KAAKxG,IAAI,CAACmG;QACZ;IACF;IACA,OAAOK;AACT"}
|
|
@@ -82,6 +82,12 @@ export declare function declaredPluginConnections(manifest: unknown): Array<{
|
|
|
82
82
|
}>;
|
|
83
83
|
/** What a site owner is told when "Sync now" comes within a minute of the last sync. */
|
|
84
84
|
export declare function pluginConnectionTooSoonText(label: string, retryAfterMs: number | null): string;
|
|
85
|
+
/**
|
|
86
|
+
* What a site owner is told when the last sync failed. The provider's own
|
|
87
|
+
* sentence usually ends in a period, and the card's next sentence must not
|
|
88
|
+
* add a second one.
|
|
89
|
+
*/
|
|
90
|
+
export declare function pluginConnectionSyncFailedText(lastError: string | null | undefined): string;
|
|
85
91
|
/** Where a connection's data goes and comes from, as the card says it. */
|
|
86
92
|
export declare function pluginConnectionSharesText(hosts: readonly string[] | undefined): string | null;
|
|
87
93
|
/** A date and time as the cards print it. */
|
|
@@ -174,6 +174,14 @@ const RESULT_MESSAGES = {
|
|
|
174
174
|
const seconds = retryAfterMs && retryAfterMs > 0 ? Math.ceil(retryAfterMs / 1000) : null;
|
|
175
175
|
return seconds ? `${label} synced moments ago. You can sync it again in ${seconds} seconds.` : `${label} synced moments ago. You can sync it again in a minute.`;
|
|
176
176
|
}
|
|
177
|
+
/**
|
|
178
|
+
* What a site owner is told when the last sync failed. The provider's own
|
|
179
|
+
* sentence usually ends in a period, and the card's next sentence must not
|
|
180
|
+
* add a second one.
|
|
181
|
+
*/ export function pluginConnectionSyncFailedText(lastError) {
|
|
182
|
+
const reason = String(lastError != null ? lastError : '').trim().replace(/[.!?\s]+$/, '');
|
|
183
|
+
return reason ? `The last sync did not work: ${reason}. It tries again on schedule, or you can sync now.` : 'The last sync did not work. It tries again on schedule, or you can sync now.';
|
|
184
|
+
}
|
|
177
185
|
/** Where a connection's data goes and comes from, as the card says it. */ export function pluginConnectionSharesText(hosts) {
|
|
178
186
|
return hosts && hosts.length ? `Shares data with: ${hosts.join(', ')}` : null;
|
|
179
187
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/plugin-connection-card.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 { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n PLUGIN_CONNECTIONS_API_ROUTES,\n type PluginConnectionStatusEntry,\n type PluginConnectionView,\n} from './plugin-connections'\n\n/*\n * WHAT THE CONNECTION CARDS SAY (AGL-4196), kept apart from React so the\n * console card, the publisher's credentials card and their specs read one\n * answer. Pure: no Firestore, no fetch, no window.\n */\n\n/** The address a publisher registers at the provider as the OAuth app's redirect URI. */\nexport function pluginConnectionRedirectUri(origin: string = platformConsoleOrigin()): string {\n return `${origin.replace(/\\/+$/, '')}/api/${PLUGIN_CONNECTIONS_API_ROUTES.connectCallback}`\n}\n\n/** A view as the card reads it: the sync may also say when it runs next. */\nexport type PluginConnectionCardView = PluginConnectionView & { nextSyncAtMs?: number | null }\n\n/**\n * Where one declared connection stands for a site, in the order the card\n * checks: a deployment without the key first, then the site's own grant,\n * then what the publisher has set up.\n */\nexport type PluginConnectionPhase =\n | 'not-configured'\n | 'not-set-up'\n | 'not-connected'\n | 'choosing'\n | 'connected'\n | 'reconnect'\n | 'error'\n\nexport function pluginConnectionPhase(entry: PluginConnectionStatusEntry, configured: boolean): PluginConnectionPhase {\n if (!configured) return 'not-configured'\n const connection = entry.connection\n if (!connection) return entry.credentialsSet ? 'not-connected' : 'not-set-up'\n if (connection.status === 'reconnect_required') return 'reconnect'\n if (connection.status === 'error') return 'error'\n return connection.ready ? 'connected' : 'choosing'\n}\n\n/** The first declared resource the site has not chosen yet, in order. */\nexport function nextResourceToChoose(\n entry: Pick<PluginConnectionStatusEntry, 'resources' | 'connection'>,\n): { id: string; label: string } | null {\n const choices = entry.connection?.choices ?? {}\n return entry.resources.find((resource) => !choices[resource.id]) ?? null\n}\n\n/** The status chip each phase wears. */\nexport const PLUGIN_CONNECTION_PHASE_CHIP: Readonly<\n Record<PluginConnectionPhase, { label: string; tone: 'neutral' | 'info' | 'success' | 'warning' | 'error' }>\n> = {\n 'not-configured': { label: 'Not available yet', tone: 'neutral' },\n 'not-set-up': { label: 'Waiting on the publisher', tone: 'neutral' },\n 'not-connected': { label: 'Not connected', tone: 'neutral' },\n choosing: { label: 'Finish setting up', tone: 'info' },\n connected: { label: 'Connected', tone: 'success' },\n reconnect: { label: 'Reconnect needed', tone: 'warning' },\n error: { label: 'Sync failed', tone: 'error' },\n}\n\n/** What a site owner is told when a deployment cannot run connections. */\nexport const PLUGIN_CONNECTIONS_NOT_CONFIGURED_TEXT =\n 'Connecting plugins to other services is not available here yet.'\n\n/** What a site owner is told while the publisher has not set the connection up. */\nexport function pluginConnectionNotSetUpText(label: string): string {\n return `The plugin's publisher has not finished setting up ${label} yet. You can connect once they have.`\n}\n\n/** The query the connect callback adds to the page it returns to. */\nexport const PLUGIN_CONNECTION_RETURN_PARAMS = {\n listing: 'pluginConnectionListing',\n connection: 'pluginConnection',\n result: 'pluginConnectionResult',\n} as const\n\nexport type PluginConnectionResult = 'connected' | 'denied' | 'expired' | 'failed' | 'not-permitted' | 'not-set-up'\n\nconst RESULT_MESSAGES: Readonly<\n Record<PluginConnectionResult, { variant: 'success' | 'warning' | 'error'; message: (label: string) => string }>\n> = {\n connected: { variant: 'success', message: (label) => `Connected ${label}.` },\n denied: { variant: 'warning', message: (label) => `Access to ${label} was not granted, so nothing was connected.` },\n expired: { variant: 'error', message: () => 'The connection took too long or was already used. Connect again.' },\n failed: { variant: 'error', message: (label) => `${label} could not be connected. Try again.` },\n 'not-permitted': {\n variant: 'error',\n message: () => 'You can no longer connect this here: the site, its plan or your permissions changed.',\n },\n 'not-set-up': { variant: 'error', message: (label) => pluginConnectionNotSetUpText(label) },\n}\n\nexport interface PluginConnectionReturn {\n listingId: string\n connectionId: string\n result: PluginConnectionResult\n /** The page's address without the three parameters. */\n cleanUrl: string\n}\n\n/**\n * The outcome the connect callback left on `href` for `listingId`, and the\n * address to replace it with, or `null` when it carries none for it.\n */\nexport function readPluginConnectionReturn(href: string, listingId: string): PluginConnectionReturn | null {\n let url: URL\n try {\n url = new URL(href)\n } catch {\n return null\n }\n const params = url.searchParams\n const result = params.get(PLUGIN_CONNECTION_RETURN_PARAMS.result)\n if (params.get(PLUGIN_CONNECTION_RETURN_PARAMS.listing) !== listingId) return null\n if (!result || !(result in RESULT_MESSAGES)) return null\n const connectionId = params.get(PLUGIN_CONNECTION_RETURN_PARAMS.connection) ?? ''\n for (const key of Object.values(PLUGIN_CONNECTION_RETURN_PARAMS)) params.delete(key)\n return {\n listingId,\n connectionId,\n result: result as PluginConnectionResult,\n cleanUrl: `${url.pathname}${url.search}${url.hash}`,\n }\n}\n\n/** The snackbar a returned connect shows. */\nexport function pluginConnectionResultMessage(\n result: PluginConnectionResult,\n label: string,\n): { variant: 'success' | 'warning' | 'error'; message: string } {\n const entry = RESULT_MESSAGES[result]\n return { variant: entry.variant, message: entry.message(label) }\n}\n\n/**\n * When the next scheduled sync runs: what the sync recorded when it says,\n * else the last one plus the pinned manifest's interval. A connection with\n * every choice made and no sync yet runs on the next pass.\n */\nexport function pluginConnectionNextSyncAtMs(\n view: PluginConnectionCardView | null,\n intervalHours: number | null | undefined,\n): number | 'soon' | null {\n // A failed sync backs off on the server, so the interval no longer says when it runs again.\n if (!view || view.status !== 'connected' || !view.ready) return null\n if (typeof view.nextSyncAtMs === 'number') return view.nextSyncAtMs\n if (!intervalHours || intervalHours <= 0) return null\n if (view.lastSyncAtMs === null) return 'soon'\n return view.lastSyncAtMs + intervalHours * 3_600_000\n}\n\n/** The sync interval a pinned manifest declares for one connection, if any. */\nexport function declaredSyncIntervalHours(manifest: unknown, connectionId: string): number | null {\n const connections = (manifest as { connections?: unknown } | null | undefined)?.connections\n if (!Array.isArray(connections)) return null\n const found = connections.find(\n (one): one is { id: string; sync?: { intervalHours?: unknown } } =>\n Boolean(one) && typeof one === 'object' && (one as { id?: unknown }).id === connectionId,\n )\n const hours = found?.sync?.intervalHours\n return typeof hours === 'number' && Number.isFinite(hours) ? hours : null\n}\n\n/** The connections a pinned manifest declares, by id and label: what the card can name before the status answers. */\nexport function declaredPluginConnections(manifest: unknown): Array<{ id: string; label: string; description?: string }> {\n const connections = (manifest as { connections?: unknown } | null | undefined)?.connections\n if (!Array.isArray(connections)) return []\n return connections.flatMap((one) => {\n if (!one || typeof one !== 'object') return []\n const { id, label, description } = one as { id?: unknown; label?: unknown; description?: unknown }\n if (typeof id !== 'string' || !id || typeof label !== 'string' || !label) return []\n return [{ id, label, ...(typeof description === 'string' && description ? { description } : {}) }]\n })\n}\n\n/** What a site owner is told when \"Sync now\" comes within a minute of the last sync. */\nexport function pluginConnectionTooSoonText(label: string, retryAfterMs: number | null): string {\n const seconds = retryAfterMs && retryAfterMs > 0 ? Math.ceil(retryAfterMs / 1000) : null\n return seconds\n ? `${label} synced moments ago. You can sync it again in ${seconds} seconds.`\n : `${label} synced moments ago. You can sync it again in a minute.`\n}\n\n/** Where a connection's data goes and comes from, as the card says it. */\nexport function pluginConnectionSharesText(hosts: readonly string[] | undefined): string | null {\n return hosts && hosts.length ? `Shares data with: ${hosts.join(', ')}` : null\n}\n\n/** A date and time as the cards print it. */\nexport function formatConnectionTime(ms: number): string {\n return new Date(ms).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })\n}\n"],"names":["platformConsoleOrigin","PLUGIN_CONNECTIONS_API_ROUTES","pluginConnectionRedirectUri","origin","replace","connectCallback","pluginConnectionPhase","entry","configured","connection","credentialsSet","status","ready","nextResourceToChoose","choices","resources","find","resource","id","PLUGIN_CONNECTION_PHASE_CHIP","label","tone","choosing","connected","reconnect","error","PLUGIN_CONNECTIONS_NOT_CONFIGURED_TEXT","pluginConnectionNotSetUpText","PLUGIN_CONNECTION_RETURN_PARAMS","listing","result","RESULT_MESSAGES","variant","message","denied","expired","failed","readPluginConnectionReturn","href","listingId","params","url","URL","searchParams","get","connectionId","key","Object","values","delete","cleanUrl","pathname","search","hash","pluginConnectionResultMessage","pluginConnectionNextSyncAtMs","view","intervalHours","nextSyncAtMs","lastSyncAtMs","declaredSyncIntervalHours","manifest","found","connections","Array","isArray","one","Boolean","hours","sync","Number","isFinite","declaredPluginConnections","flatMap","description","pluginConnectionTooSoonText","retryAfterMs","seconds","Math","ceil","pluginConnectionSharesText","hosts","length","join","formatConnectionTime","ms","Date","toLocaleString","undefined","dateStyle","timeStyle"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,6BAA6B,QAGxB,0BAAsB;AAE7B;;;;CAIC,GAED,uFAAuF,GACvF,OAAO,SAASC,4BAA4BC,SAAiBH,uBAAuB;IAClF,OAAO,GAAGG,OAAOC,OAAO,CAAC,QAAQ,IAAI,KAAK,EAAEH,8BAA8BI,eAAe,EAAE;AAC7F;AAmBA,OAAO,SAASC,sBAAsBC,KAAkC,EAAEC,UAAmB;IAC3F,IAAI,CAACA,YAAY,OAAO;IACxB,MAAMC,aAAaF,MAAME,UAAU;IACnC,IAAI,CAACA,YAAY,OAAOF,MAAMG,cAAc,GAAG,kBAAkB;IACjE,IAAID,WAAWE,MAAM,KAAK,sBAAsB,OAAO;IACvD,IAAIF,WAAWE,MAAM,KAAK,SAAS,OAAO;IAC1C,OAAOF,WAAWG,KAAK,GAAG,cAAc;AAC1C;AAEA,uEAAuE,GACvE,OAAO,SAASC,qBACdN,KAAoE;cAG7DA;QADSA;IAAhB,MAAMO,mBAAUP,oBAAAA,MAAME,UAAU,qBAAhBF,kBAAkBO,OAAO,mBAAI,CAAC;IAC9C,QAAOP,wBAAAA,MAAMQ,SAAS,CAACC,IAAI,CAAC,CAACC,WAAa,CAACH,OAAO,CAACG,SAASC,EAAE,CAAC,aAAxDX,wBAA6D;AACtE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;AAC3E;AAEA,2CAA2C,GAC3C,OAAO,SAASC,qBAAqBC,EAAU;IAC7C,OAAO,IAAIC,KAAKD,IAAIE,cAAc,CAACC,WAAW;QAAEC,WAAW;QAAUC,WAAW;IAAQ;AAC1F"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/plugin-connection-card.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 { platformConsoleOrigin } from '@aglyn/aglyn/app-utils/platform-brand'\nimport {\n PLUGIN_CONNECTIONS_API_ROUTES,\n type PluginConnectionStatusEntry,\n type PluginConnectionView,\n} from './plugin-connections'\n\n/*\n * WHAT THE CONNECTION CARDS SAY (AGL-4196), kept apart from React so the\n * console card, the publisher's credentials card and their specs read one\n * answer. Pure: no Firestore, no fetch, no window.\n */\n\n/** The address a publisher registers at the provider as the OAuth app's redirect URI. */\nexport function pluginConnectionRedirectUri(origin: string = platformConsoleOrigin()): string {\n return `${origin.replace(/\\/+$/, '')}/api/${PLUGIN_CONNECTIONS_API_ROUTES.connectCallback}`\n}\n\n/** A view as the card reads it: the sync may also say when it runs next. */\nexport type PluginConnectionCardView = PluginConnectionView & { nextSyncAtMs?: number | null }\n\n/**\n * Where one declared connection stands for a site, in the order the card\n * checks: a deployment without the key first, then the site's own grant,\n * then what the publisher has set up.\n */\nexport type PluginConnectionPhase =\n | 'not-configured'\n | 'not-set-up'\n | 'not-connected'\n | 'choosing'\n | 'connected'\n | 'reconnect'\n | 'error'\n\nexport function pluginConnectionPhase(entry: PluginConnectionStatusEntry, configured: boolean): PluginConnectionPhase {\n if (!configured) return 'not-configured'\n const connection = entry.connection\n if (!connection) return entry.credentialsSet ? 'not-connected' : 'not-set-up'\n if (connection.status === 'reconnect_required') return 'reconnect'\n if (connection.status === 'error') return 'error'\n return connection.ready ? 'connected' : 'choosing'\n}\n\n/** The first declared resource the site has not chosen yet, in order. */\nexport function nextResourceToChoose(\n entry: Pick<PluginConnectionStatusEntry, 'resources' | 'connection'>,\n): { id: string; label: string } | null {\n const choices = entry.connection?.choices ?? {}\n return entry.resources.find((resource) => !choices[resource.id]) ?? null\n}\n\n/** The status chip each phase wears. */\nexport const PLUGIN_CONNECTION_PHASE_CHIP: Readonly<\n Record<PluginConnectionPhase, { label: string; tone: 'neutral' | 'info' | 'success' | 'warning' | 'error' }>\n> = {\n 'not-configured': { label: 'Not available yet', tone: 'neutral' },\n 'not-set-up': { label: 'Waiting on the publisher', tone: 'neutral' },\n 'not-connected': { label: 'Not connected', tone: 'neutral' },\n choosing: { label: 'Finish setting up', tone: 'info' },\n connected: { label: 'Connected', tone: 'success' },\n reconnect: { label: 'Reconnect needed', tone: 'warning' },\n error: { label: 'Sync failed', tone: 'error' },\n}\n\n/** What a site owner is told when a deployment cannot run connections. */\nexport const PLUGIN_CONNECTIONS_NOT_CONFIGURED_TEXT =\n 'Connecting plugins to other services is not available here yet.'\n\n/** What a site owner is told while the publisher has not set the connection up. */\nexport function pluginConnectionNotSetUpText(label: string): string {\n return `The plugin's publisher has not finished setting up ${label} yet. You can connect once they have.`\n}\n\n/** The query the connect callback adds to the page it returns to. */\nexport const PLUGIN_CONNECTION_RETURN_PARAMS = {\n listing: 'pluginConnectionListing',\n connection: 'pluginConnection',\n result: 'pluginConnectionResult',\n} as const\n\nexport type PluginConnectionResult = 'connected' | 'denied' | 'expired' | 'failed' | 'not-permitted' | 'not-set-up'\n\nconst RESULT_MESSAGES: Readonly<\n Record<PluginConnectionResult, { variant: 'success' | 'warning' | 'error'; message: (label: string) => string }>\n> = {\n connected: { variant: 'success', message: (label) => `Connected ${label}.` },\n denied: { variant: 'warning', message: (label) => `Access to ${label} was not granted, so nothing was connected.` },\n expired: { variant: 'error', message: () => 'The connection took too long or was already used. Connect again.' },\n failed: { variant: 'error', message: (label) => `${label} could not be connected. Try again.` },\n 'not-permitted': {\n variant: 'error',\n message: () => 'You can no longer connect this here: the site, its plan or your permissions changed.',\n },\n 'not-set-up': { variant: 'error', message: (label) => pluginConnectionNotSetUpText(label) },\n}\n\nexport interface PluginConnectionReturn {\n listingId: string\n connectionId: string\n result: PluginConnectionResult\n /** The page's address without the three parameters. */\n cleanUrl: string\n}\n\n/**\n * The outcome the connect callback left on `href` for `listingId`, and the\n * address to replace it with, or `null` when it carries none for it.\n */\nexport function readPluginConnectionReturn(href: string, listingId: string): PluginConnectionReturn | null {\n let url: URL\n try {\n url = new URL(href)\n } catch {\n return null\n }\n const params = url.searchParams\n const result = params.get(PLUGIN_CONNECTION_RETURN_PARAMS.result)\n if (params.get(PLUGIN_CONNECTION_RETURN_PARAMS.listing) !== listingId) return null\n if (!result || !(result in RESULT_MESSAGES)) return null\n const connectionId = params.get(PLUGIN_CONNECTION_RETURN_PARAMS.connection) ?? ''\n for (const key of Object.values(PLUGIN_CONNECTION_RETURN_PARAMS)) params.delete(key)\n return {\n listingId,\n connectionId,\n result: result as PluginConnectionResult,\n cleanUrl: `${url.pathname}${url.search}${url.hash}`,\n }\n}\n\n/** The snackbar a returned connect shows. */\nexport function pluginConnectionResultMessage(\n result: PluginConnectionResult,\n label: string,\n): { variant: 'success' | 'warning' | 'error'; message: string } {\n const entry = RESULT_MESSAGES[result]\n return { variant: entry.variant, message: entry.message(label) }\n}\n\n/**\n * When the next scheduled sync runs: what the sync recorded when it says,\n * else the last one plus the pinned manifest's interval. A connection with\n * every choice made and no sync yet runs on the next pass.\n */\nexport function pluginConnectionNextSyncAtMs(\n view: PluginConnectionCardView | null,\n intervalHours: number | null | undefined,\n): number | 'soon' | null {\n // A failed sync backs off on the server, so the interval no longer says when it runs again.\n if (!view || view.status !== 'connected' || !view.ready) return null\n if (typeof view.nextSyncAtMs === 'number') return view.nextSyncAtMs\n if (!intervalHours || intervalHours <= 0) return null\n if (view.lastSyncAtMs === null) return 'soon'\n return view.lastSyncAtMs + intervalHours * 3_600_000\n}\n\n/** The sync interval a pinned manifest declares for one connection, if any. */\nexport function declaredSyncIntervalHours(manifest: unknown, connectionId: string): number | null {\n const connections = (manifest as { connections?: unknown } | null | undefined)?.connections\n if (!Array.isArray(connections)) return null\n const found = connections.find(\n (one): one is { id: string; sync?: { intervalHours?: unknown } } =>\n Boolean(one) && typeof one === 'object' && (one as { id?: unknown }).id === connectionId,\n )\n const hours = found?.sync?.intervalHours\n return typeof hours === 'number' && Number.isFinite(hours) ? hours : null\n}\n\n/** The connections a pinned manifest declares, by id and label: what the card can name before the status answers. */\nexport function declaredPluginConnections(manifest: unknown): Array<{ id: string; label: string; description?: string }> {\n const connections = (manifest as { connections?: unknown } | null | undefined)?.connections\n if (!Array.isArray(connections)) return []\n return connections.flatMap((one) => {\n if (!one || typeof one !== 'object') return []\n const { id, label, description } = one as { id?: unknown; label?: unknown; description?: unknown }\n if (typeof id !== 'string' || !id || typeof label !== 'string' || !label) return []\n return [{ id, label, ...(typeof description === 'string' && description ? { description } : {}) }]\n })\n}\n\n/** What a site owner is told when \"Sync now\" comes within a minute of the last sync. */\nexport function pluginConnectionTooSoonText(label: string, retryAfterMs: number | null): string {\n const seconds = retryAfterMs && retryAfterMs > 0 ? Math.ceil(retryAfterMs / 1000) : null\n return seconds\n ? `${label} synced moments ago. You can sync it again in ${seconds} seconds.`\n : `${label} synced moments ago. You can sync it again in a minute.`\n}\n\n/**\n * What a site owner is told when the last sync failed. The provider's own\n * sentence usually ends in a period, and the card's next sentence must not\n * add a second one.\n */\nexport function pluginConnectionSyncFailedText(lastError: string | null | undefined): string {\n const reason = String(lastError ?? '').trim().replace(/[.!?\\s]+$/, '')\n return reason\n ? `The last sync did not work: ${reason}. It tries again on schedule, or you can sync now.`\n : 'The last sync did not work. It tries again on schedule, or you can sync now.'\n}\n\n/** Where a connection's data goes and comes from, as the card says it. */\nexport function pluginConnectionSharesText(hosts: readonly string[] | undefined): string | null {\n return hosts && hosts.length ? `Shares data with: ${hosts.join(', ')}` : null\n}\n\n/** A date and time as the cards print it. */\nexport function formatConnectionTime(ms: number): string {\n return new Date(ms).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })\n}\n"],"names":["platformConsoleOrigin","PLUGIN_CONNECTIONS_API_ROUTES","pluginConnectionRedirectUri","origin","replace","connectCallback","pluginConnectionPhase","entry","configured","connection","credentialsSet","status","ready","nextResourceToChoose","choices","resources","find","resource","id","PLUGIN_CONNECTION_PHASE_CHIP","label","tone","choosing","connected","reconnect","error","PLUGIN_CONNECTIONS_NOT_CONFIGURED_TEXT","pluginConnectionNotSetUpText","PLUGIN_CONNECTION_RETURN_PARAMS","listing","result","RESULT_MESSAGES","variant","message","denied","expired","failed","readPluginConnectionReturn","href","listingId","params","url","URL","searchParams","get","connectionId","key","Object","values","delete","cleanUrl","pathname","search","hash","pluginConnectionResultMessage","pluginConnectionNextSyncAtMs","view","intervalHours","nextSyncAtMs","lastSyncAtMs","declaredSyncIntervalHours","manifest","found","connections","Array","isArray","one","Boolean","hours","sync","Number","isFinite","declaredPluginConnections","flatMap","description","pluginConnectionTooSoonText","retryAfterMs","seconds","Math","ceil","pluginConnectionSyncFailedText","lastError","reason","String","trim","pluginConnectionSharesText","hosts","length","join","formatConnectionTime","ms","Date","toLocaleString","undefined","dateStyle","timeStyle"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,6BAA6B,QAGxB,0BAAsB;AAE7B;;;;CAIC,GAED,uFAAuF,GACvF,OAAO,SAASC,4BAA4BC,SAAiBH,uBAAuB;IAClF,OAAO,GAAGG,OAAOC,OAAO,CAAC,QAAQ,IAAI,KAAK,EAAEH,8BAA8BI,eA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;QACnC,IAAI,OAAOhD,OAAO,YAAY,CAACA,MAAM,OAAOE,UAAU,YAAY,CAACA,OAAO,OAAO,EAAE;QACnF,OAAO;YAAC;gBAAEF;gBAAIE;eAAW,OAAOsD,gBAAgB,YAAYA,cAAc;gBAAEA;YAAY,IAAI,CAAC;SAAK;IACpG;AACF;AAEA,sFAAsF,GACtF,OAAO,SAASC,4BAA4BvD,KAAa,EAAEwD,YAA2B;IACpF,MAAMC,UAAUD,gBAAgBA,eAAe,IAAIE,KAAKC,IAAI,CAACH,eAAe,QAAQ;IACpF,OAAOC,UACH,GAAGzD,MAAM,8CAA8C,EAAEyD,QAAQ,SAAS,CAAC,GAC3E,GAAGzD,MAAM,uDAAuD,CAAC;AACvE;AAEA;;;;CAIC,GACD,OAAO,SAAS4D,+BAA+BC,SAAoC;IACjF,MAAMC,SAASC,OAAOF,oBAAAA,YAAa,IAAIG,IAAI,GAAGhF,OAAO,CAAC,aAAa;IACnE,OAAO8E,SACH,CAAC,4BAA4B,EAAEA,OAAO,kDAAkD,CAAC,GACzF;AACN;AAEA,wEAAwE,GACxE,OAAO,SAASG,2BAA2BC,KAAoC;IAC7E,OAAOA,SAASA,MAAMC,MAAM,GAAG,CAAC,kBAAkB,EAAED,MAAME,IAAI,CAAC,OAAO,GAAG;AAC3E;AAEA,2CAA2C,GAC3C,OAAO,SAASC,qBAAqBC,EAAU;IAC7C,OAAO,IAAIC,KAAKD,IAAIE,cAAc,CAACC,WAAW;QAAEC,WAAW;QAAUC,WAAW;IAAQ;AAC1F"}
|
|
@@ -136,8 +136,22 @@ export declare const PLUGIN_CONNECTIONS_FEATURE = "pluginConnections";
|
|
|
136
136
|
export declare const PLUGIN_CONNECTIONS_BY_PLAN: Readonly<Record<OrgPlan, boolean>>;
|
|
137
137
|
/** The feature as the marketplace declares it (`registerPluginEntitlements`). */
|
|
138
138
|
export declare const PLUGIN_CONNECTIONS_FEATURE_DECLARATION: PluginFeatureDeclaration;
|
|
139
|
+
/**
|
|
140
|
+
* The plans the feature comes with, as every sentence about it names them: the
|
|
141
|
+
* plans on sale that `PLUGIN_CONNECTIONS_BY_PLAN` turns on. Names, never a
|
|
142
|
+
* price.
|
|
143
|
+
*/
|
|
144
|
+
export declare const PLUGIN_CONNECTIONS_PLANS = "the Starter, Pro and Custom plans";
|
|
139
145
|
/** What a plan without the feature is told. Names the plans, never a price. */
|
|
140
146
|
export declare const PLUGIN_CONNECTIONS_PLAN_REFUSAL = "Connecting a plugin to another service comes with the Starter, Pro and Custom plans.";
|
|
147
|
+
/**
|
|
148
|
+
* What a shopper reads on a listing whose plugin declares connections, before
|
|
149
|
+
* installing (AGL-4197): the plugin installs on any plan, but connecting it,
|
|
150
|
+
* which is what makes it useful, needs one of these plans. "Google Business
|
|
151
|
+
* Profile" → "Connecting Google Business Profile comes with the Starter, Pro
|
|
152
|
+
* and Custom plans". Null when nothing is declared.
|
|
153
|
+
*/
|
|
154
|
+
export declare function pluginConnectionsPlanNote(labels: readonly string[]): string | null;
|
|
141
155
|
/** The site key: connect, choose, disconnect and read a site's plugin connections. */
|
|
142
156
|
export declare const PLUGIN_CONNECTIONS_SITE_PERMISSION = "marketplace.siteConnections";
|
|
143
157
|
/** The publisher key: set a listing's OAuth app credentials. */
|
|
@@ -89,7 +89,24 @@ import { MARKETPLACE_CONNECTION_SITE_PERMISSIONS, MARKETPLACE_CONNECTION_SITE_RO
|
|
|
89
89
|
label: 'Plugin connections',
|
|
90
90
|
defaultByPlan: PLUGIN_CONNECTIONS_BY_PLAN
|
|
91
91
|
};
|
|
92
|
-
/**
|
|
92
|
+
/**
|
|
93
|
+
* The plans the feature comes with, as every sentence about it names them: the
|
|
94
|
+
* plans on sale that `PLUGIN_CONNECTIONS_BY_PLAN` turns on. Names, never a
|
|
95
|
+
* price.
|
|
96
|
+
*/ export const PLUGIN_CONNECTIONS_PLANS = 'the Starter, Pro and Custom plans';
|
|
97
|
+
/** What a plan without the feature is told. Names the plans, never a price. */ export const PLUGIN_CONNECTIONS_PLAN_REFUSAL = `Connecting a plugin to another service comes with ${PLUGIN_CONNECTIONS_PLANS}.`;
|
|
98
|
+
/**
|
|
99
|
+
* What a shopper reads on a listing whose plugin declares connections, before
|
|
100
|
+
* installing (AGL-4197): the plugin installs on any plan, but connecting it,
|
|
101
|
+
* which is what makes it useful, needs one of these plans. "Google Business
|
|
102
|
+
* Profile" → "Connecting Google Business Profile comes with the Starter, Pro
|
|
103
|
+
* and Custom plans". Null when nothing is declared.
|
|
104
|
+
*/ export function pluginConnectionsPlanNote(labels) {
|
|
105
|
+
const names = Array.from(new Set(labels.map((label)=>String(label).trim()).filter(Boolean)));
|
|
106
|
+
if (!names.length) return null;
|
|
107
|
+
const joined = names.length === 1 ? names[0] : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
|
|
108
|
+
return `Connecting ${joined} comes with ${PLUGIN_CONNECTIONS_PLANS}`;
|
|
109
|
+
}
|
|
93
110
|
/* ------------------------------------------------------------------ */ /* The permission keys */ /* ------------------------------------------------------------------ */ /** The site key: connect, choose, disconnect and read a site's plugin connections. */ export const PLUGIN_CONNECTIONS_SITE_PERMISSION = 'marketplace.siteConnections';
|
|
94
111
|
/** The publisher key: set a listing's OAuth app credentials. */ export const PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION = 'marketplace.connectionCredentials';
|
|
95
112
|
/** The site Admin (declared beside the marketplace's other site keys). */ export const PLUGIN_CONNECTIONS_SITE_ROLE_PRESET = MARKETPLACE_CONNECTION_SITE_ROLE_PRESET;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/plugin-connections.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginConnectionEndpointHosts,\n type PluginConnectionDeclaration,\n} from '@aglyn/aglyn/app-utils/plugin-connections'\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { OrgPlan } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type { PluginFeatureDeclaration, PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\nimport { MARKETPLACE_PUBLISHER_PERMISSIONS } from './marketplace-publisher-permissions'\nimport {\n MARKETPLACE_CONNECTION_SITE_PERMISSIONS,\n MARKETPLACE_CONNECTION_SITE_ROLE_PRESET,\n} from './marketplace-site-permissions'\n\n/*\n * DECLARED CONNECTIONS, THE PLATFORM'S HALF (AGL-4193): THE CONTRACT.\n *\n * A marketplace plugin declares a connection in its manifest\n * (`@aglyn/aglyn/app-utils/plugin-connections`); this plugin, the\n * marketplace, runs it for every plugin it distributes: the publisher's OAuth\n * app credentials per listing, the site's sealed grant, the connect routes,\n * the plan feature and the two permission keys. Light and client-safe: the\n * console card imports the names, views and keys from here, and nothing here\n * reaches Firestore, a provider or React.\n *\n * Where the data lives, all server-only (no client rule opens any of it):\n *\n * pluginConnectionCredentials/{listingId}__{connectionId}\n * the publisher's OAuth client id and secret, both sealed, keyed by\n * the publishing workspace in `orgId` so its erasure sweeps them;\n * hosts/{hostId}/pluginConnections/{listingId}__{connectionId}\n * a site's grant: sealed tokens, its choices, status, sync times;\n * hosts/{hostId}/pluginConnections/oauth-{hash}\n * a pending connect's single-use state record;\n * hosts/{hostId}/pluginConnections/record-{listingId}__{connectionId}\n * the record a connection's declared sync last wrote (AGL-4192):\n * written only by the sync, read only on the server (the site's page\n * render and the console's routes), never by a client rule.\n *\n * The sync (AGL-4194) runs in the console on the fifteen-minute\n * `plugin-console-crons` tick as the `marketplace-connection-sync` job, and\n * for one connection on \"Sync now\" (`PLUGIN_CONNECTIONS_API_ROUTES.sync`).\n */\n\n/** Top-level collection of the publisher OAuth app credentials, one per listing and connection. */\nexport const PLUGIN_CONNECTION_CREDENTIALS_COLLECTION = 'pluginConnectionCredentials'\n\n/** A site's connections: `hosts/{hostId}/pluginConnections`. */\nexport const PLUGIN_CONNECTIONS_HOST_COLLECTION = 'pluginConnections'\n\n/** The id shared by a listing's credentials and a site's connection: `{listingId}__{connectionId}`. */\nexport function pluginConnectionDocId(listingId: string, connectionId: string): string {\n return `${listingId}__${connectionId}`\n}\n\n/**\n * The id of the record a connection's sync writes, beside the connection in\n * `hosts/{hostId}/pluginConnections` (AGL-4192). The `record-` prefix keeps\n * it apart from the connection (`{listingId}__{connectionId}`) and from a\n * pending connect (`oauth-…`).\n */\nexport function pluginConnectionRecordDocId(listingId: string, connectionId: string): string {\n return `record-${pluginConnectionDocId(listingId, connectionId)}`\n}\n\n/** One value of a record, typed by its declared field (`datetime` is epoch ms, `url` an https string). */\nexport type PluginConnectionRecordValue = string | number | boolean | null\n\n/**\n * The record a connection's declared sync last wrote for one site: the\n * declared summary `fields` and the declared `items`, each holding only the\n * keys the manifest's `sync.record` declares, already capped to its limits.\n * The sync replaces it whole; a site with no successful sync has none.\n */\nexport interface PluginConnectionRecordDoc {\n kind: 'record'\n listingId: string\n connectionId: string\n /** The listing version whose manifest declared the schema this was mapped with. */\n version: string\n /** When the sync that wrote it finished, epoch ms. */\n syncedAtMs: number\n fields: Record<string, PluginConnectionRecordValue>\n items: Array<Record<string, PluginConnectionRecordValue>>\n}\n\n/** The console API paths (served at `/api/<path>`). The callback is registered at providers; never rename it. */\nexport const PLUGIN_CONNECTIONS_API_ROUTES = {\n connectStart: 'plugin-connections/connect/start',\n connectCallback: 'plugin-connections/connect/callback',\n resources: 'plugin-connections/resources',\n choose: 'plugin-connections/choose',\n disconnect: 'plugin-connections/disconnect',\n status: 'plugin-connections/status',\n credentials: 'plugin-connections/credentials',\n /**\n * POST `{ hostId, listingId, connectionId }`: runs the connection's declared\n * sync once and answers `{ connection: PluginConnectionView, synced }`\n * (AGL-4194). Site key and plan, like connect.\n */\n sync: 'plugin-connections/sync',\n /** A site's record of one connection, for the editor's canvas (AGL-4195). */\n record: 'plugin-connections/record',\n} as const\n\n/** The first path segment every route above shares: the plugin's API prefix. */\nexport const PLUGIN_CONNECTIONS_API_PREFIX = 'plugin-connections'\n\n/**\n * A site connection's state.\n *\n * - `connected`: the grant works. `ready` on the view says whether every\n * declared resource has been chosen, which a sync waits for.\n * - `reconnect_required`: the provider refused the grant (revoked, expired,\n * scopes withdrawn); only the site owner connecting again fixes it.\n * - `error`: the last sync or refresh failed for another reason; the next\n * run tries again.\n */\nexport type PluginConnectionStatus = 'connected' | 'reconnect_required' | 'error'\n\n/** One resource the site owner chose: the id the provider gave it and what the picker showed. */\nexport interface PluginConnectionChoice {\n id: string\n label: string\n}\n\n/** What the console may see of a site's connection: never a token, a lease or a secret. */\nexport interface PluginConnectionView {\n listingId: string\n connectionId: string\n provider: string\n status: PluginConnectionStatus\n /** The choices made so far, by resource id. */\n choices: Record<string, PluginConnectionChoice>\n /** Whether every declared resource is chosen. */\n ready: boolean\n scopes: string[]\n connectedAtMs: number\n lastSyncAtMs: number | null\n lastError: string | null\n}\n\n/** One declared connection of a plugin installed on a site, with where it stands. */\nexport interface PluginConnectionStatusEntry {\n listingId: string\n connectionId: string\n provider: string\n label: string\n description?: string\n /** The resources the owner picks, in order. */\n resources: Array<{ id: string; label: string }>\n /** The site's connection, or `null` before one is made. */\n connection: PluginConnectionView | null\n /** Whether the publisher has set the listing's OAuth app credentials. */\n credentialsSet: boolean\n /** Whether the workspace's plan includes connections. */\n planAllows: boolean\n /** Every host this connection's data goes to or comes from ({@link pluginConnectionRecipients}). */\n hosts: string[]\n}\n\n/** Whether a listing's OAuth app credentials are set: the only thing ever read back. */\nexport interface PluginConnectionCredentialsStatus {\n connectionId: string\n label: string\n set: boolean\n updatedAtMs: number | null\n}\n\n/* ------------------------------------------------------------------ */\n/* The plan feature */\n/* ------------------------------------------------------------------ */\n\n/** The plan feature key: connections are on Starter, Pro and Custom, off on Free. */\nexport const PLUGIN_CONNECTIONS_FEATURE = 'pluginConnections'\n\n/** The plan defaults. The retired plans sit above Pro on the ladder, so they keep it. */\nexport const PLUGIN_CONNECTIONS_BY_PLAN: Readonly<Record<OrgPlan, boolean>> = {\n free: false,\n starter: true,\n pro: true,\n business: true,\n scale: true,\n advanced: true,\n agency: true,\n enterprise: true,\n}\n\n/** The feature as the marketplace declares it (`registerPluginEntitlements`). */\nexport const PLUGIN_CONNECTIONS_FEATURE_DECLARATION: PluginFeatureDeclaration = {\n key: PLUGIN_CONNECTIONS_FEATURE,\n label: 'Plugin connections',\n defaultByPlan: PLUGIN_CONNECTIONS_BY_PLAN,\n}\n\n/** What a plan without the feature is told. Names the plans, never a price. */\nexport const PLUGIN_CONNECTIONS_PLAN_REFUSAL =\n 'Connecting a plugin to another service comes with the Starter, Pro and Custom plans.'\n\n/* ------------------------------------------------------------------ */\n/* The permission keys */\n/* ------------------------------------------------------------------ */\n\n/** The site key: connect, choose, disconnect and read a site's plugin connections. */\nexport const PLUGIN_CONNECTIONS_SITE_PERMISSION = 'marketplace.siteConnections'\n\n/** The publisher key: set a listing's OAuth app credentials. */\nexport const PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION = 'marketplace.connectionCredentials'\n\n/** The site Admin (declared beside the marketplace's other site keys). */\nexport const PLUGIN_CONNECTIONS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> =\n MARKETPLACE_CONNECTION_SITE_ROLE_PRESET\n\n/** The site key as the plugin declares it into the org permission catalog. */\nexport const PLUGIN_CONNECTIONS_SITE_PERMISSION_DECLARATION: PluginOrgPermissionDeclaration =\n MARKETPLACE_CONNECTION_SITE_PERMISSIONS[0]\n\n/** The publisher key as the plugin declares it; owners and admins hold it by default. */\nexport const PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION_DECLARATION: PluginPermission =\n MARKETPLACE_PUBLISHER_PERMISSIONS.find((entry) => entry.key === PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION) as PluginPermission\n\n/** The refusal a door answers without a key: names the permission, never a role. */\nexport function pluginConnectionsPermissionRefusal(\n key: typeof PLUGIN_CONNECTIONS_SITE_PERMISSION | typeof PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION,\n): string {\n const label =\n key === PLUGIN_CONNECTIONS_SITE_PERMISSION\n ? PLUGIN_CONNECTIONS_SITE_PERMISSION_DECLARATION.label\n : PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION_DECLARATION.label\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n\n/* ------------------------------------------------------------------ */\n/* Where a listing's connections send data */\n/* ------------------------------------------------------------------ */\n\n/**\n * One declared connection's recipients, derived from its declaration alone\n * (AGL-4194): the hosts the site owner's browser is sent to for consent and\n * the platform calls with the site's grant — the authorization, token and\n * revocation endpoints and every `apiHosts` entry, wildcards as declared.\n * The listing's own list of where data goes, per listing: it is never part\n * of Aglyn's published subprocessor list, because the site owner chooses the\n * provider and connects their own account to it.\n */\nexport interface PluginConnectionRecipient {\n connectionId: string\n provider: string\n label: string\n /** Sorted, each once. */\n hosts: string[]\n}\n\n/** The hosts one declared connection reaches, sorted. */\nexport function pluginConnectionHosts(connection: PluginConnectionDeclaration): string[] {\n return [...new Set([...pluginConnectionEndpointHosts(connection), ...connection.apiHosts])].sort()\n}\n\n/** Each declared connection of a listing version, with the hosts it reaches. */\nexport function pluginConnectionRecipients(\n connections: readonly PluginConnectionDeclaration[],\n): PluginConnectionRecipient[] {\n return connections.map((connection) => ({\n connectionId: connection.id,\n provider: connection.provider,\n label: connection.label,\n hosts: pluginConnectionHosts(connection),\n }))\n}\n"],"names":["pluginConnectionEndpointHosts","MARKETPLACE_PUBLISHER_PERMISSIONS","MARKETPLACE_CONNECTION_SITE_PERMISSIONS","MARKETPLACE_CONNECTION_SITE_ROLE_PRESET","PLUGIN_CONNECTION_CREDENTIALS_COLLECTION","PLUGIN_CONNECTIONS_HOST_COLLECTION","pluginConnectionDocId","listingId","connectionId","pluginConnectionRecordDocId","PLUGIN_CONNECTIONS_API_ROUTES","connectStart","connectCallback","resources","choose","disconnect","status","credentials","sync","record","PLUGIN_CONNECTIONS_API_PREFIX","PLUGIN_CONNECTIONS_FEATURE","PLUGIN_CONNECTIONS_BY_PLAN","free","starter","pro","business","scale","advanced","agency","enterprise","PLUGIN_CONNECTIONS_FEATURE_DECLARATION","key","label","defaultByPlan","PLUGIN_CONNECTIONS_PLAN_REFUSAL","PLUGIN_CONNECTIONS_SITE_PERMISSION","PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION","PLUGIN_CONNECTIONS_SITE_ROLE_PRESET","PLUGIN_CONNECTIONS_SITE_PERMISSION_DECLARATION","PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION_DECLARATION","find","entry","pluginConnectionsPermissionRefusal","pluginConnectionHosts","connection","Set","apiHosts","sort","pluginConnectionRecipients","connections","map","id","provider","hosts"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,6BAA6B,QAExB,4CAA2C;AAKlD,SAASC,iCAAiC,QAAQ,yCAAqC;AACvF,SACEC,uCAAuC,EACvCC,uCAAuC,QAClC,oCAAgC;AAEvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GAED,iGAAiG,GACjG,OAAO,MAAMC,2CAA2C,8BAA6B;AAErF,8DAA8D,GAC9D,OAAO,MAAMC,qCAAqC,oBAAmB;AAErE,qGAAqG,GACrG,OAAO,SAASC,sBAAsBC,SAAiB,EAAEC,YAAoB;IAC3E,OAAO,GAAGD,UAAU,EAAE,EAAEC,cAAc;AACxC;AAEA;;;;;CAKC,GACD,OAAO,SAASC,4BAA4BF,SAAiB,EAAEC,YAAoB;IACjF,OAAO,CAAC,OAAO,EAAEF,s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C;AAC5E;AAuBA,uDAAuD,GACvD,OAAO,SAASW,sBAAsBC,UAAuC;IAC3E,OAAO;WAAI,IAAIC,IAAI;eAAI9C,8BAA8B6C;eAAgBA,WAAWE,QAAQ;SAAC;KAAE,CAACC,IAAI;AAClG;AAEA,8EAA8E,GAC9E,OAAO,SAASC,2BACdC,WAAmD;IAEnD,OAAOA,YAAYC,GAAG,CAAC,CAACN,aAAgB,CAAA;YACtCrC,cAAcqC,WAAWO,EAAE;YAC3BC,UAAUR,WAAWQ,QAAQ;YAC7BpB,OAAOY,WAAWZ,KAAK;YACvBqB,OAAOV,sBAAsBC;QAC/B,CAAA;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/plugin-connections.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n pluginConnectionEndpointHosts,\n type PluginConnectionDeclaration,\n} from '@aglyn/aglyn/app-utils/plugin-connections'\nimport type { HostAccessRole } from '@aglyn/aglyn/foundation/definitions/organization.types'\nimport type { OrgPlan } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport type { PluginFeatureDeclaration, PluginOrgPermissionDeclaration } from '@aglyn/aglyn/plugin-manager/plugin-entitlements'\nimport type { PluginPermission } from '@aglyn/aglyn/plugin-manager/plugin-permissions'\nimport { MARKETPLACE_PUBLISHER_PERMISSIONS } from './marketplace-publisher-permissions'\nimport {\n MARKETPLACE_CONNECTION_SITE_PERMISSIONS,\n MARKETPLACE_CONNECTION_SITE_ROLE_PRESET,\n} from './marketplace-site-permissions'\n\n/*\n * DECLARED CONNECTIONS, THE PLATFORM'S HALF (AGL-4193): THE CONTRACT.\n *\n * A marketplace plugin declares a connection in its manifest\n * (`@aglyn/aglyn/app-utils/plugin-connections`); this plugin, the\n * marketplace, runs it for every plugin it distributes: the publisher's OAuth\n * app credentials per listing, the site's sealed grant, the connect routes,\n * the plan feature and the two permission keys. Light and client-safe: the\n * console card imports the names, views and keys from here, and nothing here\n * reaches Firestore, a provider or React.\n *\n * Where the data lives, all server-only (no client rule opens any of it):\n *\n * pluginConnectionCredentials/{listingId}__{connectionId}\n * the publisher's OAuth client id and secret, both sealed, keyed by\n * the publishing workspace in `orgId` so its erasure sweeps them;\n * hosts/{hostId}/pluginConnections/{listingId}__{connectionId}\n * a site's grant: sealed tokens, its choices, status, sync times;\n * hosts/{hostId}/pluginConnections/oauth-{hash}\n * a pending connect's single-use state record;\n * hosts/{hostId}/pluginConnections/record-{listingId}__{connectionId}\n * the record a connection's declared sync last wrote (AGL-4192):\n * written only by the sync, read only on the server (the site's page\n * render and the console's routes), never by a client rule.\n *\n * The sync (AGL-4194) runs in the console on the fifteen-minute\n * `plugin-console-crons` tick as the `marketplace-connection-sync` job, and\n * for one connection on \"Sync now\" (`PLUGIN_CONNECTIONS_API_ROUTES.sync`).\n */\n\n/** Top-level collection of the publisher OAuth app credentials, one per listing and connection. */\nexport const PLUGIN_CONNECTION_CREDENTIALS_COLLECTION = 'pluginConnectionCredentials'\n\n/** A site's connections: `hosts/{hostId}/pluginConnections`. */\nexport const PLUGIN_CONNECTIONS_HOST_COLLECTION = 'pluginConnections'\n\n/** The id shared by a listing's credentials and a site's connection: `{listingId}__{connectionId}`. */\nexport function pluginConnectionDocId(listingId: string, connectionId: string): string {\n return `${listingId}__${connectionId}`\n}\n\n/**\n * The id of the record a connection's sync writes, beside the connection in\n * `hosts/{hostId}/pluginConnections` (AGL-4192). The `record-` prefix keeps\n * it apart from the connection (`{listingId}__{connectionId}`) and from a\n * pending connect (`oauth-…`).\n */\nexport function pluginConnectionRecordDocId(listingId: string, connectionId: string): string {\n return `record-${pluginConnectionDocId(listingId, connectionId)}`\n}\n\n/** One value of a record, typed by its declared field (`datetime` is epoch ms, `url` an https string). */\nexport type PluginConnectionRecordValue = string | number | boolean | null\n\n/**\n * The record a connection's declared sync last wrote for one site: the\n * declared summary `fields` and the declared `items`, each holding only the\n * keys the manifest's `sync.record` declares, already capped to its limits.\n * The sync replaces it whole; a site with no successful sync has none.\n */\nexport interface PluginConnectionRecordDoc {\n kind: 'record'\n listingId: string\n connectionId: string\n /** The listing version whose manifest declared the schema this was mapped with. */\n version: string\n /** When the sync that wrote it finished, epoch ms. */\n syncedAtMs: number\n fields: Record<string, PluginConnectionRecordValue>\n items: Array<Record<string, PluginConnectionRecordValue>>\n}\n\n/** The console API paths (served at `/api/<path>`). The callback is registered at providers; never rename it. */\nexport const PLUGIN_CONNECTIONS_API_ROUTES = {\n connectStart: 'plugin-connections/connect/start',\n connectCallback: 'plugin-connections/connect/callback',\n resources: 'plugin-connections/resources',\n choose: 'plugin-connections/choose',\n disconnect: 'plugin-connections/disconnect',\n status: 'plugin-connections/status',\n credentials: 'plugin-connections/credentials',\n /**\n * POST `{ hostId, listingId, connectionId }`: runs the connection's declared\n * sync once and answers `{ connection: PluginConnectionView, synced }`\n * (AGL-4194). Site key and plan, like connect.\n */\n sync: 'plugin-connections/sync',\n /** A site's record of one connection, for the editor's canvas (AGL-4195). */\n record: 'plugin-connections/record',\n} as const\n\n/** The first path segment every route above shares: the plugin's API prefix. */\nexport const PLUGIN_CONNECTIONS_API_PREFIX = 'plugin-connections'\n\n/**\n * A site connection's state.\n *\n * - `connected`: the grant works. `ready` on the view says whether every\n * declared resource has been chosen, which a sync waits for.\n * - `reconnect_required`: the provider refused the grant (revoked, expired,\n * scopes withdrawn); only the site owner connecting again fixes it.\n * - `error`: the last sync or refresh failed for another reason; the next\n * run tries again.\n */\nexport type PluginConnectionStatus = 'connected' | 'reconnect_required' | 'error'\n\n/** One resource the site owner chose: the id the provider gave it and what the picker showed. */\nexport interface PluginConnectionChoice {\n id: string\n label: string\n}\n\n/** What the console may see of a site's connection: never a token, a lease or a secret. */\nexport interface PluginConnectionView {\n listingId: string\n connectionId: string\n provider: string\n status: PluginConnectionStatus\n /** The choices made so far, by resource id. */\n choices: Record<string, PluginConnectionChoice>\n /** Whether every declared resource is chosen. */\n ready: boolean\n scopes: string[]\n connectedAtMs: number\n lastSyncAtMs: number | null\n lastError: string | null\n}\n\n/** One declared connection of a plugin installed on a site, with where it stands. */\nexport interface PluginConnectionStatusEntry {\n listingId: string\n connectionId: string\n provider: string\n label: string\n description?: string\n /** The resources the owner picks, in order. */\n resources: Array<{ id: string; label: string }>\n /** The site's connection, or `null` before one is made. */\n connection: PluginConnectionView | null\n /** Whether the publisher has set the listing's OAuth app credentials. */\n credentialsSet: boolean\n /** Whether the workspace's plan includes connections. */\n planAllows: boolean\n /** Every host this connection's data goes to or comes from ({@link pluginConnectionRecipients}). */\n hosts: string[]\n}\n\n/** Whether a listing's OAuth app credentials are set: the only thing ever read back. */\nexport interface PluginConnectionCredentialsStatus {\n connectionId: string\n label: string\n set: boolean\n updatedAtMs: number | null\n}\n\n/* ------------------------------------------------------------------ */\n/* The plan feature */\n/* ------------------------------------------------------------------ */\n\n/** The plan feature key: connections are on Starter, Pro and Custom, off on Free. */\nexport const PLUGIN_CONNECTIONS_FEATURE = 'pluginConnections'\n\n/** The plan defaults. The retired plans sit above Pro on the ladder, so they keep it. */\nexport const PLUGIN_CONNECTIONS_BY_PLAN: Readonly<Record<OrgPlan, boolean>> = {\n free: false,\n starter: true,\n pro: true,\n business: true,\n scale: true,\n advanced: true,\n agency: true,\n enterprise: true,\n}\n\n/** The feature as the marketplace declares it (`registerPluginEntitlements`). */\nexport const PLUGIN_CONNECTIONS_FEATURE_DECLARATION: PluginFeatureDeclaration = {\n key: PLUGIN_CONNECTIONS_FEATURE,\n label: 'Plugin connections',\n defaultByPlan: PLUGIN_CONNECTIONS_BY_PLAN,\n}\n\n/**\n * The plans the feature comes with, as every sentence about it names them: the\n * plans on sale that `PLUGIN_CONNECTIONS_BY_PLAN` turns on. Names, never a\n * price.\n */\nexport const PLUGIN_CONNECTIONS_PLANS = 'the Starter, Pro and Custom plans'\n\n/** What a plan without the feature is told. Names the plans, never a price. */\nexport const PLUGIN_CONNECTIONS_PLAN_REFUSAL =\n `Connecting a plugin to another service comes with ${PLUGIN_CONNECTIONS_PLANS}.`\n\n/**\n * What a shopper reads on a listing whose plugin declares connections, before\n * installing (AGL-4197): the plugin installs on any plan, but connecting it,\n * which is what makes it useful, needs one of these plans. \"Google Business\n * Profile\" → \"Connecting Google Business Profile comes with the Starter, Pro\n * and Custom plans\". Null when nothing is declared.\n */\nexport function pluginConnectionsPlanNote(\n labels: readonly string[],\n): string | null {\n const names = Array.from(\n new Set(labels.map((label) => String(label).trim()).filter(Boolean)),\n )\n if (!names.length) return null\n const joined =\n names.length === 1\n ? names[0]\n : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`\n return `Connecting ${joined} comes with ${PLUGIN_CONNECTIONS_PLANS}`\n}\n\n/* ------------------------------------------------------------------ */\n/* The permission keys */\n/* ------------------------------------------------------------------ */\n\n/** The site key: connect, choose, disconnect and read a site's plugin connections. */\nexport const PLUGIN_CONNECTIONS_SITE_PERMISSION = 'marketplace.siteConnections'\n\n/** The publisher key: set a listing's OAuth app credentials. */\nexport const PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION = 'marketplace.connectionCredentials'\n\n/** The site Admin (declared beside the marketplace's other site keys). */\nexport const PLUGIN_CONNECTIONS_SITE_ROLE_PRESET: Readonly<Record<HostAccessRole, boolean>> =\n MARKETPLACE_CONNECTION_SITE_ROLE_PRESET\n\n/** The site key as the plugin declares it into the org permission catalog. */\nexport const PLUGIN_CONNECTIONS_SITE_PERMISSION_DECLARATION: PluginOrgPermissionDeclaration =\n MARKETPLACE_CONNECTION_SITE_PERMISSIONS[0]\n\n/** The publisher key as the plugin declares it; owners and admins hold it by default. */\nexport const PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION_DECLARATION: PluginPermission =\n MARKETPLACE_PUBLISHER_PERMISSIONS.find((entry) => entry.key === PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION) as PluginPermission\n\n/** The refusal a door answers without a key: names the permission, never a role. */\nexport function pluginConnectionsPermissionRefusal(\n key: typeof PLUGIN_CONNECTIONS_SITE_PERMISSION | typeof PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION,\n): string {\n const label =\n key === PLUGIN_CONNECTIONS_SITE_PERMISSION\n ? PLUGIN_CONNECTIONS_SITE_PERMISSION_DECLARATION.label\n : PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION_DECLARATION.label\n return `Your role does not include \"${label}\" — ask an organization admin`\n}\n\n/* ------------------------------------------------------------------ */\n/* Where a listing's connections send data */\n/* ------------------------------------------------------------------ */\n\n/**\n * One declared connection's recipients, derived from its declaration alone\n * (AGL-4194): the hosts the site owner's browser is sent to for consent and\n * the platform calls with the site's grant — the authorization, token and\n * revocation endpoints and every `apiHosts` entry, wildcards as declared.\n * The listing's own list of where data goes, per listing: it is never part\n * of Aglyn's published subprocessor list, because the site owner chooses the\n * provider and connects their own account to it.\n */\nexport interface PluginConnectionRecipient {\n connectionId: string\n provider: string\n label: string\n /** Sorted, each once. */\n hosts: string[]\n}\n\n/** The hosts one declared connection reaches, sorted. */\nexport function pluginConnectionHosts(connection: PluginConnectionDeclaration): string[] {\n return [...new Set([...pluginConnectionEndpointHosts(connection), ...connection.apiHosts])].sort()\n}\n\n/** Each declared connection of a listing version, with the hosts it reaches. */\nexport function pluginConnectionRecipients(\n connections: readonly PluginConnectionDeclaration[],\n): PluginConnectionRecipient[] {\n return connections.map((connection) => ({\n connectionId: connection.id,\n provider: connection.provider,\n label: connection.label,\n hosts: pluginConnectionHosts(connection),\n }))\n}\n"],"names":["pluginConnectionEndpointHosts","MARKETPLACE_PUBLISHER_PERMISSIONS","MARKETPLACE_CONNECTION_SITE_PERMISSIONS","MARKETPLACE_CONNECTION_SITE_ROLE_PRESET","PLUGIN_CONNECTION_CREDENTIALS_COLLECTION","PLUGIN_CONNECTIONS_HOST_COLLECTION","pluginConnectionDocId","listingId","connectionId","pluginConnectionRecordDocId","PLUGIN_CONNECTIONS_API_ROUTES","connectStart","connectCallback","resources","choose","disconnect","status","credentials","sync","record","PLUGIN_CONNECTIONS_API_PREFIX","PLUGIN_CONNECTIONS_FEATURE","PLUGIN_CONNECTIONS_BY_PLAN","free","starter","pro","business","scale","advanced","agency","enterprise","PLUGIN_CONNECTIONS_FEATURE_DECLARATION","key","label","defaultByPlan","PLUGIN_CONNECTIONS_PLANS","PLUGIN_CONNECTIONS_PLAN_REFUSAL","pluginConnectionsPlanNote","labels","names","Array","from","Set","map","String","trim","filter","Boolean","length","joined","slice","join","PLUGIN_CONNECTIONS_SITE_PERMISSION","PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION","PLUGIN_CONNECTIONS_SITE_ROLE_PRESET","PLUGIN_CONNECTIONS_SITE_PERMISSION_DECLARATION","PLUGIN_CONNECTIONS_CREDENTIALS_PERMISSION_DECLARATION","find","entry","pluginConnectionsPermissionRefusal","pluginConnectionHosts","connection","apiHosts","sort","pluginConnectionRecipients","connections","id","provider","hosts"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,6BAA6B,QAExB,4CAA2C;AAKlD,SAASC,iCAAiC,QAAQ,yCAAqC;AACvF,SACEC,uCAAuC,EACvCC,uCAAuC,QAClC,oCAAgC;AAEvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;CA4BC,GAED,iGAAiG,GACjG,OAAO,MAAMC,2CAA2C,8BAA6B;AAErF,8DAA8D,GAC9D,OAAO,MAAMC,qCAAqC,oBAAmB;AAErE,qGAAqG,GACrG,OAAO,SAASC,sBAAsBC,SAAiB,EAAEC,YAAoB;IAC3E,OAAO,GAAGD,UAAU,EAAE,EAAEC,cAAc;AACxC;AAEA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AK,CAACA,MAAMS,MAAM,GAAG,EAAE,EAAE;IACvE,OAAO,CAAC,WAAW,EAAEC,OAAO,YAAY,EAAEd,0BAA0B;AACtE;AAEA,sEAAsE,GACtE,wEAAwE,GACxE,sEAAsE,GAEtE,oFAAoF,GACpF,OAAO,MAAMiB,qCAAqC,8BAA6B;AAE/E,8DAA8D,GAC9D,OAAO,MAAMC,4CAA4C,oCAAmC;AAE5F,wEAAwE,GACxE,OAAO,MAAMC,sCACXnD,wCAAuC;AAEzC,4EAA4E,GAC5E,OAAO,MAAMoD,iDACXrD,uCAAuC,CAAC,EAAE,CAAA;AAE5C,uFAAuF,GACvF,OAAO,MAAMsD,wDACXvD,kCAAkCwD,IAAI,CAAC,CAACC,QAAUA,MAAM1B,GAAG,KAAKqB,2CAA8D;AAEhI,kFAAkF,GAClF,OAAO,SAASM,mCACd3B,GAAiG;IAEjG,MAAMC,QACJD,QAAQoB,qCACJG,+CAA+CtB,KAAK,GACpDuB,sDAAsDvB,KAAK;IACjE,OAAO,CAAC,4BAA4B,EAAEA,MAAM,6BAA6B,CAAC;AAC5E;AAuBA,uDAAuD,GACvD,OAAO,SAAS2B,sBAAsBC,UAAuC;IAC3E,OAAO;WAAI,IAAInB,IAAI;eAAI1C,8BAA8B6D;eAAgBA,WAAWC,QAAQ;SAAC;KAAE,CAACC,IAAI;AAClG;AAEA,8EAA8E,GAC9E,OAAO,SAASC,2BACdC,WAAmD;IAEnD,OAAOA,YAAYtB,GAAG,CAAC,CAACkB,aAAgB,CAAA;YACtCrD,cAAcqD,WAAWK,EAAE;YAC3BC,UAAUN,WAAWM,QAAQ;YAC7BlC,OAAO4B,WAAW5B,KAAK;YACvBmC,OAAOR,sBAAsBC;QAC/B,CAAA;AACF"}
|
|
@@ -1177,6 +1177,8 @@ async function handler(request) {
|
|
|
1177
1177
|
const listing = listingSnapshot.data();
|
|
1178
1178
|
const sha256 = String((_versionSnapshot_get1 = versionSnapshot.get('sha256')) != null ? _versionSnapshot_get1 : '');
|
|
1179
1179
|
const approving = action === 'approve-version';
|
|
1180
|
+
// Read before the verdict write clears it (AGL-4121, below).
|
|
1181
|
+
const hadRealmTrust = Boolean(versionSnapshot.get('trust'));
|
|
1180
1182
|
if (approving) {
|
|
1181
1183
|
const outstanding = outstandingChecklistItems(versionSnapshot.get('reviewChecklist'), sha256);
|
|
1182
1184
|
if (outstanding.length) {
|
|
@@ -1245,6 +1247,13 @@ async function handler(request) {
|
|
|
1245
1247
|
}), {
|
|
1246
1248
|
merge: true
|
|
1247
1249
|
});
|
|
1250
|
+
// Withdrawn realm trust changes what loads on every site running this
|
|
1251
|
+
// version, and the tenant resolves trust once per site and caches it
|
|
1252
|
+
// with the page (AGL-4121). Only when there was trust to withdraw: a
|
|
1253
|
+
// rejection of an unsigned version changes nothing a site loads.
|
|
1254
|
+
if (!approving && hadRealmTrust) {
|
|
1255
|
+
await dropCachesForListing(firestore, listingId);
|
|
1256
|
+
}
|
|
1248
1257
|
// A plugin with its first approved version becomes browsable. Later
|
|
1249
1258
|
// approvals never change listing status — that is the point: an
|
|
1250
1259
|
// update is reviewed without disturbing what customers already have.
|