@aglyn/plugins-marketplace 1.19.0 → 1.20.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/hooks/use-marketplace-actions.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'use client'\n\nimport { lockdownRefusalText, parseLockdownRefusal } from '@aglyn/aglyn'\nimport { useLoading } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useCallback } from 'react'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n type InstallPlanStep,\n listingArtifactType,\n} from '../model/marketplace'\nimport {\n installPlanOutcome,\n marketplaceInstallEndpoint,\n marketplaceLandingMessage,\n} from '../model/marketplace-catalog'\nimport { useMarketplacePay } from './use-marketplace-pay'\n\n\n/**\n * What to tell someone whose install will never be three-way mergeable\n * (AGL-2339).\n *\n * Every install route returns `baseStored`, and `provenance.ts` says what a\n * false one means: *\"a snapshot that cannot be written leaves `baseStored:\n * false` and an artifact that reports itself as not updatable\"*. It reported\n * it to NOBODY — zero `.tsx` readers across all seven routes.\n *\n * The consequence is silent and expensive. `hasDivergedFromBase` needs the\n * base snapshot to tell the publisher's change from the user's; without one\n * an update can only overwrite. So a user who customizes a large artifact —\n * one whose content exceeded `ARTIFACT_BASE_MAX_BYTES`, or whose snapshot\n * write failed — LOSES those changes on the next update, having been told\n * nothing at install time. The update dialog does explain itself when the\n * moment arrives (`preview.mergeable` renders `preview.reason`), but by then\n * the choice is take-the-update-or-stay-behind, not \"keep a copy first\".\n *\n * Persistent rather than a timed toast: it is advice to act on before\n * editing, and it is the only moment this is knowable in advance.\n */\nfunction baseMissingWarning(displayName: string): string {\n return (\n `\"${displayName}\" is too large to keep a reference copy of, so a future ` +\n 'update will REPLACE it rather than merge. Export or note any changes ' +\n 'you make to it.'\n )\n}\n\n/**\n * Shared install/buy handlers for marketplace listings (AGL-95): used by the\n * browse grid and the listing detail page. Install copies the pinned\n * version snapshot server-side (/api/marketplace/install); buy pays in the\n * console (/api/marketplace/pay), in the `payPanel` the surface draws under\n * its button.\n *\n * @param billingHref the workspace's Billing page, for a prerequisite the\n * buyer cannot meet themselves.\n */\nexport function useMarketplaceActions(\n hostId: string,\n orgId?: string | null,\n billingHref?: string | null,\n) {\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { queueLoading } = useLoading()\n const pay = useMarketplacePay({ orgId, hostId, billingHref })\n\n // `scope` is only meaningful for artifact types that HAVE an org-scoped\n // pin — see INSTALL_TARGETS. Passing it for a template would be ignored\n // server-side, so callers ask the model rather than guessing.\n const install = useCallback(\n async (\n listing: any,\n scope?: 'org' | 'host',\n options?: {\n /**\n * Called instead of an error toast when the install route refuses\n * because the workspace's copy has been EDITED since it was installed\n * (AGL-1018's 409, AGL-1034).\n *\n * The refusal is correct — that install would have destroyed their\n * work — but \"review the update\" is only useful advice if something\n * offers the review. Handling it here rather than at each call site\n * means every surface that installs a copied artifact gets the\n * recovery, including ones written later.\n */\n onDiverged?: () => void\n },\n ) => {\n const dequeue = queueLoading()\n try {\n const artifactType = listingArtifactType(listing)\n const endpoint = marketplaceInstallEndpoint(artifactType)\n const response = await authorizedFetch(user, `/api/${endpoint}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n listingId: listing.$id,\n hostId,\n ...(scope ? { scope } : {}),\n }),\n })\n const payload = await response.json()\n if (!response.ok) {\n // The copy has diverged: hand it to the review rather than telling\n // someone to review something they cannot reach from here.\n if (payload?.diverged && options?.onDiverged) {\n return void options.onDiverged()\n }\n // An installs feature lockdown (AGL-1510/1532): \"Install failed\"\n // reads as a broken listing — the very thing an incident response\n // needs people NOT to conclude while a suspect listing is under\n // investigation. The server says installs are paused; say that.\n const locked = parseLockdownRefusal(response.status, payload)\n if (locked) {\n return void enqueueSnackbar(lockdownRefusalText(locked), {\n variant: 'warning',\n persist: true,\n })\n }\n return void enqueueSnackbar(payload?.error ?? 'Install failed', {\n variant: response.status === 402 ? 'warning' : 'error',\n allowDuplicate: true,\n })\n }\n // Types that land inert must not read as \"your site changed\".\n const landed = marketplaceLandingMessage(artifactType, listing.displayName)\n enqueueSnackbar(\n landed ??\n (payload.updated\n ? `Updated \"${listing.displayName}\" to v${payload.version}`\n : `Installed \"${listing.displayName}\" — find it under Your components`),\n { variant: 'success', persist: false },\n )\n // No base snapshot: this copy can never be three-way merged, and a\n // future update will overwrite whatever the user does to it. The\n // route has always said so on the wire; nothing listened (AGL-2339).\n //\n // `=== false` rather than a falsy test: a route that omitted the\n // field entirely has told us nothing, and warning on silence would\n // put a scary, unactionable message on every install from any\n // endpoint that had not been updated yet.\n if (payload.baseStored === false) {\n enqueueSnackbar(baseMissingWarning(listing.displayName), {\n variant: 'warning',\n persist: true,\n })\n }\n /**\n * What was, and was not, checked about an email somebody else wrote.\n *\n * Said HERE because this is the moment the design enters the\n * workspace, and because the two facts are the ones a sender cannot\n * recover afterwards by looking at the design. `unreviewed` is the\n * ordinary case — email starters are auto-listed like every other\n * copied artifact — so the sentence has to be a statement rather than\n * an alarm, and it must never be silence: an install that said nothing\n * would be read as a review that happened.\n *\n * The link hosts are the inspectable half of the link policy. The\n * remote-asset rule is mechanical and the route enforces it, but where\n * a template points a tenant's own customers is a judgment only the\n * tenant can make, and they can only make it if they are shown the\n * list.\n */\n if (payload.assurance) {\n const hosts: string[] = payload.linkHosts ?? []\n enqueueSnackbar(\n (payload.assurance === 'approved'\n ? 'Reviewed by Aglyn. '\n : 'Nobody at Aglyn has reviewed this design. ') +\n (hosts.length\n ? `It links to ${hosts.join(', ')}. `\n : 'It links nowhere outside your site. ') +\n 'Read it before you send from it.',\n { variant: 'info', persist: true },\n )\n }\n // A media reference that still resolves against the publisher's own\n // library — served by our CDN, so no third party learns who opened the\n // mail, but the picture behind it is still theirs to change.\n if (payload.foreignMediaScopes?.length) {\n enqueueSnackbar(\n 'Some images in this email are still served from the publisher’s ' +\n 'own media library, so they can change after you install. ' +\n 'Replace them with your own to pin them.',\n { variant: 'info', persist: false },\n )\n }\n // A schema whose reference fields couldn't be relinked installs with\n // those fields degraded to text — silently changing a field's type\n // would be the kind of thing you discover much later (AGL-657).\n if (payload.degradedFieldIds?.length) {\n enqueueSnackbar(\n `${payload.degradedFieldIds.length} reference field(s) became ` +\n 'plain text — the datasets they pointed at are not in this ' +\n 'organization.',\n { variant: 'info', persist: false },\n )\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n dequeue()\n }\n },\n [user, hostId, queueLoading, enqueueSnackbar],\n )\n\n /**\n * Fans an install-targeting plan out to the install routes (AGL-773). Each\n * step is either a single org pin or a host pin on a named site; org steps\n * resolve the org from the acting `hostId`. One summary snackbar reports the\n * whole plan rather than N toasts. Use `resolveInstallPlan` (model) to turn\n * an All-sites / Selected-sites choice into these steps.\n */\n const installPlan = useCallback(\n async (\n listing: any,\n steps: readonly InstallPlanStep[],\n options?: {\n /**\n * Re-pinning something already installed (AGL-1017). Only the wording\n * changes — the route is the same, because moving a pin forward IS\n * installing — but \"Installed on 1 site\" is the wrong sentence to read\n * after pressing Update.\n */\n intent?: 'install' | 'update'\n /** The version being moved to, for the update summary. */\n version?: string | number | null\n },\n ) => {\n if (!steps.length) return\n const dequeue = queueLoading()\n try {\n const artifactType = listingArtifactType(listing)\n const endpoint = marketplaceInstallEndpoint(artifactType)\n let installed = 0\n const errors: string[] = []\n /**\n * Surfaced separately from success (AGL-1017/429): the pin is written\n * either way — it is an explicit choice — but a bundle built for a\n * different host ABI will not load, and a green \"Updated\" toast alone\n * would leave the workspace believing it did.\n */\n const abiWarnings = new Set<string>()\n /**\n * Sites whose copy landed with no base snapshot (AGL-2339). Counted\n * rather than toasted per step: the fan-out installs the SAME\n * artifact everywhere, so the answer is the same on every site and N\n * identical warnings would read as N different problems.\n */\n let withoutBase = 0\n /**\n * A feature lockdown refuses every step identically (AGL-1532), so\n * the fan-out stops at the first one and says \"installs are paused\"\n * ONCE. N identical refusals stacked into the error summary would\n * read as N broken sites — the opposite of what the lock is saying.\n */\n let lockedNotice: ReturnType<typeof parseLockdownRefusal> = null\n for (const step of steps) {\n // Org steps still need a host to resolve the org server-side, so\n // fall back to the acting host; host steps target their own site.\n const targetHostId = step.scope === 'host' ? step.hostId : hostId\n const response = await authorizedFetch(user, `/api/${endpoint}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n listingId: listing.$id,\n hostId: targetHostId,\n ...(step.scope === 'org' ? { scope: 'org' } : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n if (response.ok) {\n installed += 1\n if (payload?.hostAbiWarning) {\n abiWarnings.add(String(payload.hostAbiWarning))\n }\n if (payload?.baseStored === false) withoutBase += 1\n } else {\n lockedNotice = parseLockdownRefusal(response.status, payload)\n if (lockedNotice) break\n errors.push(payload?.error ?? 'Install failed')\n }\n }\n if (lockedNotice) {\n enqueueSnackbar(lockdownRefusalText(lockedNotice), {\n variant: 'warning',\n persist: true,\n })\n // Whatever landed before the lock DID land — saying so is the\n // difference between \"nothing happened\" and a half-applied plan\n // the workspace would otherwise discover much later.\n if (installed) {\n enqueueSnackbar(\n `${installed} site(s) were already updated before the pause.`,\n { variant: 'info', persist: false },\n )\n }\n return\n }\n const outcome = installPlanOutcome({\n name: listing.displayName,\n installed,\n errors,\n orgWide: steps.some((step) => step.scope === 'org'),\n updating: options?.intent === 'update',\n version: options?.version != null ? String(options.version) : null,\n saved: Boolean(marketplaceLandingMessage(artifactType, '')),\n })\n enqueueSnackbar(\n outcome.text,\n outcome.tone === 'success'\n ? { variant: 'success', persist: false }\n : { variant: outcome.tone, allowDuplicate: true },\n )\n for (const warning of abiWarnings) {\n enqueueSnackbar(warning, { variant: 'warning', allowDuplicate: true })\n }\n if (withoutBase) {\n enqueueSnackbar(baseMissingWarning(listing.displayName), {\n variant: 'warning',\n persist: true,\n })\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n dequeue()\n }\n },\n [user, hostId, queueLoading, enqueueSnackbar],\n )\n\n const buy = useCallback(\n async (listing: any) => {\n const name = String(listing.displayName ?? 'This listing')\n const { outcome, error, locked } = await pay.buy({\n listingId: String(listing.$id),\n displayName: listing.displayName,\n })\n if (outcome === 'paid') {\n return void enqueueSnackbar(`Bought \"${name}\". It is yours to install.`, {\n variant: 'success',\n persist: false,\n })\n }\n if (outcome === 'owned') {\n return void enqueueSnackbar(`This organization already owns \"${name}\".`, {\n variant: 'info',\n persist: false,\n })\n }\n if (outcome === 'pending') {\n return void enqueueSnackbar(\n `Your payment for \"${name}\" is going through. It is yours as soon as it clears.`,\n { variant: 'info', persist: false },\n )\n }\n // A lockdown is a pause to read, and it must not vanish unread (AGL-1532).\n if (error) {\n enqueueSnackbar(\n error,\n locked ? { variant: 'warning', persist: true } : { variant: 'error', allowDuplicate: true },\n )\n }\n },\n [pay.buy, enqueueSnackbar],\n )\n\n /**\n * Uninstall a plugin listing from the listing detail (AGL-881) — the same\n * `action:'uninstall'` the installed add-ons card uses, so it removes the\n * pin (and the switchboard entry when nothing else pins it) and decrements\n * activeInstalls. Only plugins have a removable pin; other artifact types\n * land in a library and have nothing to uninstall.\n */\n const uninstall = useCallback(\n async (\n listing: any,\n scope?: 'org' | 'host',\n // Which site's pin to drop (AGL-997). Without this the call always\n // targeted the acting host, so at org scope \"uninstall\" could only\n // mean \"the whole org pin\" or \"whichever site happened to be acting\"\n // — removing the plugin from ONE of several sites was unreachable.\n targetHostId?: string,\n ) => {\n const dequeue = queueLoading()\n try {\n const response = await authorizedFetch(\n user,\n '/api/marketplace/install-plugin',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n listingId: listing.$id,\n hostId: targetHostId ?? hostId,\n action: 'uninstall',\n ...(scope ? { scope } : {}),\n }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n // Uninstall rides the install-plugin route, so an installs lock\n // refuses it too (AGL-1532) — and \"Uninstall failed\" during an\n // incident is exactly the wrong sentence for someone trying to\n // remove the listing under investigation.\n const locked = parseLockdownRefusal(response.status, payload)\n if (locked) {\n return void enqueueSnackbar(lockdownRefusalText(locked), {\n variant: 'warning',\n persist: true,\n })\n }\n return void enqueueSnackbar(payload?.error ?? 'Uninstall failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n enqueueSnackbar(`Removed \"${listing.displayName}\"`, {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n dequeue()\n }\n },\n [user, hostId, queueLoading, enqueueSnackbar],\n )\n\n return { install, installPlan, buy, uninstall, payPanel: pay.panel, buying: pay.busy }\n}\n\nexport default useMarketplaceActions\n"],"names":["lockdownRefusalText","parseLockdownRefusal","useLoading","useSnackbar","useCallback","useUser","authorizedFetch","listingArtifactType","installPlanOutcome","marketplaceInstallEndpoint","marketplaceLandingMessage","useMarketplacePay","baseMissingWarning","displayName","useMarketplaceActions","hostId","orgId","billingHref","data","user","enqueueSnackbar","queueLoading","pay","install","listing","scope","options","dequeue","payload","artifactType","endpoint","response","method","headers","body","JSON","stringify","listingId","$id","json","ok","diverged","onDiverged","locked","status","variant","persist","error","allowDuplicate","landed","updated","version","baseStored","assurance","hosts","linkHosts","length","join","foreignMediaScopes","degradedFieldIds","console","installPlan","steps","installed","errors","abiWarnings","Set","withoutBase","lockedNotice","step","targetHostId","catch","hostAbiWarning","add","String","push","outcome","name","orgWide","some","updating","intent","saved","Boolean","text","tone","warning","buy","uninstall","action","payPanel","panel","buying","busy"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;AAEA,SAASA,mBAAmB,EAAEC,oBAAoB,QAAQ,eAAc;AACxE,SAASC,UAAU,QAAQ,uBAAsB;AACjD,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,WAAW,QAAQ,QAAO;AACnC,SAASC,OAAO,QAAQ,iCAAgC;AACxD,SAASC,eAAe,QAAQ,2CAA0C;AAC1E,SAEEC,mBAAmB,QACd,0BAAsB;AAC7B,SACEC,kBAAkB,EAClBC,0BAA0B,EAC1BC,yBAAyB,QACpB,kCAA8B;AACrC,SAASC,iBAAiB,QAAQ,2BAAuB;AAGzD;;;;;;;;;;;;;;;;;;;;CAoBC,GACD,SAASC,mBAAmBC,WAAmB;IAC7C,OACE,CAAC,CAAC,EAAEA,YAAY,wDAAwD,CAAC,GACzE,0EACA;AAEJ;AAEA;;;;;;;;;CASC,GACD,OAAO,SAASC,sBACdC,MAAc,EACdC,KAAqB,EACrBC,WAA2B;IAE3B,MAAM,EAAEC,MAAMC,IAAI,EAAE,GAAGd;IACvB,MAAM,EAAEe,eAAe,EAAE,GAAGjB;IAC5B,MAAM,EAAEkB,YAAY,EAAE,GAAGnB;IACzB,MAAMoB,MAAMX,kBAAkB;QAAEK;QAAOD;QAAQE;IAAY;IAE3D,wEAAwE;IACxE,wEAAwE;IACxE,8DAA8D;IAC9D,MAAMM,UAAUnB,YACd,OACEoB,SACAC,OACAC;QAeA,MAAMC,UAAUN;QAChB,IAAI;gBA2FEO,6BAWAA;YArGJ,MAAMC,eAAetB,oBAAoBiB;YACzC,MAAMM,WAAWrB,2BAA2BoB;YAC5C,MAAME,WAAW,MAA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,CAAC,IAAO,CAAA,CAAC,CAAA;YACpD,IAAI,CAACxC,SAASS,EAAE,EAAE;;gBAChB,gEAAgE;gBAChE,+DAA+D;gBAC/D,+DAA+D;gBAC/D,0CAA0C;gBAC1C,MAAMG,SAAS1C,qBAAqB8B,SAASa,MAAM,EAAEhB;gBACrD,IAAIe,QAAQ;oBACV,OAAO,KAAKvB,gBAAgBpB,oBAAoB2C,SAAS;wBACvDE,SAAS;wBACTC,SAAS;oBACX;gBACF;gBACA,OAAO,KAAK1B,wBAAgBQ,2BAAAA,QAASmB,KAAK,mBAAI,oBAAoB;oBAChEF,SAAS;oBACTG,gBAAgB;gBAClB;YACF;YACA5B,gBAAgB,CAAC,SAAS,EAAEI,QAAQX,WAAW,CAAC,CAAC,CAAC,EAAE;gBAClDgC,SAAS;gBACTC,SAAS;YACX;QACF,EAAE,OAAOC,OAAO;YACda,QAAQb,KAAK,CAACA;YACd3B,gBAAgB,yBAAyB;gBACvCyB,SAAS;gBACTG,gBAAgB;YAClB;QACF,SAAU;YACRrB;QACF;IACF,GACA;QAACR;QAAMJ;QAAQM;QAAcD;KAAgB;IAG/C,OAAO;QAAEG;QAASsC;QAAa0B;QAAKC;QAAWE,UAAUpE,IAAIqE,KAAK;QAAEC,QAAQtE,IAAIuE,IAAI;IAAC;AACvF;AAEA,eAAe/E,sBAAqB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/hooks/use-marketplace-actions.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'use client'\n\nimport { lockdownRefusalText, parseLockdownRefusal } from '@aglyn/aglyn'\nimport { useLoading } from '@aglyn/shared-ui-jsx'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { useCallback } from 'react'\nimport { useUser } from '@aglyn/tenant-feature-instance'\nimport { authorizedFetch } from '@aglyn/shared-util-http/authorized-token'\nimport {\n type InstallPlanStep,\n listingArtifactType,\n} from '../model/marketplace'\nimport {\n installPlanOutcome,\n marketplaceInstallEndpoint,\n marketplaceLandingMessage,\n} from '../model/marketplace-catalog'\nimport { useMarketplacePay } from './use-marketplace-pay'\n\n\n/**\n * What to tell someone whose install will never be three-way mergeable\n * (AGL-2339).\n *\n * Every install route returns `baseStored`, and `provenance.ts` says what a\n * false one means: *\"a snapshot that cannot be written leaves `baseStored:\n * false` and an artifact that reports itself as not updatable\"*. It reported\n * it to NOBODY — zero `.tsx` readers across all seven routes.\n *\n * The consequence is silent and expensive. `hasDivergedFromBase` needs the\n * base snapshot to tell the publisher's change from the user's; without one\n * an update can only overwrite. So a user who customizes a large artifact —\n * one whose content exceeded `ARTIFACT_BASE_MAX_BYTES`, or whose snapshot\n * write failed — LOSES those changes on the next update, having been told\n * nothing at install time. The update dialog does explain itself when the\n * moment arrives (`preview.mergeable` renders `preview.reason`), but by then\n * the choice is take-the-update-or-stay-behind, not \"keep a copy first\".\n *\n * Persistent rather than a timed toast: it is advice to act on before\n * editing, and it is the only moment this is knowable in advance.\n */\nfunction baseMissingWarning(displayName: string): string {\n return (\n `\"${displayName}\" is too large to keep a reference copy of, so a future ` +\n 'update will REPLACE it rather than merge. Export or note any changes ' +\n 'you make to it.'\n )\n}\n\n/**\n * Shared install/buy handlers for marketplace listings (AGL-95): used by the\n * browse grid and the listing detail page. Install copies the pinned\n * version snapshot server-side (/api/marketplace/install); buy pays in the\n * console (/api/marketplace/pay), in the `payPanel` the surface draws under\n * its button.\n *\n * @param billingHref the workspace's Billing page, for a prerequisite the\n * buyer cannot meet themselves.\n */\nexport function useMarketplaceActions(\n hostId: string,\n orgId?: string | null,\n billingHref?: string | null,\n) {\n const { data: user } = useUser()\n const { enqueueSnackbar } = useSnackbar()\n const { queueLoading } = useLoading()\n const pay = useMarketplacePay({ orgId, hostId, billingHref })\n\n // `scope` is only meaningful for artifact types that HAVE an org-scoped\n // pin — see INSTALL_TARGETS. Passing it for a template would be ignored\n // server-side, so callers ask the model rather than guessing.\n const install = useCallback(\n async (\n listing: any,\n scope?: 'org' | 'host',\n options?: {\n /**\n * Called instead of an error toast when the install route refuses\n * because the workspace's copy has been EDITED since it was installed\n * (AGL-1018's 409, AGL-1034).\n *\n * The refusal is correct — that install would have destroyed their\n * work — but \"review the update\" is only useful advice if something\n * offers the review. Handling it here rather than at each call site\n * means every surface that installs a copied artifact gets the\n * recovery, including ones written later.\n */\n onDiverged?: () => void\n },\n ) => {\n const dequeue = queueLoading()\n try {\n const artifactType = listingArtifactType(listing)\n const endpoint = marketplaceInstallEndpoint(artifactType)\n const response = await authorizedFetch(user, `/api/${endpoint}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n listingId: listing.$id,\n hostId,\n ...(scope ? { scope } : {}),\n }),\n })\n const payload = await response.json()\n if (!response.ok) {\n // The copy has diverged: hand it to the review rather than telling\n // someone to review something they cannot reach from here.\n if (payload?.diverged && options?.onDiverged) {\n return void options.onDiverged()\n }\n // An installs feature lockdown (AGL-1510/1532): \"Install failed\"\n // reads as a broken listing — the very thing an incident response\n // needs people NOT to conclude while a suspect listing is under\n // investigation. The server says installs are paused; say that.\n const locked = parseLockdownRefusal(response.status, payload)\n if (locked) {\n return void enqueueSnackbar(lockdownRefusalText(locked), {\n variant: 'warning',\n persist: true,\n })\n }\n return void enqueueSnackbar(payload?.error ?? 'Install failed', {\n variant: response.status === 402 ? 'warning' : 'error',\n allowDuplicate: true,\n })\n }\n // Types that land inert must not read as \"your site changed\".\n const landed = marketplaceLandingMessage(artifactType, listing.displayName)\n enqueueSnackbar(\n landed ??\n (payload.updated\n ? `Updated \"${listing.displayName}\" to v${payload.version}`\n : `Installed \"${listing.displayName}\" — find it under Your components`),\n { variant: 'success', persist: false },\n )\n // No base snapshot: this copy can never be three-way merged, and a\n // future update will overwrite whatever the user does to it. The\n // route has always said so on the wire; nothing listened (AGL-2339).\n //\n // `=== false` rather than a falsy test: a route that omitted the\n // field entirely has told us nothing, and warning on silence would\n // put a scary, unactionable message on every install from any\n // endpoint that had not been updated yet.\n if (payload.baseStored === false) {\n enqueueSnackbar(baseMissingWarning(listing.displayName), {\n variant: 'warning',\n persist: true,\n })\n }\n /**\n * What was, and was not, checked about an email somebody else wrote.\n *\n * Said HERE because this is the moment the design enters the\n * workspace, and because the two facts are the ones a sender cannot\n * recover afterwards by looking at the design. `unreviewed` is the\n * ordinary case — email starters are auto-listed like every other\n * copied artifact — so the sentence has to be a statement rather than\n * an alarm, and it must never be silence: an install that said nothing\n * would be read as a review that happened.\n *\n * The link hosts are the inspectable half of the link policy. The\n * remote-asset rule is mechanical and the route enforces it, but where\n * a template points a tenant's own customers is a judgment only the\n * tenant can make, and they can only make it if they are shown the\n * list.\n */\n if (payload.assurance) {\n const hosts: string[] = payload.linkHosts ?? []\n enqueueSnackbar(\n (payload.assurance === 'approved'\n ? 'Reviewed by Aglyn. '\n : 'Nobody at Aglyn has reviewed this design. ') +\n (hosts.length\n ? `It links to ${hosts.join(', ')}. `\n : 'It links nowhere outside your site. ') +\n 'Read it before you send from it.',\n { variant: 'info', persist: true },\n )\n }\n // A media reference that still resolves against the publisher's own\n // library — served by our CDN, so no third party learns who opened the\n // mail, but the picture behind it is still theirs to change.\n if (payload.foreignMediaScopes?.length) {\n enqueueSnackbar(\n 'Some images in this email are still served from the publisher’s ' +\n 'own media library, so they can change after you install. ' +\n 'Replace them with your own to pin them.',\n { variant: 'info', persist: false },\n )\n }\n // A schema whose reference fields couldn't be relinked installs with\n // those fields degraded to text — silently changing a field's type\n // would be the kind of thing you discover much later (AGL-657).\n if (payload.degradedFieldIds?.length) {\n enqueueSnackbar(\n `${payload.degradedFieldIds.length} reference field(s) became ` +\n 'plain text — the datasets they pointed at are not in this ' +\n 'organization.',\n { variant: 'info', persist: false },\n )\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n dequeue()\n }\n },\n [user, hostId, queueLoading, enqueueSnackbar],\n )\n\n /**\n * Fans an install-targeting plan out to the install routes (AGL-773). Each\n * step is either a single org pin or a host pin on a named site; org steps\n * resolve the org from the acting `hostId`. One summary snackbar reports the\n * whole plan rather than N toasts. Use `resolveInstallPlan` (model) to turn\n * an All-sites / Selected-sites choice into these steps.\n */\n const installPlan = useCallback(\n async (\n listing: any,\n steps: readonly InstallPlanStep[],\n options?: {\n /**\n * Re-pinning something already installed (AGL-1017). Only the wording\n * changes — the route is the same, because moving a pin forward IS\n * installing — but \"Installed on 1 site\" is the wrong sentence to read\n * after pressing Update.\n */\n intent?: 'install' | 'update'\n /** The version being moved to, for the update summary. */\n version?: string | number | null\n },\n ) => {\n if (!steps.length) return\n const dequeue = queueLoading()\n try {\n const artifactType = listingArtifactType(listing)\n const endpoint = marketplaceInstallEndpoint(artifactType)\n let installed = 0\n const errors: string[] = []\n /**\n * Surfaced separately from success (AGL-1017/429): the pin is written\n * either way — it is an explicit choice — but a bundle built for a\n * different host ABI will not load, and a green \"Updated\" toast alone\n * would leave the workspace believing it did.\n */\n const abiWarnings = new Set<string>()\n /**\n * Sites whose copy landed with no base snapshot (AGL-2339). Counted\n * rather than toasted per step: the fan-out installs the SAME\n * artifact everywhere, so the answer is the same on every site and N\n * identical warnings would read as N different problems.\n */\n let withoutBase = 0\n /** Sites the org-wide pin left out, as the route wrote them (AGL-4047). */\n let leftOut = 0\n /**\n * A feature lockdown refuses every step identically (AGL-1532), so\n * the fan-out stops at the first one and says \"installs are paused\"\n * ONCE. N identical refusals stacked into the error summary would\n * read as N broken sites — the opposite of what the lock is saying.\n */\n let lockedNotice: ReturnType<typeof parseLockdownRefusal> = null\n for (const step of steps) {\n // Org steps still need a host to resolve the org server-side, so\n // fall back to the acting host; host steps target their own site.\n const targetHostId = step.scope === 'host' ? step.hostId : hostId\n const response = await authorizedFetch(user, `/api/${endpoint}`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n listingId: listing.$id,\n hostId: targetHostId,\n ...(step.scope === 'org' ? { scope: 'org' } : {}),\n // \"All sites except…\" (AGL-4047): the route leaves these sites\n // out before it writes the workspace's pin.\n ...(step.scope === 'org' && step.exceptHostIds?.length\n ? {\n runsOn: {\n mode: 'allExcept',\n exceptHostIds: [...step.exceptHostIds],\n },\n }\n : {}),\n }),\n })\n const payload = await response.json().catch(() => ({}))\n if (response.ok) {\n installed += 1\n if (payload?.hostAbiWarning) {\n abiWarnings.add(String(payload.hostAbiWarning))\n }\n if (payload?.baseStored === false) withoutBase += 1\n if (Array.isArray(payload?.leftOutHostIds)) {\n leftOut += payload.leftOutHostIds.length\n }\n } else {\n lockedNotice = parseLockdownRefusal(response.status, payload)\n if (lockedNotice) break\n errors.push(payload?.error ?? 'Install failed')\n }\n }\n if (lockedNotice) {\n enqueueSnackbar(lockdownRefusalText(lockedNotice), {\n variant: 'warning',\n persist: true,\n })\n // Whatever landed before the lock DID land — saying so is the\n // difference between \"nothing happened\" and a half-applied plan\n // the workspace would otherwise discover much later.\n if (installed) {\n enqueueSnackbar(\n `${installed} site(s) were already updated before the pause.`,\n { variant: 'info', persist: false },\n )\n }\n return\n }\n const outcome = installPlanOutcome({\n name: listing.displayName,\n installed,\n errors,\n orgWide: steps.some((step) => step.scope === 'org'),\n updating: options?.intent === 'update',\n version: options?.version != null ? String(options.version) : null,\n saved: Boolean(marketplaceLandingMessage(artifactType, '')),\n leftOut,\n })\n enqueueSnackbar(\n outcome.text,\n outcome.tone === 'success'\n ? { variant: 'success', persist: false }\n : { variant: outcome.tone, allowDuplicate: true },\n )\n for (const warning of abiWarnings) {\n enqueueSnackbar(warning, { variant: 'warning', allowDuplicate: true })\n }\n if (withoutBase) {\n enqueueSnackbar(baseMissingWarning(listing.displayName), {\n variant: 'warning',\n persist: true,\n })\n }\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n dequeue()\n }\n },\n [user, hostId, queueLoading, enqueueSnackbar],\n )\n\n const buy = useCallback(\n async (listing: any) => {\n const name = String(listing.displayName ?? 'This listing')\n const { outcome, error, locked } = await pay.buy({\n listingId: String(listing.$id),\n displayName: listing.displayName,\n })\n if (outcome === 'paid') {\n return void enqueueSnackbar(`Bought \"${name}\". It is yours to install.`, {\n variant: 'success',\n persist: false,\n })\n }\n if (outcome === 'owned') {\n return void enqueueSnackbar(`This organization already owns \"${name}\".`, {\n variant: 'info',\n persist: false,\n })\n }\n if (outcome === 'pending') {\n return void enqueueSnackbar(\n `Your payment for \"${name}\" is going through. It is yours as soon as it clears.`,\n { variant: 'info', persist: false },\n )\n }\n // A lockdown is a pause to read, and it must not vanish unread (AGL-1532).\n if (error) {\n enqueueSnackbar(\n error,\n locked ? { variant: 'warning', persist: true } : { variant: 'error', allowDuplicate: true },\n )\n }\n },\n [pay.buy, enqueueSnackbar],\n )\n\n /**\n * Uninstall a plugin listing from the listing detail (AGL-881) — the same\n * `action:'uninstall'` the installed add-ons card uses, so it removes the\n * pin (and the switchboard entry when nothing else pins it) and decrements\n * activeInstalls. Only plugins have a removable pin; other artifact types\n * land in a library and have nothing to uninstall.\n */\n const uninstall = useCallback(\n async (\n listing: any,\n scope?: 'org' | 'host',\n // Which site's pin to drop (AGL-997). Without this the call always\n // targeted the acting host, so at org scope \"uninstall\" could only\n // mean \"the whole org pin\" or \"whichever site happened to be acting\"\n // — removing the plugin from ONE of several sites was unreachable.\n targetHostId?: string,\n ) => {\n const dequeue = queueLoading()\n try {\n const response = await authorizedFetch(\n user,\n '/api/marketplace/install-plugin',\n {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n listingId: listing.$id,\n hostId: targetHostId ?? hostId,\n action: 'uninstall',\n ...(scope ? { scope } : {}),\n }),\n },\n )\n const payload = await response.json().catch(() => ({}))\n if (!response.ok) {\n // Uninstall rides the install-plugin route, so an installs lock\n // refuses it too (AGL-1532) — and \"Uninstall failed\" during an\n // incident is exactly the wrong sentence for someone trying to\n // remove the listing under investigation.\n const locked = parseLockdownRefusal(response.status, payload)\n if (locked) {\n return void enqueueSnackbar(lockdownRefusalText(locked), {\n variant: 'warning',\n persist: true,\n })\n }\n return void enqueueSnackbar(payload?.error ?? 'Uninstall failed', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n enqueueSnackbar(`Removed \"${listing.displayName}\"`, {\n variant: 'success',\n persist: false,\n })\n } catch (error) {\n console.error(error)\n enqueueSnackbar('An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n } finally {\n dequeue()\n }\n },\n [user, hostId, queueLoading, enqueueSnackbar],\n )\n\n return { install, installPlan, buy, uninstall, payPanel: pay.panel, buying: pay.busy }\n}\n\nexport default useMarketplaceActions\n"],"names":["lockdownRefusalText","parseLockdownRefusal","useLoading","useSnackbar","useCallback","useUser","authorizedFetch","listingArtifactType","installPlanOutcome","marketplaceInstallEndpoint","marketplaceLandingMessage","useMarketplacePay","baseMissingWarning","displayName","useMarketplaceActions","hostId","orgId","billingHref","data","user","enqueueSnackbar","queueLoading","pay","install","listing","scope","options","dequeue","payload","artifactType","endpoint","response","method","headers","body","JSON","stringify","listingId","$id","json","ok","diverged","onDiverged","locked","status","variant","persist","error","allowDuplicate","landed","updated","version","baseStored","assurance","hosts","linkHosts","length","join","foreignMediaScopes","degradedFieldIds","console","installPlan","steps","installed","errors","abiWarnings","Set","withoutBase","leftOut","lockedNotice","step","targetHostId","exceptHostIds","runsOn","mode","catch","hostAbiWarning","add","String","Array","isArray","leftOutHostIds","push","outcome","name","orgWide","some","updating","intent","saved","Boolean","text","tone","warning","buy","uninstall","action","payPanel","panel","buying","busy"],"mappings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EwD,uBAAAA,eAAgBxD;oBACxBiF,QAAQ;mBACJvE,QAAQ;oBAAEA;gBAAM,IAAI,CAAC;YAE7B;YAEF,MAAMG,UAAU,MAAMG,SAASQ,IAAI,GAAGoC,KAAK,CAAC,IAAO,CAAA,CAAC,CAAA;YACpD,IAAI,CAAC5C,SAASS,EAAE,EAAE;;gBAChB,gEAAgE;gBAChE,+DAA+D;gBAC/D,+DAA+D;gBAC/D,0CAA0C;gBAC1C,MAAMG,SAAS1C,qBAAqB8B,SAASa,MAAM,EAAEhB;gBACrD,IAAIe,QAAQ;oBACV,OAAO,KAAKvB,gBAAgBpB,oBAAoB2C,SAAS;wBACvDE,SAAS;wBACTC,SAAS;oBACX;gBACF;gBACA,OAAO,KAAK1B,wBAAgBQ,2BAAAA,QAASmB,KAAK,mBAAI,oBAAoB;oBAChEF,SAAS;oBACTG,gBAAgB;gBAClB;YACF;YACA5B,gBAAgB,CAAC,SAAS,EAAEI,QAAQX,WAAW,CAAC,CAAC,CAAC,EAAE;gBAClDgC,SAAS;gBACTC,SAAS;YACX;QACF,EAAE,OAAOC,OAAO;YACda,QAAQb,KAAK,CAACA;YACd3B,gBAAgB,yBAAyB;gBACvCyB,SAAS;gBACTG,gBAAgB;YAClB;QACF,SAAU;YACRrB;QACF;IACF,GACA;QAACR;QAAMJ;QAAQM;QAAcD;KAAgB;IAG/C,OAAO;QAAEG;QAASsC;QAAaiC;QAAKC;QAAWE,UAAU3E,IAAI4E,KAAK;QAAEC,QAAQ7E,IAAI8E,IAAI;IAAC;AACvF;AAEA,eAAetF,sBAAqB"}
@@ -186,6 +186,20 @@ export interface OrgInstallSite {
186
186
  pinnedBy: InstallTarget;
187
187
  /** This site has its OWN pin on top of an org pin. */
188
188
  shadowed: boolean;
189
+ /**
190
+ * Pinned here, but the site's own Admin › Plugins switch has it off (its
191
+ * `disabledPlugins` holds the listing id, AGL-4047), so it does not run
192
+ * here. Present only when true, and only when the caller handed over the
193
+ * sites' lists and the listing id.
194
+ */
195
+ switchedOff?: true;
196
+ }
197
+ /** A site as the install picture reads it: its id, its name, and the plugins it switched off. */
198
+ export interface OrgInstallHost {
199
+ id: string;
200
+ label: string;
201
+ /** The site's own deny-list (`disabledPlugins`), when the caller has it. */
202
+ disabledPlugins?: readonly string[] | null;
189
203
  }
190
204
  /**
191
205
  * The whole org's install picture for one listing (AGL-997).
@@ -214,10 +228,15 @@ export interface OrgInstallSummary {
214
228
  availableHostIds: string[];
215
229
  installedAnywhere: boolean;
216
230
  }
217
- export declare function resolveOrgInstallSummary(hosts: ReadonlyArray<{
218
- id: string;
219
- label: string;
220
- }>, hostPins: Readonly<Record<string, InstallPin | null | undefined>>, orgPin: InstallPin | null | undefined): OrgInstallSummary;
231
+ /**
232
+ * `listingId` (AGL-4047): a pin is not the whole answer. A site whose own
233
+ * switch has the listing off (`disabledPlugins`, written by its Admin ›
234
+ * Plugins page or by an install that left it out) keeps its pin or its org
235
+ * coverage but runs nothing, exactly as the realm join drops it. Given the id
236
+ * and each site's list, such a site is marked `switchedOff`; without them the
237
+ * picture is the pins alone, as before.
238
+ */
239
+ export declare function resolveOrgInstallSummary(hosts: ReadonlyArray<OrgInstallHost>, hostPins: Readonly<Record<string, InstallPin | null | undefined>>, orgPin: InstallPin | null | undefined, listingId?: string): OrgInstallSummary;
221
240
  /** One site an uninstall would touch, and whether it really loses the plugin. */
222
241
  export interface UninstallTarget {
223
242
  hostId: string;
@@ -341,6 +360,8 @@ export declare function installPlanOutcome(input: {
341
360
  version?: string | null;
342
361
  /** The artifact lands in a library and is not live (a template, a layout): "Saved", not "Installed". */
343
362
  saved?: boolean;
363
+ /** Sites the org-wide pin left out, "All sites except…" (AGL-4047). */
364
+ leftOut?: number;
344
365
  }): {
345
366
  tone: 'success' | 'warning' | 'error';
346
367
  text: string;
@@ -283,26 +283,36 @@
283
283
  availableVersion
284
284
  };
285
285
  }
286
- export function resolveOrgInstallSummary(hosts, hostPins, orgPin) {
286
+ /**
287
+ * `listingId` (AGL-4047): a pin is not the whole answer. A site whose own
288
+ * switch has the listing off (`disabledPlugins`, written by its Admin ›
289
+ * Plugins page or by an install that left it out) keeps its pin or its org
290
+ * coverage but runs nothing, exactly as the realm join drops it. Given the id
291
+ * and each site's list, such a site is marked `switchedOff`; without them the
292
+ * picture is the pins alone, as before.
293
+ */ export function resolveOrgInstallSummary(hosts, hostPins, orgPin, listingId) {
287
294
  const orgWide = Boolean(orgPin);
288
295
  const orgVersion = (orgPin == null ? void 0 : orgPin.version) != null ? String(orgPin.version) : null;
289
296
  const sites = [];
290
297
  const hostPinnedIds = [];
291
298
  const availableHostIds = [];
292
299
  for (const host of hosts){
300
+ var _host_disabledPlugins;
293
301
  const hostPin = hostPins[host.id];
294
302
  if (hostPin) hostPinnedIds.push(host.id);
295
303
  if (!hostPin && !orgPin) {
296
304
  availableHostIds.push(host.id);
297
305
  continue;
298
306
  }
299
- sites.push({
307
+ sites.push(_extends({
300
308
  hostId: host.id,
301
309
  label: host.label,
302
310
  version: (hostPin == null ? void 0 : hostPin.version) != null ? String(hostPin.version) : orgVersion,
303
311
  pinnedBy: hostPin ? 'host' : 'org',
304
312
  shadowed: Boolean(hostPin && orgPin)
305
- });
313
+ }, listingId && ((_host_disabledPlugins = host.disabledPlugins) == null ? void 0 : _host_disabledPlugins.includes(listingId)) ? {
314
+ switchedOff: true
315
+ } : {}));
306
316
  }
307
317
  return {
308
318
  orgWide,
@@ -355,7 +365,21 @@ export function resolveOrgInstallSummary(hosts, hostPins, orgPin) {
355
365
  });
356
366
  }
357
367
  /** What "Where it runs" opens with: the whole organization, or how many of its sites. */ export function pluginSiteSetSummary(install, siteCount) {
358
- return install.orgWide ? `Installed for the whole organization (v${install.orgVersion}) — every site, including ones you add later.` : `Installed on ${install.sites.length} of ${siteCount} sites.`;
368
+ // Sites whose own switch has it off (AGL-4047): pinned, but not running.
369
+ const off = install.sites.filter((site)=>site.switchedOff).map((site)=>site.label);
370
+ if (install.orgWide) {
371
+ const head = `Installed for the whole organization (v${install.orgVersion})`;
372
+ if (!off.length) return `${head} — every site, including ones you add later.`;
373
+ return off.length === install.sites.length ? `${head}. Every site switched it off, so it runs only on sites you add later.` : `${head}. It runs on every site except ${namesList(off)}, which switched it off, and on sites you add later.`;
374
+ }
375
+ const head = `Installed on ${install.sites.length} of ${siteCount} sites`;
376
+ if (!off.length) return `${head}.`;
377
+ const running = install.sites.length - off.length;
378
+ return `${head}. ${namesList(off)} switched it off, so it runs on ${running ? running : 'none of them'}.`;
379
+ }
380
+ /** "A", "A and B", "A, B and C". */ function namesList(names) {
381
+ var _names_;
382
+ return names.length < 2 ? (_names_ = names[0]) != null ? _names_ : '' : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
359
383
  }
360
384
  /** What the update confirmation says: the plugin, the version it moves to and where, and what stays put. */ export function pluginUpdatePrompt(input) {
361
385
  return {
@@ -435,14 +459,15 @@ const PLACEMENT_NOUNS = {
435
459
  };
436
460
  }
437
461
  /** What a run of installs (an install, an update, or the several steps of one) says once it is done. */ export function installPlanOutcome(input) {
438
- var _errors_;
462
+ var _input_leftOut, _errors_;
439
463
  const { name, installed, errors, orgWide, updating, version, saved } = input;
464
+ const leftOut = (_input_leftOut = input.leftOut) != null ? _input_leftOut : 0;
440
465
  const noun = updating ? 'Updated' : saved ? 'Saved' : 'Installed';
441
466
  const toVersion = updating && version != null ? ` to v${version}` : '';
442
467
  if (installed && !errors.length) {
443
468
  return {
444
469
  tone: 'success',
445
- text: orgWide ? `${noun} "${name}"${toVersion} for the whole organization` : `${noun} "${name}"${toVersion} on ${installed} site${installed === 1 ? '' : 's'}`
470
+ text: orgWide ? leftOut > 0 ? `${noun} "${name}"${toVersion} for every site but ${leftOut === 1 ? 'the one' : `the ${leftOut}`} you left out, and for sites you add later` : `${noun} "${name}"${toVersion} for the whole organization` : `${noun} "${name}"${toVersion} on ${installed} site${installed === 1 ? '' : 's'}`
446
471
  };
447
472
  }
448
473
  if (installed && errors.length) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/marketplace-catalog.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 type { InstallableArtifactType as MarketplaceArtifactType } from '@aglyn/aglyn/app-utils/artifact-provenance'\n\n/**\n * The marketplace's catalog vocabulary, pure (AGL-3668): what each artifact\n * type is called, where each installs, the categories, a plugin's install\n * state from its two pins, and which route installs a type and what its\n * install says. The native apps generate from it; `marketplace.ts` and the\n * install hook re-export and use it.\n */\n\n/**\n * Human-readable label for each artifact type (AGL-864).\n *\n * Shared by browse cards, the listing detail page, and the seller panel so\n * \"what kind of thing is this\" reads the same everywhere. Resolve a listing's\n * label through {@link listingArtifactLabel}, which tolerates the legacy\n * `type`/`kind` shape the way {@link listingArtifactType} does.\n */\nexport const ARTIFACT_TYPE_LABELS: Record<MarketplaceArtifactType, string> = {\n plugin: 'Plugin',\n component: 'Component',\n template: 'Site template',\n layout: 'Layout',\n datasetSchema: 'Dataset schema',\n emailTemplate: 'Email template',\n emailStarter: 'Email starter',\n theme: 'Theme',\n siteStarter: 'Site starter',\n}\n\n/** Where an installed artifact lives. */\nexport type InstallTarget = 'org' | 'host'\n\n/**\n * Install targets each artifact type actually supports (AGL-656).\n *\n * This is not a policy choice — it is where the install routes physically\n * write. Only plugins have an org-scoped pin\n * (`orgs/{orgId}/installs/{listingId}`, applying to every site, shadowed by\n * a host pin). Components land in `hosts/{h}/components`, templates and\n * layouts in `hosts/{h}/templates`: all host-scoped by nature, because a\n * screen tree belongs to a site.\n *\n * Exported so the UI can ask rather than assume — an install picker that\n * offers \"this whole organization\" for a template would be lying.\n */\nexport const INSTALL_TARGETS: Record<\n MarketplaceArtifactType,\n readonly InstallTarget[]\n> = {\n plugin: ['org', 'host'],\n component: ['host'],\n template: ['host'],\n layout: ['host'],\n // Dataset schemas are org-shared data (AGL-237), so they install at org\n // scope — as a new empty dataset, not a pin (AGL-657).\n datasetSchema: ['org'],\n emailTemplate: ['host'],\n // A campaign email is a screen, and a screen belongs to a site.\n emailStarter: ['host'],\n // A theme is one site's visual identity, written to `hosts/{h}.theme`\n // (AGL-1020). Applying one org-wide would repaint every site at once from a\n // control that says \"install\".\n theme: ['host'],\n // A site starter installs by creating a site from it (AGL-4049), never\n // into an existing one.\n siteStarter: ['host'],\n}\n\n/** A plugin install pin — the version-pinned doc the install API writes. */\nexport interface InstallPin {\n version?: number | string\n}\n\n/**\n * The install state of a plugin listing for one site, told honestly (AGL-656).\n *\n * A plugin can be pinned at two scopes: the org pin\n * (`orgs/{orgId}/installs/{listingId}`) applies to every site, and a host pin\n * (`hosts/{hostId}/installs/{listingId}`) applies to just this one AND shadows\n * the org pin. Detecting installs from `hosts/{h}/components` — the COMPONENT\n * collection — never sees either pin, so an installed plugin used to read as\n * \"not installed\" on both the browse grid and the detail page. This resolves\n * the effective state from the two pins the way the loader does.\n */\nexport interface PluginInstallState {\n /** Effective pin scope for this site — host wins over org — or null. */\n scope: InstallTarget | null\n /** Version pinned at the effective scope, or null when not installed. */\n installedVersion: string | null\n /** Both pins exist: the host pin takes precedence, shadowing the org one. */\n shadowed: boolean\n /** Installed, but the pinned version is behind the listing's latest. */\n updateAvailable: boolean\n}\n\n/**\n * Resolves a plugin listing's install state for a site from its two pins\n * (AGL-656). The host pin shadows the org pin, mirroring the loader, so the\n * effective version and update prompt always describe what actually runs here.\n */\nexport function resolvePluginInstallState(\n latestVersion: number | string | undefined,\n hostPin: InstallPin | null | undefined,\n orgPin: InstallPin | null | undefined,\n): PluginInstallState {\n const effective = hostPin ?? orgPin ?? null\n const installedVersion =\n effective?.version != null ? String(effective.version) : null\n return {\n scope: hostPin ? 'host' : orgPin ? 'org' : null,\n installedVersion,\n shadowed: Boolean(hostPin && orgPin),\n // Any difference is an upgrade prompt, matching the installed-plugins card\n // — pins only ever move forward, so \"different\" means \"behind\".\n updateAvailable:\n installedVersion != null &&\n latestVersion != null &&\n String(latestVersion) !== installedVersion,\n }\n}\n\n/** Fixed category taxonomy for marketplace listings (AGL-430). */\nexport const LISTING_CATEGORIES: readonly string[] = [\n 'analytics',\n 'automation',\n 'commerce',\n 'communication',\n 'content',\n 'design',\n 'forms',\n 'integrations',\n 'marketing',\n 'productivity',\n 'seo',\n 'security',\n] as const\n\n/**\n * Each artifact type has its own installer route (AGL-672): routing\n * everything to the component one silently installed the wrong thing or\n * 404'd. `listingArtifactType` tolerates the legacy `type`/`kind`\n * discriminators (AGL-654).\n */\nexport function marketplaceInstallEndpoint(artifactType: string): string {\n switch (artifactType) {\n case 'template':\n return 'marketplace/install-template'\n case 'layout':\n return 'marketplace/install-layout'\n case 'plugin':\n return 'marketplace/install-plugin'\n case 'datasetSchema':\n return 'marketplace/install-dataset-schema'\n case 'emailTemplate':\n return 'marketplace/install-email-template'\n case 'emailStarter':\n return 'marketplace/install-email-starter'\n case 'theme':\n return 'marketplace/install-theme'\n default:\n return 'marketplace/install'\n }\n}\n\n/**\n * Artifact types whose install deliberately does NOT touch the running site\n * (AGL-669/671/657) — the copy must not imply otherwise. Templates and layouts\n * land in the Templates library; an email template lands as an inactive\n * version the owner still has to activate.\n */\nexport function marketplaceLandingMessage(\n artifactType: string,\n displayName: string,\n): string | null {\n switch (artifactType) {\n case 'template':\n case 'layout':\n return (\n `Saved \"${displayName}\" to your Templates — nothing is live until ` +\n 'you use it.'\n )\n case 'emailTemplate':\n return (\n `Saved \"${displayName}\" as a draft version — activate it in the ` +\n 'email designer to start sending it.'\n )\n case 'emailStarter':\n // A copy, and saying so is the point: the publisher cannot reach it\n // again, and nothing goes out until a campaign is sent from it.\n return (\n `Added \"${displayName}\" to your Email templates as your own copy — ` +\n 'edit it freely, nothing is sent until you send a campaign.'\n )\n case 'datasetSchema':\n return `Created \"${displayName}\" as a new, empty dataset.`\n case 'theme':\n // The one type that DOES change the running site on install, so it gets\n // the opposite of the reassurance the others get — plus the way back,\n // because a repainted site is alarming if you cannot see how to undo it.\n return (\n `Applied \"${displayName}\" to this site. Setup → Theme has a way back ` +\n 'to your previous theme.'\n )\n default:\n return null\n }\n}\n\n/**\n * ─── WHAT A PLUGIN'S PAGE SAYS ABOUT ITS INSTALLS (AGL-1016, AGL-997, AGL-1027, AGL-3671) ───\n *\n * The version comparison, the update status, the org-wide picture of one listing's pins, which sites an\n * uninstall touches and the sentences the workspace's plugin pages and their dialogs say about them. All of\n * it was spread across `update-state.ts`, `marketplace.ts` and the plugin-site-set components; it lives here,\n * pure, so the native apps replay the very same answers (`libs/native/contracts/function-cases.generated.json`).\n * Those modules re-export what moved.\n */\n\n/**\n * Orders two artifact versions, or returns null when they cannot be ordered.\n *\n * Two numbering schemes are in play and both are real: copied artifacts get a\n * monotonic integer from the publish route, plugins get the semver string off\n * their manifest. A single string compare handles neither (\"10\" < \"9\",\n * \"1.10.0\" < \"1.9.0\"), so both are parsed as dotted numbers — which covers the\n * integer case as a one-segment version.\n *\n * Anything non-numeric (a prerelease tag, a date-stamped build) is not ordered\n * by guesswork: unequal-and-incomparable is reported as such and surfaces as\n * `unknown`, which is honest, where a string compare would confidently point\n * an update button at an older build.\n */\nexport function compareArtifactVersions(\n a: string | number | null | undefined,\n b: string | number | null | undefined,\n): -1 | 0 | 1 | null {\n if (a == null || b == null || a === '' || b === '') return null\n const left = String(a)\n const right = String(b)\n if (left === right) return 0\n const parse = (value: string): number[] | null => {\n const parts = value.split('.')\n const numbers: number[] = []\n for (const part of parts) {\n if (!/^\\d+$/.test(part)) return null\n numbers.push(Number(part))\n }\n return numbers.length ? numbers : null\n }\n const leftParts = parse(left)\n const rightParts = parse(right)\n if (!leftParts || !rightParts) return null\n const length = Math.max(leftParts.length, rightParts.length)\n for (let index = 0; index < length; index += 1) {\n const leftPart = leftParts[index] ?? 0\n const rightPart = rightParts[index] ?? 0\n if (leftPart < rightPart) return -1\n if (leftPart > rightPart) return 1\n }\n // Equal numerically but not as strings — \"1.0\" and \"1.0.0\" are the same\n // version written two ways.\n return 0\n}\n\nexport type UpdateState =\n /** Running the newest version the publisher offers. */\n | 'current'\n /** A newer version exists and can be taken. */\n | 'update-available'\n /**\n * Installed version is NEWER than what is offered. Not a bug: a publisher\n * installs their own unapproved version to test it, and a version can be\n * withdrawn after someone installed it.\n */\n | 'ahead'\n /** Not enough is known to say — no provenance, or nothing published to compare. */\n | 'unknown'\n\nexport interface UpdateStatus {\n state: UpdateState\n /** The version running, or null when provenance cannot say. */\n installedVersion: string | null\n /** The newest version on offer — for plugins, the newest APPROVED one. */\n availableVersion: string | null\n /**\n * Why the answer is `unknown`, for a UI that should say which kind of\n * silence this is rather than implying the artifact is current.\n */\n unknownReason?: 'no-provenance' | 'nothing-published' | 'incomparable'\n}\n\n/**\n * One sentence describing an update state, so four surfaces do not each invent\n * their own wording for the same fact.\n */\nexport function updateStateLabel(status: UpdateStatus): string {\n switch (status.state) {\n case 'update-available':\n return `You have v${status.installedVersion} · v${status.availableVersion} available`\n case 'current':\n return `Up to date · v${status.installedVersion}`\n case 'ahead':\n return `You have v${status.installedVersion}, newer than the published v${status.availableVersion}`\n default:\n return status.unknownReason === 'nothing-published'\n ? 'No published version to compare against'\n : status.unknownReason === 'incomparable'\n ? `You have v${status.installedVersion}; v${status.availableVersion} cannot be ordered against it`\n : 'Installed before update tracking — version unknown'\n }\n}\n\n/** The pin fields an update comparison reads, in every shape the install routes have written. */\nexport interface UpdateComparablePin {\n version?: unknown\n installedFrom?: { listingId?: string; version?: unknown } | null\n marketplace?: { listingId?: string; version?: unknown } | null\n source?: { listingId?: string; version?: unknown } | null\n listingId?: string\n}\n\n/**\n * What a listing OFFERS right now (the plugin branch of `offeredPluginVersion`): the newest approved version, unless a\n * revocation (`versions` naming it, or `'all'`) has stopped it, in which case nothing is offered.\n */\nexport function pluginOfferedVersion(\n latestApprovedVersion: unknown,\n revocationVersions: readonly string[] | 'all' | null | undefined,\n): string | null {\n const offered = String(latestApprovedVersion ?? '')\n if (!offered) return null\n if (revocationVersions === 'all') return null\n return Array.isArray(revocationVersions) && revocationVersions.includes(offered) ? null : offered\n}\n\n/**\n * Whether the installed plugin is still what the publisher ships (the plugin branch of `resolveUpdateState`): the\n * pin's version against the version on offer. A pin that names no listing is the one shape that records no version\n * (`no-provenance`).\n */\nexport function pluginUpdateStatus(\n pin: UpdateComparablePin | null | undefined,\n offeredVersion: string | null | undefined,\n): UpdateStatus {\n const unknown: UpdateStatus = { state: 'unknown', installedVersion: null, availableVersion: null, unknownReason: 'no-provenance' }\n if (!pin) return unknown\n const recorded = pin.installedFrom?.listingId\n ? pin.installedFrom.version\n : pin.marketplace?.listingId\n ? pin.marketplace.version\n : pin.source?.listingId\n ? pin.source.version\n : pin.listingId\n ? pin.version\n : undefined\n const installedVersion = recorded == null || recorded === '' ? null : String(recorded)\n if (!installedVersion) return unknown\n if (offeredVersion == null || offeredVersion === '') {\n return { state: 'unknown', installedVersion, availableVersion: null, unknownReason: 'nothing-published' }\n }\n const availableVersion = String(offeredVersion)\n const order = compareArtifactVersions(installedVersion, availableVersion)\n if (order === null) return { state: 'unknown', installedVersion, availableVersion, unknownReason: 'incomparable' }\n return { state: order === 0 ? 'current' : order < 0 ? 'update-available' : 'ahead', installedVersion, availableVersion }\n}\n\n\n/** One site's slice of an org-scope install picture (AGL-997). */\nexport interface OrgInstallSite {\n hostId: string\n label: string\n /** The version that actually runs here, from the effective pin. */\n version: string | null\n /** Where that pin lives — a host pin shadows the org one, as the loader does. */\n pinnedBy: InstallTarget\n /** This site has its OWN pin on top of an org pin. */\n shadowed: boolean\n}\n\n/**\n * The whole org's install picture for one listing (AGL-997).\n *\n * At org scope, \"installed\" is a SET, not a boolean. The detail page used to\n * resolve state against the single acting host, so a plugin installed on one\n * of five sites reported \"Installed on this site\" — describing one arbitrary\n * site and staying silent about the other four — and offered an Uninstall\n * that was all-or-nothing.\n *\n * `orgWide` and per-site pins are not exclusive: an org pin covers every\n * site including ones created later, and a host pin on top of it shadows it\n * for that one site. Both facts have to survive into the UI, which is why\n * this returns the sites AND the pins rather than a single scope.\n */\nexport interface OrgInstallSummary {\n /** An org pin exists: every site is covered, including future ones. */\n orgWide: boolean\n /** Version of the org pin, when there is one. */\n orgVersion: string | null\n /** Every site the listing effectively runs on. */\n sites: OrgInstallSite[]\n /** Sites carrying their own removable host pin. */\n hostPinnedIds: string[]\n /** Sites with no pin of their own and no org pin covering them. */\n availableHostIds: string[]\n installedAnywhere: boolean\n}\n\nexport function resolveOrgInstallSummary(\n hosts: ReadonlyArray<{ id: string; label: string }>,\n hostPins: Readonly<Record<string, InstallPin | null | undefined>>,\n orgPin: InstallPin | null | undefined,\n): OrgInstallSummary {\n const orgWide = Boolean(orgPin)\n const orgVersion = orgPin?.version != null ? String(orgPin.version) : null\n const sites: OrgInstallSite[] = []\n const hostPinnedIds: string[] = []\n const availableHostIds: string[] = []\n for (const host of hosts) {\n const hostPin = hostPins[host.id]\n if (hostPin) hostPinnedIds.push(host.id)\n if (!hostPin && !orgPin) {\n availableHostIds.push(host.id)\n continue\n }\n sites.push({\n hostId: host.id,\n label: host.label,\n version:\n hostPin?.version != null ? String(hostPin.version) : orgVersion,\n pinnedBy: hostPin ? 'host' : 'org',\n shadowed: Boolean(hostPin && orgPin),\n })\n }\n return {\n orgWide,\n orgVersion,\n sites,\n hostPinnedIds,\n availableHostIds,\n installedAnywhere: orgWide || hostPinnedIds.length > 0,\n }\n}\n\n/** One site an uninstall would touch, and whether it really loses the plugin. */\nexport interface UninstallTarget {\n hostId: string\n label: string\n /**\n * The plugin keeps running here. Removing a HOST pin while an org pin still\n * covers the site, or the ORG pin while the site holds its own host pin,\n * changes which pointer is in use and nothing a visitor can see.\n */\n stillCovered: boolean\n}\n\n/**\n * Which sites an uninstall actually affects (AGL-1027).\n *\n * The shadowing case is the whole reason this is a function rather than a\n * filter at the call site. A pin is not a boolean per site: an org pin covers\n * everything, a host pin names one site, and where both exist the host pin\n * wins. So \"remove\" means three different things depending on which pointer is\n * being dropped and what is left underneath — and the one thing the dialog must\n * never do is tell someone a plugin will stop working when it will not.\n *\n * Returns every site the operation touches, including the ones that keep the\n * plugin, so the dialog can say so explicitly instead of omitting them and\n * leaving the count unexplained.\n */\nexport function resolveUninstallTargets(\n orgInstall: OrgInstallSummary,\n scope: 'org' | 'host',\n hostId?: string,\n): UninstallTarget[] {\n if (scope === 'host') {\n const site = orgInstall.sites.find((entry) => entry.hostId === hostId)\n if (!site) return []\n // Its own pin goes; the org pin, if there is one, still covers it.\n return [\n { hostId: site.hostId, label: site.label, stillCovered: orgInstall.orgWide },\n ]\n }\n // Dropping the org pin: every site loses it EXCEPT those holding a host pin\n // of their own, which were already shadowing the org pin anyway.\n return orgInstall.sites.map((site) => ({\n hostId: site.hostId,\n label: site.label,\n stillCovered: site.pinnedBy === 'host',\n }))\n}\n\n// ─── The sentences of a plugin's install pages and their dialogs (AGL-1017, AGL-1027, AGL-3671) ───\n\n/** The sites of an org-wide picture whose running version is behind the one on offer. */\nexport function staleSites(sites: readonly OrgInstallSite[], latestVersion: string | number | null | undefined): OrgInstallSite[] {\n return sites.filter((site) => (compareArtifactVersions(site.version, latestVersion) ?? 0) < 0)\n}\n\n/** What \"Where it runs\" opens with: the whole organization, or how many of its sites. */\nexport function pluginSiteSetSummary(install: OrgInstallSummary, siteCount: number): string {\n return install.orgWide\n ? `Installed for the whole organization (v${install.orgVersion}) — every site, including ones you add later.`\n : `Installed on ${install.sites.length} of ${siteCount} sites.`\n}\n\n/** What the update confirmation says: the plugin, the version it moves to and where, and what stays put. */\nexport function pluginUpdatePrompt(input: {\n name: string\n latestVersion: string\n label: string\n /** The update is for one site: other sites stay on the version they run. */\n singleSite: boolean\n}): { title: string; body: string; others: string | null; note: string } {\n return {\n title: `Update to v${input.latestVersion}?`,\n body: `${input.name} moves from the version running now to v${input.latestVersion} on ${input.label}.`,\n others: input.singleSite ? 'Other sites stay on the version they are running.' : null,\n note: 'Pins only move forward — there is no going back to the previous version from here.',\n }\n}\n\n/** What the update button of a pin that is org-wide, or of the stale per-site ones, is called and aims at. */\nexport function pluginUpdateAll(install: OrgInstallSummary, stale: readonly OrgInstallSite[], latestVersion: string) {\n return {\n label: install.orgWide ? `Update to v${latestVersion}` : `Update all ${stale.length} to v${latestVersion}`,\n target: install.orgWide ? 'every site in this organization' : `${stale.length} site${stale.length === 1 ? '' : 's'}`,\n hostIds: install.orgWide ? null : stale.map((site) => site.hostId),\n }\n}\n\n/** The notice above an org-wide update: one pin moves every site at once. */\nexport const PLUGIN_ORG_WIDE_UPDATE_NOTE =\n 'This is one organization-wide pin, so updating moves every site at once. To take a version on one site first, install per site instead.'\n\n/** One site an uninstall dialog was told about by the impact check. */\nexport interface UninstallImpactSite {\n hostId: string\n label: string\n stillCovered: boolean\n placements: Array<{ type: 'screen' | 'layout' | 'component'; id: string; name: string; count: number }>\n affectedScreens: number\n truncated: boolean\n}\n\n/** What `/api/hosts/plugin-impact` answers. */\nexport interface UninstallImpact {\n sites: UninstallImpactSite[]\n losingSites: number\n placements: number\n affectedScreens: number\n truncated: boolean\n dataSurvives: boolean\n}\n\n/** The word typed to confirm an uninstall that breaks pages, or whose impact could not be checked. */\nexport const UNINSTALL_ACKNOWLEDGEMENT = 'UNINSTALL'\n\n/** What the uninstall dialog shows, worked out from the targets and the impact check's answer. */\nexport interface UninstallImpactView {\n title: string\n confirmLabel: string\n /** The check is still running. */\n scanning: boolean\n /** Alerts above the sites, in order. */\n alerts: Array<{ tone: 'warning' | 'error' | 'info'; text: string }>\n /** Sites that lose the plugin and place it on pages: the site, how many pages, and the chips. */\n sites: Array<{ label: string; pages: string; chips: string[] }>\n /** The closing note, when sites lose the plugin. */\n note: string | null\n /** Pages stop rendering it, or the check could not say: the person types {@link UNINSTALL_ACKNOWLEDGEMENT}. */\n needsAcknowledgement: boolean\n}\n\nconst PLACEMENT_NOUNS = { screen: 'page', layout: 'layout', component: 'component' } as const\n\n/** The uninstall dialog (`UninstallImpactDialog`) as data, so every client says the same things. */\nexport function uninstallImpactView(input: {\n name: string\n scope: 'org' | 'host'\n /** The listing's plugin id; without one the placements cannot be found. */\n pluginId: string\n targets: readonly UninstallTarget[]\n /** The impact check's answer, once it has come. */\n impact: UninstallImpact | null\n /** The impact check failed. */\n failed: boolean\n}): UninstallImpactView {\n const { name, scope, pluginId, targets, impact, failed } = input\n const losing = targets.filter((target) => !target.stillCovered)\n const covered = targets.filter((target) => target.stillCovered)\n const scanning = Boolean(pluginId) && losing.length > 0 && !impact && !failed\n const affected = impact?.affectedScreens ?? 0\n const unknown = failed || (!pluginId && losing.length > 0)\n const alerts: UninstallImpactView['alerts'] = []\n if (unknown && !scanning) {\n alerts.push({\n tone: 'warning',\n text: pluginId\n ? 'The impact check could not run, so this cannot say what would stop working. Nothing here means \"nothing breaks\".'\n : 'This listing records no plugin id, so its placements cannot be found. Pages using it may stop rendering it.',\n })\n }\n if (!scanning && !unknown && affected > 0) {\n const sites = impact?.losingSites ?? losing.length\n alerts.push({\n tone: 'error',\n text:\n `Removes ${name} from ${sites} site${sites === 1 ? '' : 's'}; ` +\n `${impact?.truncated ? 'at least ' : ''}${affected} published page${affected === 1 ? '' : 's'} ` +\n `place${affected === 1 ? 's' : ''} it and will stop rendering it.`,\n })\n }\n if (!scanning && !unknown && affected === 0 && losing.length) {\n alerts.push({ tone: 'info', text: 'No published page places this plugin, so nothing visitors can see changes.' })\n }\n if (covered.length) {\n alerts.push({\n tone: 'info',\n text:\n covered.length === targets.length\n ? `The plugin keeps running on ${covered.length === 1 ? 'this site' : `all ${covered.length} of these sites`}, ` +\n `because another install still covers ${covered.length === 1 ? 'it' : 'them'}. Only which version is in use changes.`\n : `${covered.length} of these sites keep the plugin — ${covered.map((target) => target.label).join(', ')} — ` +\n 'because another install still covers them.',\n })\n }\n const sites = (impact?.sites ?? [])\n .filter((site) => !site.stillCovered && site.placements.length)\n .map((site) => ({\n label: site.label,\n pages: `${site.affectedScreens} published page${site.affectedScreens === 1 ? '' : 's'} affected`,\n chips: [\n ...site.placements\n .slice(0, 12)\n .map((placement) => `${PLACEMENT_NOUNS[placement.type]}: ${placement.name}${placement.count > 1 ? ` ×${placement.count}` : ''}`),\n ...(site.placements.length > 12 ? [`+${site.placements.length - 12} more`] : []),\n ],\n }))\n return {\n title: scope === 'org' ? `Uninstall ${name} across the organization?` : `Remove ${name} from this site?`,\n confirmLabel: scope === 'org' ? 'Uninstall org-wide' : 'Remove',\n scanning,\n alerts,\n sites,\n note:\n !scanning && losing.length\n ? 'Uninstalling removes the install only. The plugin’s settings and any data it stored are kept, and installing it again restores the pages that place it.'\n : null,\n needsAcknowledgement: !scanning && (affected > 0 || unknown),\n }\n}\n\n/** What a run of installs (an install, an update, or the several steps of one) says once it is done. */\nexport function installPlanOutcome(input: {\n name: string\n /** Steps that went through, and the refusals of those that did not. */\n installed: number\n errors: readonly string[]\n /** One of the steps was the org-wide pin. */\n orgWide: boolean\n /** The steps moved existing pins to {@link version}. */\n updating: boolean\n version?: string | null\n /** The artifact lands in a library and is not live (a template, a layout): \"Saved\", not \"Installed\". */\n saved?: boolean\n}): { tone: 'success' | 'warning' | 'error'; text: string } {\n const { name, installed, errors, orgWide, updating, version, saved } = input\n const noun = updating ? 'Updated' : saved ? 'Saved' : 'Installed'\n const toVersion = updating && version != null ? ` to v${version}` : ''\n if (installed && !errors.length) {\n return {\n tone: 'success',\n text: orgWide\n ? `${noun} \"${name}\"${toVersion} for the whole organization`\n : `${noun} \"${name}\"${toVersion} on ${installed} site${installed === 1 ? '' : 's'}`,\n }\n }\n if (installed && errors.length) {\n return { tone: 'warning', text: `${noun} on ${installed} site(s); ${errors.length} failed — ${errors[0]}` }\n }\n return { tone: 'error', text: errors[0] ?? 'Install failed' }\n}\n\n/** The row of the plugins list for one install: the version and where it runs. */\nexport function installedPluginCaption(input: { version?: unknown; orgWide: boolean; siteLabels: readonly string[] }): string {\n return (\n `v${input.version} · ` +\n (input.orgWide ? 'every site in this organization' : input.siteLabels.length === 1 ? input.siteLabels[0] : `${input.siteLabels.length} sites`)\n )\n}\n\n// ─── A marketplace plugin's settings, from its manifest (AGL-428, AGL-3671) ───\n\nconst MANIFEST_CONFIG_FIELD_LIMIT = 50\nconst MANIFEST_CONFIG_FIELD_TYPES: ReadonlySet<string> = new Set(['string', 'number', 'boolean', 'select'])\n\ninterface ManifestConfigField {\n key: string\n label: string\n type: 'string' | 'number' | 'boolean' | 'select'\n description?: string\n options?: Array<{ value: string; label: string }>\n min?: number\n max?: number\n}\n\n/** A stored or declared value as its field takes it (`coerce` of `plugin-config.ts`), else [fallback]. */\nfunction coerceManifestConfigValue(field: ManifestConfigField, raw: unknown, fallback: unknown): unknown {\n switch (field.type) {\n case 'boolean':\n return typeof raw === 'boolean' ? raw : fallback\n case 'number': {\n const value = typeof raw === 'number' && Number.isFinite(raw) ? raw : NaN\n if (Number.isNaN(value)) return fallback\n if (field.min != null && value < field.min) return field.min\n if (field.max != null && value > field.max) return field.max\n return value\n }\n case 'select': {\n const value = typeof raw === 'string' ? raw : undefined\n return field.options?.some((option) => option.value === value) ? value : fallback\n }\n default:\n return typeof raw === 'string' ? raw : fallback\n }\n}\n\n/**\n * The fields a plugin's MANIFEST declares for its settings and the values they start from (`pluginConfigSchemaFromManifest`\n * of `plugin-config.ts`, which this repeats without its imports so the native apps replay it). Everything is re-validated\n * rather than trusted: a junk type drops the field, a duplicate key drops the second, a select with nothing to select is\n * dropped, and the count is capped. `null` when the manifest declares nothing usable, which means \"this plugin has no\n * settings\".\n */\nexport function manifestSettingsFields(manifest: unknown): { fields: ManifestConfigField[]; defaults: Record<string, unknown> } | null {\n const declared = (manifest as { config?: unknown } | null | undefined)?.config\n const rawFields = (declared as { fields?: unknown } | undefined)?.fields\n if (!Array.isArray(rawFields)) return null\n const seen = new Set<string>()\n const fields: ManifestConfigField[] = []\n for (const raw of rawFields) {\n if (fields.length >= MANIFEST_CONFIG_FIELD_LIMIT) break\n const entry = raw as Record<string, unknown> | null\n const key = typeof entry?.['key'] === 'string' ? entry['key'].trim() : ''\n if (!key || seen.has(key)) continue\n const type = String(entry?.['type'] ?? 'string')\n if (!MANIFEST_CONFIG_FIELD_TYPES.has(type)) continue\n const options = Array.isArray(entry?.['options'])\n ? (entry['options'] as unknown[])\n .map((option) => option as Record<string, unknown> | null)\n .filter((option) => typeof option?.['value'] === 'string' && typeof option?.['label'] === 'string')\n .map((option) => ({ value: String(option?.['value']), label: String(option?.['label']) }))\n : undefined\n if (type === 'select' && !options?.length) continue\n seen.add(key)\n fields.push({\n key,\n label: typeof entry?.['label'] === 'string' && entry['label'].trim() ? String(entry['label']).slice(0, 120) : key,\n type: type as ManifestConfigField['type'],\n description: typeof entry?.['description'] === 'string' ? String(entry['description']).slice(0, 400) : undefined,\n options,\n min: typeof entry?.['min'] === 'number' ? entry['min'] : undefined,\n max: typeof entry?.['max'] === 'number' ? entry['max'] : undefined,\n })\n }\n if (!fields.length) return null\n const rawDefaults = (declared as { defaults?: unknown } | undefined)?.defaults\n const defaults: Record<string, unknown> = {}\n for (const field of fields) {\n const supplied = rawDefaults && typeof rawDefaults === 'object' ? (rawDefaults as Record<string, unknown>)[field.key] : undefined\n const empty =\n field.type === 'boolean' ? false : field.type === 'number' ? (field.min ?? 0) : field.type === 'select' ? (field.options?.[0]?.value ?? '') : ''\n defaults[field.key] = coerceManifestConfigValue(field, supplied, empty)\n }\n return { fields, defaults }\n}\n\nconst MANIFEST_FIELD_KIND = { string: 'text', number: 'number', boolean: 'toggle', select: 'select' } as const\n\n/**\n * The workspace-settings screen of a marketplace plugin, as a native screen spec: the console's `PluginConfigCards` for a\n * pin's manifest. The same shape the generated screens of the built-in plugins have (`pluginSettingsScreen` of\n * `native-plugin-settings.mjs`), under an id of its own, saved to `orgs/{org}/pluginSettings/{plugin}` as the console\n * saves it. `null` for a plugin that declares no settings.\n */\nexport function manifestSettingsScreen(pluginId: string, label: string, manifest: unknown): Record<string, unknown> | null {\n const schema = pluginId ? manifestSettingsFields(manifest) : null\n if (!schema) return null\n const fields = schema.fields.map((field) => {\n const out: Record<string, unknown> = {\n key: field.key,\n label: field.label,\n kind: MANIFEST_FIELD_KIND[field.type],\n // `??` keeps a stored false or 0, which `|` would skip for the default.\n initial: `{item.${field.key} ?? const.defaults.${field.key}}`,\n }\n if (field.type === 'select') out['options'] = (field.options ?? []).map(({ value, label: text }) => ({ value, label: text }))\n const band = field.type === 'number' && (field.min != null || field.max != null) ? `Between ${field.min ?? 'any'} and ${field.max ?? 'any'}.` : ''\n const help = [field.description, band].filter(Boolean).join(' ')\n if (help) out['help'] = help\n return out\n })\n const written = Object.fromEntries(schema.fields.map((field) => [field.key, `{form.${field.key}}`]))\n return {\n id: `marketplace.pluginSettings.${pluginId}`,\n title: `${label} settings`,\n subtitle: `How ${label} behaves for this workspace`,\n icon: 'gearshape|settings',\n scope: 'org',\n requires: 'org.can[org.settings]',\n constants: { defaults: schema.defaults },\n load: { settings: { doc: `orgs/{org.id}/pluginSettings/${pluginId}`, optional: true } },\n blocks: [\n {\n type: 'form',\n id: 'settings',\n object: 'data.settings',\n footer: 'A site can override these on its own plugin page.',\n fields,\n submit: {\n label: 'Save settings',\n write: { doc: `orgs/{org.id}/pluginSettings/${pluginId}`, fields: { ...written, updatedBy: '{user.uid}' } },\n success: 'Settings saved',\n },\n },\n ],\n }\n}\n"],"names":["ARTIFACT_TYPE_LABELS","plugin","component","template","layout","datasetSchema","emailTemplate","emailStarter","theme","siteStarter","INSTALL_TARGETS","resolvePluginInstallState","latestVersion","hostPin","orgPin","effective","installedVersion","version","String","scope","shadowed","Boolean","updateAvailable","LISTING_CATEGORIES","marketplaceInstallEndpoint","artifactType","marketplaceLandingMessage","displayName","compareArtifactVersions","a","b","left","right","parse","value","parts","split","numbers","part","test","push","Number","length","leftParts","rightParts","Math","max","index","leftPart","rightPart","updateStateLabel","status","state","availableVersion","unknownReason","pluginOfferedVersion","latestApprovedVersion","revocationVersions","offered","Array","isArray","includes","pluginUpdateStatus","pin","offeredVersion","unknown","recorded","installedFrom","listingId","marketplace","source","undefined","order","resolveOrgInstallSummary","hosts","hostPins","orgWide","orgVersion","sites","hostPinnedIds","availableHostIds","host","id","hostId","label","pinnedBy","installedAnywhere","resolveUninstallTargets","orgInstall","site","find","entry","stillCovered","map","staleSites","filter","pluginSiteSetSummary","install","siteCount","pluginUpdatePrompt","input","title","body","name","others","singleSite","note","pluginUpdateAll","stale","target","hostIds","PLUGIN_ORG_WIDE_UPDATE_NOTE","UNINSTALL_ACKNOWLEDGEMENT","PLACEMENT_NOUNS","screen","uninstallImpactView","pluginId","targets","impact","failed","losing","covered","scanning","affected","affectedScreens","alerts","tone","text","losingSites","truncated","join","placements","pages","chips","slice","placement","type","count","confirmLabel","needsAcknowledgement","installPlanOutcome","errors","installed","updating","saved","noun","toVersion","installedPluginCaption","siteLabels","MANIFEST_CONFIG_FIELD_LIMIT","MANIFEST_CONFIG_FIELD_TYPES","Set","coerceManifestConfigValue","field","raw","fallback","isFinite","NaN","isNaN","min","options","some","option","manifestSettingsFields","manifest","declared","config","rawFields","fields","seen","key","trim","has","add","description","rawDefaults","defaults","supplied","empty","MANIFEST_FIELD_KIND","string","number","boolean","select","manifestSettingsScreen","schema","out","kind","initial","band","help","written","Object","fromEntries","subtitle","icon","requires","constants","load","settings","doc","optional","blocks","object","footer","submit","write","updatedBy","success"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID;;;;;;CAMC,GAED;;;;;;;CAOC,GACD,OAAO,MAAMA,uBAAgE;IAC3EC,QAAQ;IACRC,WAAW;IACXC,UAAU;IACVC,QAAQ;IACRC,eAAe;IACfC,eAAe;IACfC,cAAc;IACdC,OAAO;IACPC,aAAa;AACf,EAAC;AAKD;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,kBAGT;IACFT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,CAAC,CAAC;SAAC;IAClG,OAAO;QACLxF,IAAI,CAAC,2BAA2B,EAAEkC,UAAU;QAC5Cf,OAAO,GAAGjB,MAAM,SAAS,CAAC;QAC1B8G,UAAU,CAAC,IAAI,EAAE9G,MAAM,2BAA2B,CAAC;QACnD+G,MAAM;QACNhL,OAAO;QACPiL,UAAU;QACVC,WAAW;YAAErB,UAAUS,OAAOT,QAAQ;QAAC;QACvCsB,MAAM;YAAEC,UAAU;gBAAEC,KAAK,CAAC,6BAA6B,EAAEpF,UAAU;gBAAEqF,UAAU;YAAK;QAAE;QACtFC,QAAQ;YACN;gBACElE,MAAM;gBACNtD,IAAI;gBACJyH,QAAQ;gBACRC,QAAQ;gBACRpC;gBACAqC,QAAQ;oBACNzH,OAAO;oBACP0H,OAAO;wBAAEN,KAAK,CAAC,6BAA6B,EAAEpF,UAAU;wBAAEoD,QAAQ,aAAKuB;4BAASgB,WAAW;;oBAAe;oBAC1GC,SAAS;gBACX;YACF;SACD;IACH;AACF"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/model/marketplace-catalog.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 type { InstallableArtifactType as MarketplaceArtifactType } from '@aglyn/aglyn/app-utils/artifact-provenance'\n\n/**\n * The marketplace's catalog vocabulary, pure (AGL-3668): what each artifact\n * type is called, where each installs, the categories, a plugin's install\n * state from its two pins, and which route installs a type and what its\n * install says. The native apps generate from it; `marketplace.ts` and the\n * install hook re-export and use it.\n */\n\n/**\n * Human-readable label for each artifact type (AGL-864).\n *\n * Shared by browse cards, the listing detail page, and the seller panel so\n * \"what kind of thing is this\" reads the same everywhere. Resolve a listing's\n * label through {@link listingArtifactLabel}, which tolerates the legacy\n * `type`/`kind` shape the way {@link listingArtifactType} does.\n */\nexport const ARTIFACT_TYPE_LABELS: Record<MarketplaceArtifactType, string> = {\n plugin: 'Plugin',\n component: 'Component',\n template: 'Site template',\n layout: 'Layout',\n datasetSchema: 'Dataset schema',\n emailTemplate: 'Email template',\n emailStarter: 'Email starter',\n theme: 'Theme',\n siteStarter: 'Site starter',\n}\n\n/** Where an installed artifact lives. */\nexport type InstallTarget = 'org' | 'host'\n\n/**\n * Install targets each artifact type actually supports (AGL-656).\n *\n * This is not a policy choice — it is where the install routes physically\n * write. Only plugins have an org-scoped pin\n * (`orgs/{orgId}/installs/{listingId}`, applying to every site, shadowed by\n * a host pin). Components land in `hosts/{h}/components`, templates and\n * layouts in `hosts/{h}/templates`: all host-scoped by nature, because a\n * screen tree belongs to a site.\n *\n * Exported so the UI can ask rather than assume — an install picker that\n * offers \"this whole organization\" for a template would be lying.\n */\nexport const INSTALL_TARGETS: Record<\n MarketplaceArtifactType,\n readonly InstallTarget[]\n> = {\n plugin: ['org', 'host'],\n component: ['host'],\n template: ['host'],\n layout: ['host'],\n // Dataset schemas are org-shared data (AGL-237), so they install at org\n // scope — as a new empty dataset, not a pin (AGL-657).\n datasetSchema: ['org'],\n emailTemplate: ['host'],\n // A campaign email is a screen, and a screen belongs to a site.\n emailStarter: ['host'],\n // A theme is one site's visual identity, written to `hosts/{h}.theme`\n // (AGL-1020). Applying one org-wide would repaint every site at once from a\n // control that says \"install\".\n theme: ['host'],\n // A site starter installs by creating a site from it (AGL-4049), never\n // into an existing one.\n siteStarter: ['host'],\n}\n\n/** A plugin install pin — the version-pinned doc the install API writes. */\nexport interface InstallPin {\n version?: number | string\n}\n\n/**\n * The install state of a plugin listing for one site, told honestly (AGL-656).\n *\n * A plugin can be pinned at two scopes: the org pin\n * (`orgs/{orgId}/installs/{listingId}`) applies to every site, and a host pin\n * (`hosts/{hostId}/installs/{listingId}`) applies to just this one AND shadows\n * the org pin. Detecting installs from `hosts/{h}/components` — the COMPONENT\n * collection — never sees either pin, so an installed plugin used to read as\n * \"not installed\" on both the browse grid and the detail page. This resolves\n * the effective state from the two pins the way the loader does.\n */\nexport interface PluginInstallState {\n /** Effective pin scope for this site — host wins over org — or null. */\n scope: InstallTarget | null\n /** Version pinned at the effective scope, or null when not installed. */\n installedVersion: string | null\n /** Both pins exist: the host pin takes precedence, shadowing the org one. */\n shadowed: boolean\n /** Installed, but the pinned version is behind the listing's latest. */\n updateAvailable: boolean\n}\n\n/**\n * Resolves a plugin listing's install state for a site from its two pins\n * (AGL-656). The host pin shadows the org pin, mirroring the loader, so the\n * effective version and update prompt always describe what actually runs here.\n */\nexport function resolvePluginInstallState(\n latestVersion: number | string | undefined,\n hostPin: InstallPin | null | undefined,\n orgPin: InstallPin | null | undefined,\n): PluginInstallState {\n const effective = hostPin ?? orgPin ?? null\n const installedVersion =\n effective?.version != null ? String(effective.version) : null\n return {\n scope: hostPin ? 'host' : orgPin ? 'org' : null,\n installedVersion,\n shadowed: Boolean(hostPin && orgPin),\n // Any difference is an upgrade prompt, matching the installed-plugins card\n // — pins only ever move forward, so \"different\" means \"behind\".\n updateAvailable:\n installedVersion != null &&\n latestVersion != null &&\n String(latestVersion) !== installedVersion,\n }\n}\n\n/** Fixed category taxonomy for marketplace listings (AGL-430). */\nexport const LISTING_CATEGORIES: readonly string[] = [\n 'analytics',\n 'automation',\n 'commerce',\n 'communication',\n 'content',\n 'design',\n 'forms',\n 'integrations',\n 'marketing',\n 'productivity',\n 'seo',\n 'security',\n] as const\n\n/**\n * Each artifact type has its own installer route (AGL-672): routing\n * everything to the component one silently installed the wrong thing or\n * 404'd. `listingArtifactType` tolerates the legacy `type`/`kind`\n * discriminators (AGL-654).\n */\nexport function marketplaceInstallEndpoint(artifactType: string): string {\n switch (artifactType) {\n case 'template':\n return 'marketplace/install-template'\n case 'layout':\n return 'marketplace/install-layout'\n case 'plugin':\n return 'marketplace/install-plugin'\n case 'datasetSchema':\n return 'marketplace/install-dataset-schema'\n case 'emailTemplate':\n return 'marketplace/install-email-template'\n case 'emailStarter':\n return 'marketplace/install-email-starter'\n case 'theme':\n return 'marketplace/install-theme'\n default:\n return 'marketplace/install'\n }\n}\n\n/**\n * Artifact types whose install deliberately does NOT touch the running site\n * (AGL-669/671/657) — the copy must not imply otherwise. Templates and layouts\n * land in the Templates library; an email template lands as an inactive\n * version the owner still has to activate.\n */\nexport function marketplaceLandingMessage(\n artifactType: string,\n displayName: string,\n): string | null {\n switch (artifactType) {\n case 'template':\n case 'layout':\n return (\n `Saved \"${displayName}\" to your Templates — nothing is live until ` +\n 'you use it.'\n )\n case 'emailTemplate':\n return (\n `Saved \"${displayName}\" as a draft version — activate it in the ` +\n 'email designer to start sending it.'\n )\n case 'emailStarter':\n // A copy, and saying so is the point: the publisher cannot reach it\n // again, and nothing goes out until a campaign is sent from it.\n return (\n `Added \"${displayName}\" to your Email templates as your own copy — ` +\n 'edit it freely, nothing is sent until you send a campaign.'\n )\n case 'datasetSchema':\n return `Created \"${displayName}\" as a new, empty dataset.`\n case 'theme':\n // The one type that DOES change the running site on install, so it gets\n // the opposite of the reassurance the others get — plus the way back,\n // because a repainted site is alarming if you cannot see how to undo it.\n return (\n `Applied \"${displayName}\" to this site. Setup → Theme has a way back ` +\n 'to your previous theme.'\n )\n default:\n return null\n }\n}\n\n/**\n * ─── WHAT A PLUGIN'S PAGE SAYS ABOUT ITS INSTALLS (AGL-1016, AGL-997, AGL-1027, AGL-3671) ───\n *\n * The version comparison, the update status, the org-wide picture of one listing's pins, which sites an\n * uninstall touches and the sentences the workspace's plugin pages and their dialogs say about them. All of\n * it was spread across `update-state.ts`, `marketplace.ts` and the plugin-site-set components; it lives here,\n * pure, so the native apps replay the very same answers (`libs/native/contracts/function-cases.generated.json`).\n * Those modules re-export what moved.\n */\n\n/**\n * Orders two artifact versions, or returns null when they cannot be ordered.\n *\n * Two numbering schemes are in play and both are real: copied artifacts get a\n * monotonic integer from the publish route, plugins get the semver string off\n * their manifest. A single string compare handles neither (\"10\" < \"9\",\n * \"1.10.0\" < \"1.9.0\"), so both are parsed as dotted numbers — which covers the\n * integer case as a one-segment version.\n *\n * Anything non-numeric (a prerelease tag, a date-stamped build) is not ordered\n * by guesswork: unequal-and-incomparable is reported as such and surfaces as\n * `unknown`, which is honest, where a string compare would confidently point\n * an update button at an older build.\n */\nexport function compareArtifactVersions(\n a: string | number | null | undefined,\n b: string | number | null | undefined,\n): -1 | 0 | 1 | null {\n if (a == null || b == null || a === '' || b === '') return null\n const left = String(a)\n const right = String(b)\n if (left === right) return 0\n const parse = (value: string): number[] | null => {\n const parts = value.split('.')\n const numbers: number[] = []\n for (const part of parts) {\n if (!/^\\d+$/.test(part)) return null\n numbers.push(Number(part))\n }\n return numbers.length ? numbers : null\n }\n const leftParts = parse(left)\n const rightParts = parse(right)\n if (!leftParts || !rightParts) return null\n const length = Math.max(leftParts.length, rightParts.length)\n for (let index = 0; index < length; index += 1) {\n const leftPart = leftParts[index] ?? 0\n const rightPart = rightParts[index] ?? 0\n if (leftPart < rightPart) return -1\n if (leftPart > rightPart) return 1\n }\n // Equal numerically but not as strings — \"1.0\" and \"1.0.0\" are the same\n // version written two ways.\n return 0\n}\n\nexport type UpdateState =\n /** Running the newest version the publisher offers. */\n | 'current'\n /** A newer version exists and can be taken. */\n | 'update-available'\n /**\n * Installed version is NEWER than what is offered. Not a bug: a publisher\n * installs their own unapproved version to test it, and a version can be\n * withdrawn after someone installed it.\n */\n | 'ahead'\n /** Not enough is known to say — no provenance, or nothing published to compare. */\n | 'unknown'\n\nexport interface UpdateStatus {\n state: UpdateState\n /** The version running, or null when provenance cannot say. */\n installedVersion: string | null\n /** The newest version on offer — for plugins, the newest APPROVED one. */\n availableVersion: string | null\n /**\n * Why the answer is `unknown`, for a UI that should say which kind of\n * silence this is rather than implying the artifact is current.\n */\n unknownReason?: 'no-provenance' | 'nothing-published' | 'incomparable'\n}\n\n/**\n * One sentence describing an update state, so four surfaces do not each invent\n * their own wording for the same fact.\n */\nexport function updateStateLabel(status: UpdateStatus): string {\n switch (status.state) {\n case 'update-available':\n return `You have v${status.installedVersion} · v${status.availableVersion} available`\n case 'current':\n return `Up to date · v${status.installedVersion}`\n case 'ahead':\n return `You have v${status.installedVersion}, newer than the published v${status.availableVersion}`\n default:\n return status.unknownReason === 'nothing-published'\n ? 'No published version to compare against'\n : status.unknownReason === 'incomparable'\n ? `You have v${status.installedVersion}; v${status.availableVersion} cannot be ordered against it`\n : 'Installed before update tracking — version unknown'\n }\n}\n\n/** The pin fields an update comparison reads, in every shape the install routes have written. */\nexport interface UpdateComparablePin {\n version?: unknown\n installedFrom?: { listingId?: string; version?: unknown } | null\n marketplace?: { listingId?: string; version?: unknown } | null\n source?: { listingId?: string; version?: unknown } | null\n listingId?: string\n}\n\n/**\n * What a listing OFFERS right now (the plugin branch of `offeredPluginVersion`): the newest approved version, unless a\n * revocation (`versions` naming it, or `'all'`) has stopped it, in which case nothing is offered.\n */\nexport function pluginOfferedVersion(\n latestApprovedVersion: unknown,\n revocationVersions: readonly string[] | 'all' | null | undefined,\n): string | null {\n const offered = String(latestApprovedVersion ?? '')\n if (!offered) return null\n if (revocationVersions === 'all') return null\n return Array.isArray(revocationVersions) && revocationVersions.includes(offered) ? null : offered\n}\n\n/**\n * Whether the installed plugin is still what the publisher ships (the plugin branch of `resolveUpdateState`): the\n * pin's version against the version on offer. A pin that names no listing is the one shape that records no version\n * (`no-provenance`).\n */\nexport function pluginUpdateStatus(\n pin: UpdateComparablePin | null | undefined,\n offeredVersion: string | null | undefined,\n): UpdateStatus {\n const unknown: UpdateStatus = { state: 'unknown', installedVersion: null, availableVersion: null, unknownReason: 'no-provenance' }\n if (!pin) return unknown\n const recorded = pin.installedFrom?.listingId\n ? pin.installedFrom.version\n : pin.marketplace?.listingId\n ? pin.marketplace.version\n : pin.source?.listingId\n ? pin.source.version\n : pin.listingId\n ? pin.version\n : undefined\n const installedVersion = recorded == null || recorded === '' ? null : String(recorded)\n if (!installedVersion) return unknown\n if (offeredVersion == null || offeredVersion === '') {\n return { state: 'unknown', installedVersion, availableVersion: null, unknownReason: 'nothing-published' }\n }\n const availableVersion = String(offeredVersion)\n const order = compareArtifactVersions(installedVersion, availableVersion)\n if (order === null) return { state: 'unknown', installedVersion, availableVersion, unknownReason: 'incomparable' }\n return { state: order === 0 ? 'current' : order < 0 ? 'update-available' : 'ahead', installedVersion, availableVersion }\n}\n\n\n/** One site's slice of an org-scope install picture (AGL-997). */\nexport interface OrgInstallSite {\n hostId: string\n label: string\n /** The version that actually runs here, from the effective pin. */\n version: string | null\n /** Where that pin lives — a host pin shadows the org one, as the loader does. */\n pinnedBy: InstallTarget\n /** This site has its OWN pin on top of an org pin. */\n shadowed: boolean\n /**\n * Pinned here, but the site's own Admin › Plugins switch has it off (its\n * `disabledPlugins` holds the listing id, AGL-4047), so it does not run\n * here. Present only when true, and only when the caller handed over the\n * sites' lists and the listing id.\n */\n switchedOff?: true\n}\n\n/** A site as the install picture reads it: its id, its name, and the plugins it switched off. */\nexport interface OrgInstallHost {\n id: string\n label: string\n /** The site's own deny-list (`disabledPlugins`), when the caller has it. */\n disabledPlugins?: readonly string[] | null\n}\n\n/**\n * The whole org's install picture for one listing (AGL-997).\n *\n * At org scope, \"installed\" is a SET, not a boolean. The detail page used to\n * resolve state against the single acting host, so a plugin installed on one\n * of five sites reported \"Installed on this site\" — describing one arbitrary\n * site and staying silent about the other four — and offered an Uninstall\n * that was all-or-nothing.\n *\n * `orgWide` and per-site pins are not exclusive: an org pin covers every\n * site including ones created later, and a host pin on top of it shadows it\n * for that one site. Both facts have to survive into the UI, which is why\n * this returns the sites AND the pins rather than a single scope.\n */\nexport interface OrgInstallSummary {\n /** An org pin exists: every site is covered, including future ones. */\n orgWide: boolean\n /** Version of the org pin, when there is one. */\n orgVersion: string | null\n /** Every site the listing effectively runs on. */\n sites: OrgInstallSite[]\n /** Sites carrying their own removable host pin. */\n hostPinnedIds: string[]\n /** Sites with no pin of their own and no org pin covering them. */\n availableHostIds: string[]\n installedAnywhere: boolean\n}\n\n/**\n * `listingId` (AGL-4047): a pin is not the whole answer. A site whose own\n * switch has the listing off (`disabledPlugins`, written by its Admin ›\n * Plugins page or by an install that left it out) keeps its pin or its org\n * coverage but runs nothing, exactly as the realm join drops it. Given the id\n * and each site's list, such a site is marked `switchedOff`; without them the\n * picture is the pins alone, as before.\n */\nexport function resolveOrgInstallSummary(\n hosts: ReadonlyArray<OrgInstallHost>,\n hostPins: Readonly<Record<string, InstallPin | null | undefined>>,\n orgPin: InstallPin | null | undefined,\n listingId?: string,\n): OrgInstallSummary {\n const orgWide = Boolean(orgPin)\n const orgVersion = orgPin?.version != null ? String(orgPin.version) : null\n const sites: OrgInstallSite[] = []\n const hostPinnedIds: string[] = []\n const availableHostIds: string[] = []\n for (const host of hosts) {\n const hostPin = hostPins[host.id]\n if (hostPin) hostPinnedIds.push(host.id)\n if (!hostPin && !orgPin) {\n availableHostIds.push(host.id)\n continue\n }\n sites.push({\n hostId: host.id,\n label: host.label,\n version:\n hostPin?.version != null ? String(hostPin.version) : orgVersion,\n pinnedBy: hostPin ? 'host' : 'org',\n shadowed: Boolean(hostPin && orgPin),\n ...(listingId && host.disabledPlugins?.includes(listingId)\n ? { switchedOff: true as const }\n : {}),\n })\n }\n return {\n orgWide,\n orgVersion,\n sites,\n hostPinnedIds,\n availableHostIds,\n installedAnywhere: orgWide || hostPinnedIds.length > 0,\n }\n}\n\n/** One site an uninstall would touch, and whether it really loses the plugin. */\nexport interface UninstallTarget {\n hostId: string\n label: string\n /**\n * The plugin keeps running here. Removing a HOST pin while an org pin still\n * covers the site, or the ORG pin while the site holds its own host pin,\n * changes which pointer is in use and nothing a visitor can see.\n */\n stillCovered: boolean\n}\n\n/**\n * Which sites an uninstall actually affects (AGL-1027).\n *\n * The shadowing case is the whole reason this is a function rather than a\n * filter at the call site. A pin is not a boolean per site: an org pin covers\n * everything, a host pin names one site, and where both exist the host pin\n * wins. So \"remove\" means three different things depending on which pointer is\n * being dropped and what is left underneath — and the one thing the dialog must\n * never do is tell someone a plugin will stop working when it will not.\n *\n * Returns every site the operation touches, including the ones that keep the\n * plugin, so the dialog can say so explicitly instead of omitting them and\n * leaving the count unexplained.\n */\nexport function resolveUninstallTargets(\n orgInstall: OrgInstallSummary,\n scope: 'org' | 'host',\n hostId?: string,\n): UninstallTarget[] {\n if (scope === 'host') {\n const site = orgInstall.sites.find((entry) => entry.hostId === hostId)\n if (!site) return []\n // Its own pin goes; the org pin, if there is one, still covers it.\n return [\n { hostId: site.hostId, label: site.label, stillCovered: orgInstall.orgWide },\n ]\n }\n // Dropping the org pin: every site loses it EXCEPT those holding a host pin\n // of their own, which were already shadowing the org pin anyway.\n return orgInstall.sites.map((site) => ({\n hostId: site.hostId,\n label: site.label,\n stillCovered: site.pinnedBy === 'host',\n }))\n}\n\n// ─── The sentences of a plugin's install pages and their dialogs (AGL-1017, AGL-1027, AGL-3671) ───\n\n/** The sites of an org-wide picture whose running version is behind the one on offer. */\nexport function staleSites(sites: readonly OrgInstallSite[], latestVersion: string | number | null | undefined): OrgInstallSite[] {\n return sites.filter((site) => (compareArtifactVersions(site.version, latestVersion) ?? 0) < 0)\n}\n\n/** What \"Where it runs\" opens with: the whole organization, or how many of its sites. */\nexport function pluginSiteSetSummary(install: OrgInstallSummary, siteCount: number): string {\n // Sites whose own switch has it off (AGL-4047): pinned, but not running.\n const off = install.sites.filter((site) => site.switchedOff).map((site) => site.label)\n if (install.orgWide) {\n const head = `Installed for the whole organization (v${install.orgVersion})`\n if (!off.length) return `${head} — every site, including ones you add later.`\n return off.length === install.sites.length\n ? `${head}. Every site switched it off, so it runs only on sites you add later.`\n : `${head}. It runs on every site except ${namesList(off)}, which switched it off, and on sites you add later.`\n }\n const head = `Installed on ${install.sites.length} of ${siteCount} sites`\n if (!off.length) return `${head}.`\n const running = install.sites.length - off.length\n return `${head}. ${namesList(off)} switched it off, so it runs on ${running ? running : 'none of them'}.`\n}\n\n/** \"A\", \"A and B\", \"A, B and C\". */\nfunction namesList(names: readonly string[]): string {\n return names.length < 2 ? (names[0] ?? '') : `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`\n}\n\n/** What the update confirmation says: the plugin, the version it moves to and where, and what stays put. */\nexport function pluginUpdatePrompt(input: {\n name: string\n latestVersion: string\n label: string\n /** The update is for one site: other sites stay on the version they run. */\n singleSite: boolean\n}): { title: string; body: string; others: string | null; note: string } {\n return {\n title: `Update to v${input.latestVersion}?`,\n body: `${input.name} moves from the version running now to v${input.latestVersion} on ${input.label}.`,\n others: input.singleSite ? 'Other sites stay on the version they are running.' : null,\n note: 'Pins only move forward — there is no going back to the previous version from here.',\n }\n}\n\n/** What the update button of a pin that is org-wide, or of the stale per-site ones, is called and aims at. */\nexport function pluginUpdateAll(install: OrgInstallSummary, stale: readonly OrgInstallSite[], latestVersion: string) {\n return {\n label: install.orgWide ? `Update to v${latestVersion}` : `Update all ${stale.length} to v${latestVersion}`,\n target: install.orgWide ? 'every site in this organization' : `${stale.length} site${stale.length === 1 ? '' : 's'}`,\n hostIds: install.orgWide ? null : stale.map((site) => site.hostId),\n }\n}\n\n/** The notice above an org-wide update: one pin moves every site at once. */\nexport const PLUGIN_ORG_WIDE_UPDATE_NOTE =\n 'This is one organization-wide pin, so updating moves every site at once. To take a version on one site first, install per site instead.'\n\n/** One site an uninstall dialog was told about by the impact check. */\nexport interface UninstallImpactSite {\n hostId: string\n label: string\n stillCovered: boolean\n placements: Array<{ type: 'screen' | 'layout' | 'component'; id: string; name: string; count: number }>\n affectedScreens: number\n truncated: boolean\n}\n\n/** What `/api/hosts/plugin-impact` answers. */\nexport interface UninstallImpact {\n sites: UninstallImpactSite[]\n losingSites: number\n placements: number\n affectedScreens: number\n truncated: boolean\n dataSurvives: boolean\n}\n\n/** The word typed to confirm an uninstall that breaks pages, or whose impact could not be checked. */\nexport const UNINSTALL_ACKNOWLEDGEMENT = 'UNINSTALL'\n\n/** What the uninstall dialog shows, worked out from the targets and the impact check's answer. */\nexport interface UninstallImpactView {\n title: string\n confirmLabel: string\n /** The check is still running. */\n scanning: boolean\n /** Alerts above the sites, in order. */\n alerts: Array<{ tone: 'warning' | 'error' | 'info'; text: string }>\n /** Sites that lose the plugin and place it on pages: the site, how many pages, and the chips. */\n sites: Array<{ label: string; pages: string; chips: string[] }>\n /** The closing note, when sites lose the plugin. */\n note: string | null\n /** Pages stop rendering it, or the check could not say: the person types {@link UNINSTALL_ACKNOWLEDGEMENT}. */\n needsAcknowledgement: boolean\n}\n\nconst PLACEMENT_NOUNS = { screen: 'page', layout: 'layout', component: 'component' } as const\n\n/** The uninstall dialog (`UninstallImpactDialog`) as data, so every client says the same things. */\nexport function uninstallImpactView(input: {\n name: string\n scope: 'org' | 'host'\n /** The listing's plugin id; without one the placements cannot be found. */\n pluginId: string\n targets: readonly UninstallTarget[]\n /** The impact check's answer, once it has come. */\n impact: UninstallImpact | null\n /** The impact check failed. */\n failed: boolean\n}): UninstallImpactView {\n const { name, scope, pluginId, targets, impact, failed } = input\n const losing = targets.filter((target) => !target.stillCovered)\n const covered = targets.filter((target) => target.stillCovered)\n const scanning = Boolean(pluginId) && losing.length > 0 && !impact && !failed\n const affected = impact?.affectedScreens ?? 0\n const unknown = failed || (!pluginId && losing.length > 0)\n const alerts: UninstallImpactView['alerts'] = []\n if (unknown && !scanning) {\n alerts.push({\n tone: 'warning',\n text: pluginId\n ? 'The impact check could not run, so this cannot say what would stop working. Nothing here means \"nothing breaks\".'\n : 'This listing records no plugin id, so its placements cannot be found. Pages using it may stop rendering it.',\n })\n }\n if (!scanning && !unknown && affected > 0) {\n const sites = impact?.losingSites ?? losing.length\n alerts.push({\n tone: 'error',\n text:\n `Removes ${name} from ${sites} site${sites === 1 ? '' : 's'}; ` +\n `${impact?.truncated ? 'at least ' : ''}${affected} published page${affected === 1 ? '' : 's'} ` +\n `place${affected === 1 ? 's' : ''} it and will stop rendering it.`,\n })\n }\n if (!scanning && !unknown && affected === 0 && losing.length) {\n alerts.push({ tone: 'info', text: 'No published page places this plugin, so nothing visitors can see changes.' })\n }\n if (covered.length) {\n alerts.push({\n tone: 'info',\n text:\n covered.length === targets.length\n ? `The plugin keeps running on ${covered.length === 1 ? 'this site' : `all ${covered.length} of these sites`}, ` +\n `because another install still covers ${covered.length === 1 ? 'it' : 'them'}. Only which version is in use changes.`\n : `${covered.length} of these sites keep the plugin — ${covered.map((target) => target.label).join(', ')} — ` +\n 'because another install still covers them.',\n })\n }\n const sites = (impact?.sites ?? [])\n .filter((site) => !site.stillCovered && site.placements.length)\n .map((site) => ({\n label: site.label,\n pages: `${site.affectedScreens} published page${site.affectedScreens === 1 ? '' : 's'} affected`,\n chips: [\n ...site.placements\n .slice(0, 12)\n .map((placement) => `${PLACEMENT_NOUNS[placement.type]}: ${placement.name}${placement.count > 1 ? ` ×${placement.count}` : ''}`),\n ...(site.placements.length > 12 ? [`+${site.placements.length - 12} more`] : []),\n ],\n }))\n return {\n title: scope === 'org' ? `Uninstall ${name} across the organization?` : `Remove ${name} from this site?`,\n confirmLabel: scope === 'org' ? 'Uninstall org-wide' : 'Remove',\n scanning,\n alerts,\n sites,\n note:\n !scanning && losing.length\n ? 'Uninstalling removes the install only. The plugin’s settings and any data it stored are kept, and installing it again restores the pages that place it.'\n : null,\n needsAcknowledgement: !scanning && (affected > 0 || unknown),\n }\n}\n\n/** What a run of installs (an install, an update, or the several steps of one) says once it is done. */\nexport function installPlanOutcome(input: {\n name: string\n /** Steps that went through, and the refusals of those that did not. */\n installed: number\n errors: readonly string[]\n /** One of the steps was the org-wide pin. */\n orgWide: boolean\n /** The steps moved existing pins to {@link version}. */\n updating: boolean\n version?: string | null\n /** The artifact lands in a library and is not live (a template, a layout): \"Saved\", not \"Installed\". */\n saved?: boolean\n /** Sites the org-wide pin left out, \"All sites except…\" (AGL-4047). */\n leftOut?: number\n}): { tone: 'success' | 'warning' | 'error'; text: string } {\n const { name, installed, errors, orgWide, updating, version, saved } = input\n const leftOut = input.leftOut ?? 0\n const noun = updating ? 'Updated' : saved ? 'Saved' : 'Installed'\n const toVersion = updating && version != null ? ` to v${version}` : ''\n if (installed && !errors.length) {\n return {\n tone: 'success',\n text: orgWide\n ? leftOut > 0\n ? `${noun} \"${name}\"${toVersion} for every site but ${leftOut === 1 ? 'the one' : `the ${leftOut}`} you left out, and for sites you add later`\n : `${noun} \"${name}\"${toVersion} for the whole organization`\n : `${noun} \"${name}\"${toVersion} on ${installed} site${installed === 1 ? '' : 's'}`,\n }\n }\n if (installed && errors.length) {\n return { tone: 'warning', text: `${noun} on ${installed} site(s); ${errors.length} failed — ${errors[0]}` }\n }\n return { tone: 'error', text: errors[0] ?? 'Install failed' }\n}\n\n/** The row of the plugins list for one install: the version and where it runs. */\nexport function installedPluginCaption(input: { version?: unknown; orgWide: boolean; siteLabels: readonly string[] }): string {\n return (\n `v${input.version} · ` +\n (input.orgWide ? 'every site in this organization' : input.siteLabels.length === 1 ? input.siteLabels[0] : `${input.siteLabels.length} sites`)\n )\n}\n\n// ─── A marketplace plugin's settings, from its manifest (AGL-428, AGL-3671) ───\n\nconst MANIFEST_CONFIG_FIELD_LIMIT = 50\nconst MANIFEST_CONFIG_FIELD_TYPES: ReadonlySet<string> = new Set(['string', 'number', 'boolean', 'select'])\n\ninterface ManifestConfigField {\n key: string\n label: string\n type: 'string' | 'number' | 'boolean' | 'select'\n description?: string\n options?: Array<{ value: string; label: string }>\n min?: number\n max?: number\n}\n\n/** A stored or declared value as its field takes it (`coerce` of `plugin-config.ts`), else [fallback]. */\nfunction coerceManifestConfigValue(field: ManifestConfigField, raw: unknown, fallback: unknown): unknown {\n switch (field.type) {\n case 'boolean':\n return typeof raw === 'boolean' ? raw : fallback\n case 'number': {\n const value = typeof raw === 'number' && Number.isFinite(raw) ? raw : NaN\n if (Number.isNaN(value)) return fallback\n if (field.min != null && value < field.min) return field.min\n if (field.max != null && value > field.max) return field.max\n return value\n }\n case 'select': {\n const value = typeof raw === 'string' ? raw : undefined\n return field.options?.some((option) => option.value === value) ? value : fallback\n }\n default:\n return typeof raw === 'string' ? raw : fallback\n }\n}\n\n/**\n * The fields a plugin's MANIFEST declares for its settings and the values they start from (`pluginConfigSchemaFromManifest`\n * of `plugin-config.ts`, which this repeats without its imports so the native apps replay it). Everything is re-validated\n * rather than trusted: a junk type drops the field, a duplicate key drops the second, a select with nothing to select is\n * dropped, and the count is capped. `null` when the manifest declares nothing usable, which means \"this plugin has no\n * settings\".\n */\nexport function manifestSettingsFields(manifest: unknown): { fields: ManifestConfigField[]; defaults: Record<string, unknown> } | null {\n const declared = (manifest as { config?: unknown } | null | undefined)?.config\n const rawFields = (declared as { fields?: unknown } | undefined)?.fields\n if (!Array.isArray(rawFields)) return null\n const seen = new Set<string>()\n const fields: ManifestConfigField[] = []\n for (const raw of rawFields) {\n if (fields.length >= MANIFEST_CONFIG_FIELD_LIMIT) break\n const entry = raw as Record<string, unknown> | null\n const key = typeof entry?.['key'] === 'string' ? entry['key'].trim() : ''\n if (!key || seen.has(key)) continue\n const type = String(entry?.['type'] ?? 'string')\n if (!MANIFEST_CONFIG_FIELD_TYPES.has(type)) continue\n const options = Array.isArray(entry?.['options'])\n ? (entry['options'] as unknown[])\n .map((option) => option as Record<string, unknown> | null)\n .filter((option) => typeof option?.['value'] === 'string' && typeof option?.['label'] === 'string')\n .map((option) => ({ value: String(option?.['value']), label: String(option?.['label']) }))\n : undefined\n if (type === 'select' && !options?.length) continue\n seen.add(key)\n fields.push({\n key,\n label: typeof entry?.['label'] === 'string' && entry['label'].trim() ? String(entry['label']).slice(0, 120) : key,\n type: type as ManifestConfigField['type'],\n description: typeof entry?.['description'] === 'string' ? String(entry['description']).slice(0, 400) : undefined,\n options,\n min: typeof entry?.['min'] === 'number' ? entry['min'] : undefined,\n max: typeof entry?.['max'] === 'number' ? entry['max'] : undefined,\n })\n }\n if (!fields.length) return null\n const rawDefaults = (declared as { defaults?: unknown } | undefined)?.defaults\n const defaults: Record<string, unknown> = {}\n for (const field of fields) {\n const supplied = rawDefaults && typeof rawDefaults === 'object' ? (rawDefaults as Record<string, unknown>)[field.key] : undefined\n const empty =\n field.type === 'boolean' ? false : field.type === 'number' ? (field.min ?? 0) : field.type === 'select' ? (field.options?.[0]?.value ?? '') : ''\n defaults[field.key] = coerceManifestConfigValue(field, supplied, empty)\n }\n return { fields, defaults }\n}\n\nconst MANIFEST_FIELD_KIND = { string: 'text', number: 'number', boolean: 'toggle', select: 'select' } as const\n\n/**\n * The workspace-settings screen of a marketplace plugin, as a native screen spec: the console's `PluginConfigCards` for a\n * pin's manifest. The same shape the generated screens of the built-in plugins have (`pluginSettingsScreen` of\n * `native-plugin-settings.mjs`), under an id of its own, saved to `orgs/{org}/pluginSettings/{plugin}` as the console\n * saves it. `null` for a plugin that declares no settings.\n */\nexport function manifestSettingsScreen(pluginId: string, label: string, manifest: unknown): Record<string, unknown> | null {\n const schema = pluginId ? manifestSettingsFields(manifest) : null\n if (!schema) return null\n const fields = schema.fields.map((field) => {\n const out: Record<string, unknown> = {\n key: field.key,\n label: field.label,\n kind: MANIFEST_FIELD_KIND[field.type],\n // `??` keeps a stored false or 0, which `|` would skip for the default.\n initial: `{item.${field.key} ?? const.defaults.${field.key}}`,\n }\n if (field.type === 'select') out['options'] = (field.options ?? []).map(({ value, label: text }) => ({ value, label: text }))\n const band = field.type === 'number' && (field.min != null || field.max != null) ? `Between ${field.min ?? 'any'} and ${field.max ?? 'any'}.` : ''\n const help = [field.description, band].filter(Boolean).join(' ')\n if (help) out['help'] = help\n return out\n })\n const written = Object.fromEntries(schema.fields.map((field) => [field.key, `{form.${field.key}}`]))\n return {\n id: `marketplace.pluginSettings.${pluginId}`,\n title: `${label} settings`,\n subtitle: `How ${label} behaves for this workspace`,\n icon: 'gearshape|settings',\n scope: 'org',\n requires: 'org.can[org.settings]',\n constants: { defaults: schema.defaults },\n load: { settings: { doc: `orgs/{org.id}/pluginSettings/${pluginId}`, optional: true } },\n blocks: [\n {\n type: 'form',\n id: 'settings',\n object: 'data.settings',\n footer: 'A site can override these on its own plugin page.',\n fields,\n submit: {\n label: 'Save settings',\n write: { doc: `orgs/{org.id}/pluginSettings/${pluginId}`, fields: { ...written, updatedBy: '{user.uid}' } },\n success: 'Settings saved',\n },\n },\n ],\n }\n}\n"],"names":["ARTIFACT_TYPE_LABELS","plugin","component","template","layout","datasetSchema","emailTemplate","emailStarter","theme","siteStarter","INSTALL_TARGETS","resolvePluginInstallState","latestVersion","hostPin","orgPin","effective","installedVersion","version","String","scope","shadowed","Boolean","updateAvailable","LISTING_CATEGORIES","marketplaceInstallEndpoint","artifactType","marketplaceLandingMessage","displayName","compareArtifactVersions","a","b","left","right","parse","value","parts","split","numbers","part","test","push","Number","length","leftParts","rightParts","Math","max","index","leftPart","rightPart","updateStateLabel","status","state","availableVersion","unknownReason","pluginOfferedVersion","latestApprovedVersion","revocationVersions","offered","Array","isArray","includes","pluginUpdateStatus","pin","offeredVersion","unknown","recorded","installedFrom","listingId","marketplace","source","undefined","order","resolveOrgInstallSummary","hosts","hostPins","orgWide","orgVersion","sites","hostPinnedIds","availableHostIds","host","id","hostId","label","pinnedBy","disabledPlugins","switchedOff","installedAnywhere","resolveUninstallTargets","orgInstall","site","find","entry","stillCovered","map","staleSites","filter","pluginSiteSetSummary","install","siteCount","off","head","namesList","running","names","slice","join","pluginUpdatePrompt","input","title","body","name","others","singleSite","note","pluginUpdateAll","stale","target","hostIds","PLUGIN_ORG_WIDE_UPDATE_NOTE","UNINSTALL_ACKNOWLEDGEMENT","PLACEMENT_NOUNS","screen","uninstallImpactView","pluginId","targets","impact","failed","losing","covered","scanning","affected","affectedScreens","alerts","tone","text","losingSites","truncated","placements","pages","chips","placement","type","count","confirmLabel","needsAcknowledgement","installPlanOutcome","errors","installed","updating","saved","leftOut","noun","toVersion","installedPluginCaption","siteLabels","MANIFEST_CONFIG_FIELD_LIMIT","MANIFEST_CONFIG_FIELD_TYPES","Set","coerceManifestConfigValue","field","raw","fallback","isFinite","NaN","isNaN","min","options","some","option","manifestSettingsFields","manifest","declared","config","rawFields","fields","seen","key","trim","has","add","description","rawDefaults","defaults","supplied","empty","MANIFEST_FIELD_KIND","string","number","boolean","select","manifestSettingsScreen","schema","out","kind","initial","band","help","written","Object","fromEntries","subtitle","icon","requires","constants","load","settings","doc","optional","blocks","object","footer","submit","write","updatedBy","success"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAID;;;;;;CAMC,GAED;;;;;;;CAOC,GACD,OAAO,MAAMA,uBAAgE;IAC3EC,QAAQ;IACRC,WAAW;IACXC,UAAU;IACVC,QAAQ;IACRC,eAAe;IACfC,eAAe;IACfC,cAAc;IACdC,OAAO;IACPC,aAAa;AACf,EAAC;AAKD;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,kBAGT;IACFT,QAAQ;QAAC;QAAO;KAAO;IACvBC,WAAW;QAAC;KAAO;IACnBC,UAAU;QAAC;KAAO;IAClBC,QAAQ;QAAC;KAAO;IAChB,wEAAwE;IACxE,uDAAuD;IACvDC,eAAe;QAAC;KAAM;IACtBC,eAAe;QAAC;KAAO;IACvB,gEAAgE;IAChEC,cAAc;QAAC;KAAO;IACtB,sEAAsE;IACtE,4EAA4E;IAC5E,+BAA+B;IAC/BC,OAAO;QAAC;KAAO;IACf,uEAAuE;IACvE,wBAAwB;IACxBC,aAAa;QAAC;KAAO;AACvB,EAAC;AA6BD;;;;CAIC,GACD,OAAO,SAASE,0BACdC,aAA0C,EAC1CC,OAAsC,EACtCC,MAAqC;QAEnBD;IAAlB,MAAME,aAAYF,OAAAA,kBAAAA,UAAWC,kBAAXD,OAAqB;IACvC,MAAMG,mBACJD,CAAAA,6BAAAA,UAAWE,OAAO,KAAI,OAAOC,OAAOH,UAAUE,OAAO,IAAI;IAC3D,OAAO;QACLE,OAAON,UAAU,SAASC,SAAS,QAAQ;QAC3CE;QACAI,UAAUC,QAAQR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