@aglyn/plugins-marketplace 1.0.0-beta.206 → 1.0.0-beta.209
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-marketplace",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.209",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,19 +25,19 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.0.0-beta.
|
|
29
|
-
"@aglyn/aglyn-markdown-editor": "1.0.0-beta.
|
|
30
|
-
"@aglyn/shared-data-enums": "1.0.0-beta.
|
|
31
|
-
"@aglyn/shared-data-mdi": "1.0.0-beta.
|
|
32
|
-
"@aglyn/shared-ui-jsx": "1.0.0-beta.
|
|
33
|
-
"@aglyn/shared-ui-next": "1.0.0-beta.
|
|
34
|
-
"@aglyn/shared-ui-snackstack": "1.0.0-beta.
|
|
35
|
-
"@aglyn/shared-util-email": "1.0.0-beta.
|
|
36
|
-
"@aglyn/shared-util-http": "1.0.0-beta.
|
|
37
|
-
"@aglyn/shared-util-timestamp": "1.0.0-beta.
|
|
38
|
-
"@aglyn/tenant-data-admin": "1.0.0-beta.
|
|
39
|
-
"@aglyn/tenant-feature-instance": "1.0.0-beta.
|
|
40
|
-
"@aglyn/tenant-runtime": "1.0.0-beta.
|
|
28
|
+
"@aglyn/aglyn": "1.0.0-beta.209",
|
|
29
|
+
"@aglyn/aglyn-markdown-editor": "1.0.0-beta.209",
|
|
30
|
+
"@aglyn/shared-data-enums": "1.0.0-beta.209",
|
|
31
|
+
"@aglyn/shared-data-mdi": "1.0.0-beta.209",
|
|
32
|
+
"@aglyn/shared-ui-jsx": "1.0.0-beta.209",
|
|
33
|
+
"@aglyn/shared-ui-next": "1.0.0-beta.209",
|
|
34
|
+
"@aglyn/shared-ui-snackstack": "1.0.0-beta.209",
|
|
35
|
+
"@aglyn/shared-util-email": "1.0.0-beta.209",
|
|
36
|
+
"@aglyn/shared-util-http": "1.0.0-beta.209",
|
|
37
|
+
"@aglyn/shared-util-timestamp": "1.0.0-beta.209",
|
|
38
|
+
"@aglyn/tenant-data-admin": "1.0.0-beta.209",
|
|
39
|
+
"@aglyn/tenant-feature-instance": "1.0.0-beta.209",
|
|
40
|
+
"@aglyn/tenant-runtime": "1.0.0-beta.209",
|
|
41
41
|
"@swc/helpers": "0.5.23"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
@@ -37,6 +37,10 @@ import { type PluginApiHandler } from '@aglyn/aglyn/server';
|
|
|
37
37
|
*
|
|
38
38
|
* `preview` changes nothing and returns what the swap would do, so the
|
|
39
39
|
* confirmation can name it rather than showing a JSON blob.
|
|
40
|
+
*
|
|
41
|
+
* Every action that writes the theme then drops the site's cached pages
|
|
42
|
+
* (AGL-3386). The theme styles every page and nothing publishes it, so
|
|
43
|
+
* without the drop "the site repaints" meant "within the hour".
|
|
40
44
|
*/
|
|
41
45
|
export declare const installThemeHandler: PluginApiHandler;
|
|
42
46
|
export default installThemeHandler;
|
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
* limitations under the License.
|
|
16
16
|
*/ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
17
17
|
import { describeTheme } from "@aglyn/aglyn/app-utils/marketplace-theme";
|
|
18
|
+
import { dropPluginSiteCache } from "@aglyn/aglyn/plugin-manager/plugin-site-cache";
|
|
18
19
|
import { firebaseAdmin } from "@aglyn/tenant-data-admin";
|
|
19
20
|
import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
|
|
20
21
|
import { isPrivateListing, listingArtifactType } from "../model/marketplace.js";
|
|
@@ -45,6 +46,10 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
|
|
|
45
46
|
*
|
|
46
47
|
* `preview` changes nothing and returns what the swap would do, so the
|
|
47
48
|
* confirmation can name it rather than showing a JSON blob.
|
|
49
|
+
*
|
|
50
|
+
* Every action that writes the theme then drops the site's cached pages
|
|
51
|
+
* (AGL-3386). The theme styles every page and nothing publishes it, so
|
|
52
|
+
* without the drop "the site repaints" meant "within the hour".
|
|
48
53
|
*/ export const installThemeHandler = async (req, res)=>{
|
|
49
54
|
var _ref, _ref1, _req_headers_authorization;
|
|
50
55
|
var _req_body, _req_body1, _req_body2;
|
|
@@ -99,6 +104,15 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
|
|
|
99
104
|
}
|
|
100
105
|
const now = firebaseAdmin.firestore.FieldValue.serverTimestamp();
|
|
101
106
|
const currentTheme = (_hostSnapshot_get1 = hostSnapshot.get('theme')) != null ? _hostSnapshot_get1 : null;
|
|
107
|
+
// Awaited before the response, because a serverless function may be
|
|
108
|
+
// frozen once it has answered. Never throws: a drop that fails leaves the
|
|
109
|
+
// theme saved and the hour-long cache as the backstop.
|
|
110
|
+
const repaintLiveSite = (action)=>dropPluginSiteCache({
|
|
111
|
+
hostIds: [
|
|
112
|
+
hostId
|
|
113
|
+
],
|
|
114
|
+
reason: `marketplace theme ${action}`
|
|
115
|
+
});
|
|
102
116
|
// ---- reset: back to the platform default ----
|
|
103
117
|
if (action === 'reset') {
|
|
104
118
|
await hostRef.set({
|
|
@@ -116,6 +130,7 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
|
|
|
116
130
|
}, {
|
|
117
131
|
merge: true
|
|
118
132
|
});
|
|
133
|
+
await repaintLiveSite('reset');
|
|
119
134
|
return res.status(200).json({
|
|
120
135
|
reset: true
|
|
121
136
|
});
|
|
@@ -131,6 +146,7 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
|
|
|
131
146
|
}, {
|
|
132
147
|
merge: true
|
|
133
148
|
});
|
|
149
|
+
await repaintLiveSite('overrides cleared');
|
|
134
150
|
return res.status(200).json({
|
|
135
151
|
cleared: true
|
|
136
152
|
});
|
|
@@ -160,6 +176,7 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
|
|
|
160
176
|
}), {
|
|
161
177
|
merge: true
|
|
162
178
|
});
|
|
179
|
+
await repaintLiveSite('reverted');
|
|
163
180
|
return res.status(200).json({
|
|
164
181
|
reverted: true
|
|
165
182
|
});
|
|
@@ -287,6 +304,7 @@ import { isPublisherSecurityLocked } from "./sale-risk.js";
|
|
|
287
304
|
}, {
|
|
288
305
|
merge: true
|
|
289
306
|
});
|
|
307
|
+
await repaintLiveSite('installed');
|
|
290
308
|
await recordVersionMove({
|
|
291
309
|
firestore,
|
|
292
310
|
listingRef,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-theme.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 PluginApiHandler } from '@aglyn/aglyn/server'\nimport { describeTheme } from '@aglyn/aglyn/app-utils/marketplace-theme'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n isPrivateListing,\n listingArtifactType,\n} from '../model/marketplace'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { hasDivergedFromBase, recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Installs a marketplace theme onto a site (AGL-1020).\n *\n * Themes are the exception to \"installing never changes a running site\". A\n * template or a layout can land inert in a library because it is one thing\n * among many; a theme IS the site's appearance, and installing one into a\n * library where it does nothing would be a control that appears to work and\n * does not. So this writes `hosts/{hostId}.theme` and the site repaints.\n *\n * Which makes reversibility the requirement, not a nicety. Two things provide\n * it, and neither is a confirmation dialog:\n *\n * * The theme being replaced is kept verbatim in `themeReplaced`, so `revert`\n * restores exactly what was there — including a hand-built theme that was\n * never a marketplace artifact and exists nowhere else.\n * * `reset` clears the theme entirely, which is the \"use the default theme\"\n * the issue asks to keep first-class. It is a distinct action from revert\n * because \"back to how it was\" and \"back to stock\" are different intents and\n * guessing between them is how people lose work.\n *\n * `preview` changes nothing and returns what the swap would do, so the\n * confirmation can name it rather than showing a JSON blob.\n */\nexport const installThemeHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const action = ['revert', 'reset', 'preview', 'clear-overrides'].includes(\n req.body?.action,\n )\n ? (req.body.action as\n | 'revert'\n | 'reset'\n | 'preview'\n | 'clear-overrides')\n : 'install'\n const listingId = String(req.body?.listingId ?? '')\n if (!hostId || (action === 'install' && !listingId)) {\n return res.status(400).json({ error: 'Missing listingId or hostId' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow installing from the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n const currentTheme = hostSnapshot.get('theme') ?? null\n\n // ---- reset: back to the platform default ----\n if (action === 'reset') {\n await hostRef.set(\n {\n // Kept, not dropped: resetting is reversible for the same reason\n // installing is, and someone who resets by mistake has otherwise\n // lost a theme that existed in no other document.\n themeReplaced: { theme: currentTheme, replacedAt: now },\n theme: firebaseAdmin.firestore.FieldValue.delete(),\n themeInstalledFrom: firebaseAdmin.firestore.FieldValue.delete(),\n themeOverride: firebaseAdmin.firestore.FieldValue.delete(),\n updatedAt: now,\n },\n { merge: true },\n )\n return res.status(200).json({ reset: true })\n }\n\n // ---- clear-overrides: drop this site's changes, keep the theme ----\n // The third way back, and the narrowest: \"reset to the publisher's\n // version\" is deleting the patch — the whole point of owning the patch\n // rather than the copy (AGL-1019). The theme itself is untouched.\n if (action === 'clear-overrides') {\n await hostRef.set(\n {\n themeOverride: firebaseAdmin.firestore.FieldValue.delete(),\n updatedAt: now,\n },\n { merge: true },\n )\n return res.status(200).json({ cleared: true })\n }\n\n // ---- revert: back to whatever this site had before the last swap ----\n if (action === 'revert') {\n const replaced = hostSnapshot.get('themeReplaced')\n if (!replaced) {\n return res.status(409).json({\n error: 'There is no previous theme to go back to on this site.',\n })\n }\n await hostRef.set(\n {\n theme: replaced.theme ?? firebaseAdmin.firestore.FieldValue.delete(),\n ...(replaced.installedFrom\n ? { themeInstalledFrom: replaced.installedFrom }\n : { themeInstalledFrom: firebaseAdmin.firestore.FieldValue.delete() }),\n // The overrides that were live alongside that theme come back with\n // it. Reverting the base and keeping a patch authored against the\n // theme being reverted FROM is the one combination nobody asked for.\n ...(replaced.override\n ? { themeOverride: replaced.override }\n : { themeOverride: firebaseAdmin.firestore.FieldValue.delete() }),\n themeReplaced: firebaseAdmin.firestore.FieldValue.delete(),\n updatedAt: now,\n },\n { merge: true },\n )\n return res.status(200).json({ reverted: true })\n }\n\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (\n !listing ||\n listing.deletedAt ||\n // Staff takedown blocks new installs on EVERY artifact type\n // (AGL-2290). AGL-948 extended takedown past plugins in the browse\n // predicate and in `resolveMarketplacePluginVersion`, but the gate that\n // decides whether content is HANDED OVER was only ever added to\n // `install-plugin.ts`. So a component, theme, template, layout, email\n // template or dataset schema that staff had taken down stayed\n // installable by anyone holding its listing id — which makes takedown a\n // suggestion for six of the seven artifact types.\n //\n // No owner exemption, matching `install-plugin.ts`: a takedown is a\n // moderation decision about the artifact, not about who is asking.\n listing.hiddenAt ||\n // A publisher under a SECURITY lock hands nothing over (AGL-3365).\n (await isPublisherSecurityLocked(firestore, listing.profileId)) ||\n listingArtifactType(listing) !== 'theme'\n ) {\n return res.status(404).json({ error: 'Unknown theme' })\n }\n\n const priceUsd = Number(listing.priceUsd ?? 0)\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n // Private listings install ONLY for the owning org (AGL-2290).\n //\n // `install-plugin.ts` has carried this since AGL-968; the other six never\n // did, so a private component, theme, template, layout, email template or\n // dataset schema was installable by anyone who knew its listing id. Browse\n // hides them and the detail page 404s, but neither is a control — the\n // route is.\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // A FULLY refunded purchase stops entitling (AGL-1546), and until\n // AGL-1699 only the component route knew that: this one asked whether a\n // purchase doc EXISTED, so buy/install/refund kept the artifact. The\n // predicate lives in one place now so the next route cannot miss it.\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n // THE ORG THE LICENCE HAS TO COVER (AGL-2331). `membership.orgId` is\n // resolved server-side from the caller's own membership by the\n // permission gate above — never a request-body field — so this is the\n // workspace the install actually lands in, and the only one a purchase\n // can entitle here.\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n const theme = versionSnapshot.get('theme')\n if (!theme || !Object.keys(theme).length) {\n return res.status(500).json({ error: 'Theme version missing' })\n }\n\n // ---- preview: say what the swap changes, change nothing ----\n if (action === 'preview') {\n return res.status(200).json({\n incoming: describeTheme(theme),\n current: describeTheme(currentTheme),\n // A site with no theme is on the platform default, so there is nothing\n // to lose and the confirmation should not imply there is.\n replaces: Boolean(currentTheme && Object.keys(currentTheme).length),\n version: listing.latestVersion ?? null,\n })\n }\n\n // ---- install ----\n // Replacing a theme the workspace has edited destroys those edits (AGL-1018).\n // Unlike a component this is not recoverable by looking in a library — the\n // theme lives on one field on one document — so the refusal matters more.\n const diverged = await hasDivergedFromBase({\n firestore,\n sha256: hostSnapshot.get('themeInstalledFrom.sha256'),\n current: currentTheme,\n })\n if (diverged && req.body?.mode !== 'replace') {\n return res.status(409).json({\n error:\n 'This site’s theme has been edited since it was installed. Review ' +\n 'the update to see what would change.',\n diverged: true,\n })\n }\n\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: 'theme',\n content: theme,\n })\n const previousVersion =\n hostSnapshot.get('themeInstalledFrom.version') ?? null\n\n await hostRef.set(\n {\n theme,\n themeInstalledFrom: provenance.installedFrom,\n // Everything needed to put this site back exactly as it was, captured\n // BEFORE the write that changes it.\n themeReplaced: {\n theme: currentTheme,\n ...(hostSnapshot.get('themeInstalledFrom')\n ? { installedFrom: hostSnapshot.get('themeInstalledFrom') }\n : {}),\n ...(hostSnapshot.get('themeOverride')\n ? { override: hostSnapshot.get('themeOverride') }\n : {}),\n replacedAt: now,\n },\n // Overrides SURVIVE a theme swap (AGL-1021). A site that set its brand\n // colour still means it under a new theme, and silently discarding\n // that on install would be the more surprising of the two options.\n //\n // What must not happen is surviving *silently*: the override keeps the\n // `baseSha256` it was authored against, which no longer matches the\n // theme now installed, so `isOverrideForCurrentTheme` is false and the\n // editor says so with an offer to clear them. Rewriting that hash here\n // would launder a patch written for another theme into one that claims\n // to belong to this one.\n updatedAt: now,\n },\n { merge: true },\n )\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'theme',\n from: previousVersion,\n to: listing.latestVersion,\n })\n await listingRef\n .update({\n installCount: firebaseAdmin.firestore.FieldValue.increment(1),\n })\n .catch(() => undefined)\n\n return res.status(200).json({\n installed: true,\n version: listing.latestVersion ?? null,\n baseStored: provenance.baseStored,\n applied: describeTheme(theme),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Theme install failed' })\n }\n}\n\nexport default installThemeHandler\n"],"names":["describeTheme","firebaseAdmin","resolveOrgPermissions","isPrivateListing","listingArtifactType","canActAsPublisher","requirePurchase","hasDivergedFromBase","recordInstallProvenance","recordVersionMove","isPublisherSecurityLocked","installThemeHandler","req","res","method","status","json","error","hostId","String","body","action","includes","listingId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","memberRole","now","FieldValue","serverTimestamp","currentTheme","set","themeReplaced","theme","replacedAt","delete","themeInstalledFrom","themeOverride","updatedAt","merge","reset","cleared","replaced","installedFrom","override","reverted","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","Number","ownsListing","unpaid","buyerUid","buyerOrgId","orgId","versionSnapshot","latestVersion","Object","keys","incoming","current","replaces","Boolean","version","diverged","sha256","mode","provenance","artifactType","content","previousVersion","from","to","update","installCount","increment","catch","installed","baseStored","applied","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,aAAa,QAAQ,2CAA0C;AACxE,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,gBAA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EE;YACAG,oBAAoBmC,WAAW5B,aAAa;YAC5C,sEAAsE;YACtE,oCAAoC;YACpCX,eAAe;gBACbC,OAAOH;eACHpB,aAAac,GAAG,CAAC,wBACjB;gBAAEmB,eAAejC,aAAac,GAAG,CAAC;YAAsB,IACxD,CAAC,GACDd,aAAac,GAAG,CAAC,mBACjB;gBAAEoB,UAAUlC,aAAac,GAAG,CAAC;YAAiB,IAC9C,CAAC;gBACLU,YAAYP;;YAEd,uEAAuE;YACvE,mEAAmE;YACnE,mEAAmE;YACnE,EAAE;YACF,uEAAuE;YACvE,oEAAoE;YACpE,uEAAuE;YACvE,uEAAuE;YACvE,uEAAuE;YACvE,yBAAyB;YACzBW,WAAWX;QACb,GACA;YAAEY,OAAO;QAAK;QAGhB,MAAMnD,kBAAkB;YACtBgC;YACA0B;YACA0B,cAAc;YACdG,MAAMD;YACNE,IAAIjE,QAAQiD,aAAa;QAC3B;QACA,MAAMd,WACH+B,MAAM,CAAC;YACNC,cAAclG,cAAcwC,SAAS,CAACQ,UAAU,CAACmD,SAAS,CAAC;QAC7D,GACCC,KAAK,CAAC,IAAMvE;QAEf,OAAOjB,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BsF,WAAW;YACXd,OAAO,GAAExD,yBAAAA,QAAQiD,aAAa,YAArBjD,yBAAyB;YAClCuE,YAAYX,WAAWW,UAAU;YACjCC,SAASxG,cAAcsD;QACzB;IACF,EAAE,OAAOrC,OAAO;QACdwF,QAAQxF,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAuB;IAC9D;AACF,EAAC;AAED,eAAeN,oBAAmB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/install-theme.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 PluginApiHandler } from '@aglyn/aglyn/server'\nimport { describeTheme } from '@aglyn/aglyn/app-utils/marketplace-theme'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n isPrivateListing,\n listingArtifactType,\n} from '../model/marketplace'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { hasDivergedFromBase, recordInstallProvenance } from './provenance'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Installs a marketplace theme onto a site (AGL-1020).\n *\n * Themes are the exception to \"installing never changes a running site\". A\n * template or a layout can land inert in a library because it is one thing\n * among many; a theme IS the site's appearance, and installing one into a\n * library where it does nothing would be a control that appears to work and\n * does not. So this writes `hosts/{hostId}.theme` and the site repaints.\n *\n * Which makes reversibility the requirement, not a nicety. Two things provide\n * it, and neither is a confirmation dialog:\n *\n * * The theme being replaced is kept verbatim in `themeReplaced`, so `revert`\n * restores exactly what was there — including a hand-built theme that was\n * never a marketplace artifact and exists nowhere else.\n * * `reset` clears the theme entirely, which is the \"use the default theme\"\n * the issue asks to keep first-class. It is a distinct action from revert\n * because \"back to how it was\" and \"back to stock\" are different intents and\n * guessing between them is how people lose work.\n *\n * `preview` changes nothing and returns what the swap would do, so the\n * confirmation can name it rather than showing a JSON blob.\n *\n * Every action that writes the theme then drops the site's cached pages\n * (AGL-3386). The theme styles every page and nothing publishes it, so\n * without the drop \"the site repaints\" meant \"within the hour\".\n */\nexport const installThemeHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.body?.hostId ?? '')\n const action = ['revert', 'reset', 'preview', 'clear-overrides'].includes(\n req.body?.action,\n )\n ? (req.body.action as\n | 'revert'\n | 'reset'\n | 'preview'\n | 'clear-overrides')\n : 'install'\n const listingId = String(req.body?.listingId ?? '')\n if (!hostId || (action === 'install' && !listingId)) {\n return res.status(400).json({ error: 'Missing listingId or hostId' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow installing from the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (memberRole !== 'admin' && memberRole !== 'editor') {\n return res.status(403).json({ error: 'Not a site admin or editor' })\n }\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n const currentTheme = hostSnapshot.get('theme') ?? null\n // Awaited before the response, because a serverless function may be\n // frozen once it has answered. Never throws: a drop that fails leaves the\n // theme saved and the hour-long cache as the backstop.\n const repaintLiveSite = (action: string) =>\n dropPluginSiteCache({\n hostIds: [hostId],\n reason: `marketplace theme ${action}`,\n })\n\n // ---- reset: back to the platform default ----\n if (action === 'reset') {\n await hostRef.set(\n {\n // Kept, not dropped: resetting is reversible for the same reason\n // installing is, and someone who resets by mistake has otherwise\n // lost a theme that existed in no other document.\n themeReplaced: { theme: currentTheme, replacedAt: now },\n theme: firebaseAdmin.firestore.FieldValue.delete(),\n themeInstalledFrom: firebaseAdmin.firestore.FieldValue.delete(),\n themeOverride: firebaseAdmin.firestore.FieldValue.delete(),\n updatedAt: now,\n },\n { merge: true },\n )\n await repaintLiveSite('reset')\n return res.status(200).json({ reset: true })\n }\n\n // ---- clear-overrides: drop this site's changes, keep the theme ----\n // The third way back, and the narrowest: \"reset to the publisher's\n // version\" is deleting the patch — the whole point of owning the patch\n // rather than the copy (AGL-1019). The theme itself is untouched.\n if (action === 'clear-overrides') {\n await hostRef.set(\n {\n themeOverride: firebaseAdmin.firestore.FieldValue.delete(),\n updatedAt: now,\n },\n { merge: true },\n )\n await repaintLiveSite('overrides cleared')\n return res.status(200).json({ cleared: true })\n }\n\n // ---- revert: back to whatever this site had before the last swap ----\n if (action === 'revert') {\n const replaced = hostSnapshot.get('themeReplaced')\n if (!replaced) {\n return res.status(409).json({\n error: 'There is no previous theme to go back to on this site.',\n })\n }\n await hostRef.set(\n {\n theme: replaced.theme ?? firebaseAdmin.firestore.FieldValue.delete(),\n ...(replaced.installedFrom\n ? { themeInstalledFrom: replaced.installedFrom }\n : { themeInstalledFrom: firebaseAdmin.firestore.FieldValue.delete() }),\n // The overrides that were live alongside that theme come back with\n // it. Reverting the base and keeping a patch authored against the\n // theme being reverted FROM is the one combination nobody asked for.\n ...(replaced.override\n ? { themeOverride: replaced.override }\n : { themeOverride: firebaseAdmin.firestore.FieldValue.delete() }),\n themeReplaced: firebaseAdmin.firestore.FieldValue.delete(),\n updatedAt: now,\n },\n { merge: true },\n )\n await repaintLiveSite('reverted')\n return res.status(200).json({ reverted: true })\n }\n\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (\n !listing ||\n listing.deletedAt ||\n // Staff takedown blocks new installs on EVERY artifact type\n // (AGL-2290). AGL-948 extended takedown past plugins in the browse\n // predicate and in `resolveMarketplacePluginVersion`, but the gate that\n // decides whether content is HANDED OVER was only ever added to\n // `install-plugin.ts`. So a component, theme, template, layout, email\n // template or dataset schema that staff had taken down stayed\n // installable by anyone holding its listing id — which makes takedown a\n // suggestion for six of the seven artifact types.\n //\n // No owner exemption, matching `install-plugin.ts`: a takedown is a\n // moderation decision about the artifact, not about who is asking.\n listing.hiddenAt ||\n // A publisher under a SECURITY lock hands nothing over (AGL-3365).\n (await isPublisherSecurityLocked(firestore, listing.profileId)) ||\n listingArtifactType(listing) !== 'theme'\n ) {\n return res.status(404).json({ error: 'Unknown theme' })\n }\n\n const priceUsd = Number(listing.priceUsd ?? 0)\n const ownsListing = await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n )\n // Private listings install ONLY for the owning org (AGL-2290).\n //\n // `install-plugin.ts` has carried this since AGL-968; the other six never\n // did, so a private component, theme, template, layout, email template or\n // dataset schema was installable by anyone who knew its listing id. Browse\n // hides them and the detail page 404s, but neither is a control — the\n // route is.\n if (isPrivateListing(listing) && !ownsListing) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // A FULLY refunded purchase stops entitling (AGL-1546), and until\n // AGL-1699 only the component route knew that: this one asked whether a\n // purchase doc EXISTED, so buy/install/refund kept the artifact. The\n // predicate lives in one place now so the next route cannot miss it.\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n // THE ORG THE LICENCE HAS TO COVER (AGL-2331). `membership.orgId` is\n // resolved server-side from the caller's own membership by the\n // permission gate above — never a request-body field — so this is the\n // workspace the install actually lands in, and the only one a purchase\n // can entitle here.\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing,\n })\n if (unpaid) return res.status(402).json(unpaid)\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n const theme = versionSnapshot.get('theme')\n if (!theme || !Object.keys(theme).length) {\n return res.status(500).json({ error: 'Theme version missing' })\n }\n\n // ---- preview: say what the swap changes, change nothing ----\n if (action === 'preview') {\n return res.status(200).json({\n incoming: describeTheme(theme),\n current: describeTheme(currentTheme),\n // A site with no theme is on the platform default, so there is nothing\n // to lose and the confirmation should not imply there is.\n replaces: Boolean(currentTheme && Object.keys(currentTheme).length),\n version: listing.latestVersion ?? null,\n })\n }\n\n // ---- install ----\n // Replacing a theme the workspace has edited destroys those edits (AGL-1018).\n // Unlike a component this is not recoverable by looking in a library — the\n // theme lives on one field on one document — so the refusal matters more.\n const diverged = await hasDivergedFromBase({\n firestore,\n sha256: hostSnapshot.get('themeInstalledFrom.sha256'),\n current: currentTheme,\n })\n if (diverged && req.body?.mode !== 'replace') {\n return res.status(409).json({\n error:\n 'This site’s theme has been edited since it was installed. Review ' +\n 'the update to see what would change.',\n diverged: true,\n })\n }\n\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: 'theme',\n content: theme,\n })\n const previousVersion =\n hostSnapshot.get('themeInstalledFrom.version') ?? null\n\n await hostRef.set(\n {\n theme,\n themeInstalledFrom: provenance.installedFrom,\n // Everything needed to put this site back exactly as it was, captured\n // BEFORE the write that changes it.\n themeReplaced: {\n theme: currentTheme,\n ...(hostSnapshot.get('themeInstalledFrom')\n ? { installedFrom: hostSnapshot.get('themeInstalledFrom') }\n : {}),\n ...(hostSnapshot.get('themeOverride')\n ? { override: hostSnapshot.get('themeOverride') }\n : {}),\n replacedAt: now,\n },\n // Overrides SURVIVE a theme swap (AGL-1021). A site that set its brand\n // colour still means it under a new theme, and silently discarding\n // that on install would be the more surprising of the two options.\n //\n // What must not happen is surviving *silently*: the override keeps the\n // `baseSha256` it was authored against, which no longer matches the\n // theme now installed, so `isOverrideForCurrentTheme` is false and the\n // editor says so with an offer to clear them. Rewriting that hash here\n // would launder a patch written for another theme into one that claims\n // to belong to this one.\n updatedAt: now,\n },\n { merge: true },\n )\n\n await repaintLiveSite('installed')\n\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType: 'theme',\n from: previousVersion,\n to: listing.latestVersion,\n })\n await listingRef\n .update({\n installCount: firebaseAdmin.firestore.FieldValue.increment(1),\n })\n .catch(() => undefined)\n\n return res.status(200).json({\n installed: true,\n version: listing.latestVersion ?? null,\n baseStored: provenance.baseStored,\n applied: describeTheme(theme),\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Theme install failed' })\n }\n}\n\nexport default installThemeHandler\n"],"names":["describeTheme","dropPluginSiteCache","firebaseAdmin","resolveOrgPermissions","isPrivateListing","listingArtifactType","canActAsPublisher","requirePurchase","hasDivergedFromBase","recordInstallProvenance","recordVersionMove","isPublisherSecurityLocked","installThemeHandler","req","res","method","status","json","error","hostId","String","body","action","includes","listingId","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","listing","membership","decoded","app","auth","verifyIdToken","uid","permissions","installPlugins","firestore","hostRef","collection","doc","get","exists","memberRole","now","FieldValue","serverTimestamp","currentTheme","repaintLiveSite","hostIds","reason","set","themeReplaced","theme","replacedAt","delete","themeInstalledFrom","themeOverride","updatedAt","merge","reset","cleared","replaced","installedFrom","override","reverted","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","Number","ownsListing","unpaid","buyerUid","buyerOrgId","orgId","versionSnapshot","latestVersion","Object","keys","incoming","current","replaces","Boolean","version","diverged","sha256","mode","provenance","artifactType","content","previousVersion","from","to","update","installCount","increment","catch","installed","baseStored","applied","console"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC;AAGD,SAASA,aAAa,QAAQ,2CAA0C;AACxE,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,gBAAgB,EAChBC,mBAAmB,QACd,0BAAsB;AAC7B,SAASC,iBAAiB,QAAQ,yBAAqB;AACvD,SAASC,eAAe,QAAQ,4BAAwB;AACxD,SAASC,mBAAmB,EAAEC,uBAAuB,QAAQ,kBAAc;AAC3E,SAASC,iBAAiB,QAAQ,qBAAiB;AACnD,SAASC,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CAAjBd,qBAAkD;QAEpD,MAAMW,QAAQa,GAAG,CACf;YACEE;YACAG,oBAAoBmC,WAAW5B,aAAa;YAC5C,sEAAsE;YACtE,oCAAoC;YACpCX,eAAe;gBACbC,OAAON;eACHpB,aAAac,GAAG,CAAC,wBACjB;gBAAEsB,eAAepC,aAAac,GAAG,CAAC;YAAsB,IACxD,CAAC,GACDd,aAAac,GAAG,CAAC,mBACjB;gBAAEuB,UAAUrC,aAAac,GAAG,CAAC;YAAiB,IAC9C,CAAC;gBACLa,YAAYV;;YAEd,uEAAuE;YACvE,mEAAmE;YACnE,mEAAmE;YACnE,EAAE;YACF,uEAAuE;YACvE,oEAAoE;YACpE,uEAAuE;YACvE,uEAAuE;YACvE,uEAAuE;YACvE,yBAAyB;YACzBc,WAAWd;QACb,GACA;YAAEe,OAAO;QAAK;QAGhB,MAAMX,gBAAgB;QAEtB,MAAM3C,kBAAkB;YACtBgC;YACA6B;YACA0B,cAAc;YACdG,MAAMD;YACNE,IAAIpE,QAAQoD,aAAa;QAC3B;QACA,MAAMd,WACH+B,MAAM,CAAC;YACNC,cAAcrG,cAAcwC,SAAS,CAACQ,UAAU,CAACsD,SAAS,CAAC;QAC7D,GACCC,KAAK,CAAC,IAAM1E;QAEf,OAAOjB,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1ByF,WAAW;YACXd,OAAO,GAAE3D,yBAAAA,QAAQoD,aAAa,YAArBpD,yBAAyB;YAClC0E,YAAYX,WAAWW,UAAU;YACjCC,SAAS5G,cAAc0D;QACzB;IACF,EAAE,OAAOxC,OAAO;QACd2F,QAAQ3F,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAuB;IAC9D;AACF,EAAC;AAED,eAAeN,oBAAmB"}
|
|
@@ -21,6 +21,7 @@ import { artifactCreateListKeys } from "@aglyn/aglyn/app-utils/artifact-list-key
|
|
|
21
21
|
import { createResourceUid, decodeStoredNodes, encodeStoredNodes, newResourceScopeFields, ORG_SCOPE_TOKEN } from "@aglyn/aglyn/server";
|
|
22
22
|
import { applyArtifactUpdate, planArtifactUpdate, summarizeSchemaChange } from "../model/artifact-merge.js";
|
|
23
23
|
import { ARTIFACT_BASE_COLLECTION } from "@aglyn/aglyn/app-utils/marketplace-provenance";
|
|
24
|
+
import { dropPluginSiteCache } from "@aglyn/aglyn/plugin-manager/plugin-site-cache";
|
|
24
25
|
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
25
26
|
import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
|
|
26
27
|
import { listingArtifactType, resolveInstalledDatasetSchema } from "../model/marketplace.js";
|
|
@@ -456,6 +457,18 @@ export const updateArtifactHandler = async (req, res)=>{
|
|
|
456
457
|
}), {
|
|
457
458
|
merge: true
|
|
458
459
|
});
|
|
460
|
+
// A merged THEME repaints every page of the site the moment it lands,
|
|
461
|
+
// and nothing publishes it — so the site's cached pages go now rather
|
|
462
|
+
// than within the hour (AGL-3386). Awaited before the response, and it
|
|
463
|
+
// never throws: a failed drop leaves the update applied.
|
|
464
|
+
if (artifactType === 'theme') {
|
|
465
|
+
await dropPluginSiteCache({
|
|
466
|
+
hostIds: [
|
|
467
|
+
hostId
|
|
468
|
+
],
|
|
469
|
+
reason: 'marketplace theme updated'
|
|
470
|
+
});
|
|
471
|
+
}
|
|
459
472
|
// Per-version tally (AGL-1036): this install just moved versions, which
|
|
460
473
|
// is the whole reason the per-version count exists.
|
|
461
474
|
await recordVersionMove({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/update-artifact.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The leaf module, not the server barrel: the list keys every artifact\n// create stamps (AGL-3321), which the install specs' closed-world barrel\n// mocks have no reason to stage.\nimport { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport {\n createResourceUid,\n decodeStoredNodes,\n encodeStoredNodes,\n newResourceScopeFields,\n ORG_SCOPE_TOKEN,\n type PluginApiHandler,\n type ScopeToken,\n} from '@aglyn/aglyn/server'\nimport {\n applyArtifactUpdate,\n planArtifactUpdate,\n summarizeSchemaChange,\n type ArtifactChange,\n type ArtifactUpdatePlan,\n} from '../model/artifact-merge'\nimport { ARTIFACT_BASE_COLLECTION } from '@aglyn/aglyn/app-utils/marketplace-provenance'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n listingArtifactType,\n resolveInstalledDatasetSchema,\n} from '../model/marketplace'\nimport { readPublishedProps } from '../model/marketplace-props'\nimport { recordInstallProvenance } from './provenance'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Updating a COPIED marketplace artifact (AGL-1018).\n *\n * The install routes update by overwriting: a component re-install writes the\n * publisher's tree straight over the workspace's copy, and a template or layout\n * re-install soft-deletes the previous bundle. Both are silent, and both throw\n * away work the customer did after installing.\n *\n * This route never overwrites without saying what will be lost. `preview`\n * classifies every field against AGL-1015's base snapshot and returns the plan;\n * `apply` writes only what the plan (and, for conflicts, the caller) chose.\n * There are two ways to take a new version and both are safe:\n *\n * * **merge** — take the publisher's changes to fields nobody here edited, keep\n * this workspace's edits, and overwrite a contested field only when it was\n * explicitly picked.\n * * **copy** — install the new version fresh and DETACH the customised copy,\n * which keeps it as an ordinary workspace artifact rather than deleting it.\n *\n * Without a base snapshot only `copy` is offered. Inventing an origin to diff\n * against is how a merge becomes confidently wrong.\n */\n\ntype Mode = 'merge' | 'copy'\n\n/** What a preview tells the client, and what the dialog renders. */\ninterface UpdatePreview {\n artifactType: string\n installedVersion: string | null\n availableVersion: string | null\n /** A three-way merge is possible: a base snapshot exists and the type supports it. */\n mergeable: boolean\n /** Why not, when it isn't. */\n reason?: string\n safe: ArtifactChange[]\n kept: ArtifactChange[]\n conflicts: ArtifactChange[]\n unchanged: number\n identical: boolean\n /** Dataset schemas only: what the change does to existing records. */\n schema?: {\n added: string[]\n removed: string[]\n retyped: string[]\n additiveOnly: boolean\n recordCount: number\n }\n}\n\n/** Everything the route needs to diff and write one copied artifact. */\ninterface Target {\n ref: FirebaseFirestore.DocumentReference\n /** The copy as it is now, in the same shape the base snapshot holds. */\n current: unknown\n /** Fields to write alongside merged content. */\n write: (content: any) => Record<string, unknown>\n /** Fields that detach this copy from its listing, for `copy` mode. */\n detach?: Record<string, unknown>\n /**\n * The AGL-1037 scope the FORKED copy is created with, or `null` when the\n * destination collection is not scoped (AGL-1478).\n *\n * Required, and required on purpose. `copy` mode writes a brand-new\n * document into `target.ref.parent` — whatever collection that turns out\n * to be — from a spread of carried fields, and a spread cannot carry a\n * field the source never had. For `orgs/{orgId}/datasets` that is the\n * AGL-1466 bug exactly: an unstamped dataset is not \"unrestricted\", it is\n * matched by no `array-contains-any` reader in the product, so it renders\n * on no site and is missing from the workflows and reference-health cards\n * even for an org-wide member.\n *\n * Making it optional with a sensible default would have been the smaller\n * diff and is the thing that fails: the two `mediaFolders` creators that\n * each forgot `visibleTo` were both written by people who had the field\n * in front of them. A sixth artifact type cannot be added here without\n * answering this, which is the only guarantee that survives a stranger.\n *\n * `null` is a real answer, not an escape hatch: components live in\n * `hosts/{hostId}/components` and layouts in `hosts/{hostId}/templates`,\n * both private to their host by construction and neither carrying a scope.\n */\n forkScope: readonly ScopeToken[] | null\n /**\n * The declared properties the new version carries (AGL-2933), for a\n * component or layout, sanitized; `undefined` when the version was published\n * before properties were carried, or the type declares none.\n *\n * Not part of the merged content. Every base snapshot recorded before this\n * field existed holds only the tree, so diffing properties three ways would\n * read each installed copy's declarations as a local edit to keep. They are\n * the publisher's contract with the tree instead: whatever the merge takes\n * of the nodes binds to them, so the incoming list replaces the installed\n * one, in both modes.\n */\n props?: ReturnType<typeof readPublishedProps>\n}\n\nconst trimChanges = (changes: ArtifactChange[]): ArtifactChange[] =>\n // The dialog lists changes; a 400-node tree that changed wholesale would\n // otherwise ship its entire content twice through a JSON response.\n changes.slice(0, 200)\n\nexport const updateArtifactHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const listingId = String(req.body?.listingId ?? '')\n const hostId = String(req.body?.hostId ?? '')\n const action = req.body?.action === 'apply' ? 'apply' : 'preview'\n const mode: Mode = req.body?.mode === 'copy' ? 'copy' : 'merge'\n const takePaths: string[] = Array.isArray(req.body?.takePaths)\n ? req.body.takePaths.map((path: unknown) => String(path))\n : []\n const confirmDestructive = Boolean(req.body?.confirmDestructive)\n if (!listingId || !hostId) {\n return res.status(400).json({ error: 'Missing listingId or hostId' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n // The same gate installing uses: taking a new version of something is\n // installing it, and a role that cannot install must not be able to\n // rewrite an installed artifact through a different door.\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error: 'Your organization role does not allow installing from the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (\n !listing ||\n listing.deletedAt ||\n // Staff takedown blocks new installs on EVERY artifact type\n // (AGL-2290). AGL-948 extended takedown past plugins in the browse\n // predicate and in `resolveMarketplacePluginVersion`, but the gate that\n // decides whether content is HANDED OVER was only ever added to\n // `install-plugin.ts`. So a component, theme, template, layout, email\n // template or dataset schema that staff had taken down stayed\n // installable by anyone holding its listing id — which makes takedown a\n // suggestion for six of the seven artifact types.\n //\n // No owner exemption, matching `install-plugin.ts`: a takedown is a\n // moderation decision about the artifact, not about who is asking.\n listing.hiddenAt ||\n // A publisher under a SECURITY lock hands nothing over (AGL-3365).\n (await isPublisherSecurityLocked(firestore, listing.profileId))\n ) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // Taking a NEW version of a paid listing is buying content, and this\n // route never asked whether the caller still owned it (AGL-1699). The\n // install routes gate; this one only checked the org ROLE, so a buyer\n // who was refunded — and even in `copy` mode, which installs the new\n // version fresh — kept pulling every future paid release through here.\n //\n // Deliberately not a regression for anyone legitimate: a live purchase,\n // a free listing, or the publisher's own listing all pass, and nobody\n // without one of those could have had an installed copy to update.\n // The `priceUsd > 0` test is out here rather than left to the helper so\n // a free listing — most of them — does not pay for a publisher lookup.\n const priceUsd = Number(listing.priceUsd ?? 0)\n if (priceUsd > 0) {\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n // THE ORG THE LICENCE HAS TO COVER (AGL-2331). `membership.orgId` is\n // resolved server-side from the caller's own membership by the\n // permission gate above — never a request-body field — so this is the\n // workspace the install actually lands in, and the only one a purchase\n // can entitle here.\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing: await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n ),\n })\n if (unpaid) return res.status(402).json(unpaid)\n }\n\n const artifactType = listingArtifactType(listing)\n if (artifactType === 'plugin') {\n // Plugins are pinned, not copied: an update moves a pointer at immutable\n // bytes (AGL-1017) and has nothing to merge.\n return res.status(400).json({\n error: 'Plugins update by re-pinning — use the install route',\n })\n }\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n if (!versionSnapshot.exists) {\n return res.status(404).json({ error: 'Listing version missing' })\n }\n const availableVersion =\n listing.latestVersion == null ? null : String(listing.latestVersion)\n\n const orgId = (await getOrgForHost(hostId))?.orgId ?? ''\n\n /** The installed copy, the base it was installed from, and the offer. */\n let target: Target | null = null\n let incoming: unknown = null\n let installedVersion: string | null = null\n let baseSha: string | null = null\n let notMergeable: string | undefined\n let schemaSummary: UpdatePreview['schema']\n\n if (artifactType === 'component') {\n const existing = await hostRef\n .collection('components')\n .where('marketplace.listingId', '==', listingId)\n .limit(1)\n .get()\n const doc = existing.docs.find((entry) => !entry.get('deletedAt'))\n if (!doc) return res.status(404).json({ error: 'Not installed on this site' })\n const version = versionSnapshot.data() as any\n incoming = { rootId: version.rootId, nodes: version.nodes }\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('marketplace.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n target = {\n ref: doc.ref,\n current: {\n rootId: doc.get('rootId'),\n // DECODED, because everything downstream compares by VALUE: the\n // divergence hash, and `planArtifactUpdate`'s three-way diff over\n // dotted paths like `nodes.abc123.props.title`. A stored `Bytes`\n // has no such paths, so the merge would see the whole tree as\n // removed and write an empty one back (AGL-1151).\n nodes: decodeStoredNodes(doc.get('nodes')),\n },\n write: (content) => ({\n rootId: content?.rootId ?? null,\n // Compressed at rest, like every other writer of this document.\n nodes: Buffer.from(encodeStoredNodes(content?.nodes ?? {})!),\n }),\n // Detaching keeps the customised component as an ordinary one: it stays\n // on every page that uses it, and only stops being tracked against the\n // listing — which is what makes \"install as a new copy\" non-destructive\n // without leaving two documents claiming to be the same install.\n detach: {\n marketplace: firebaseAdmin.firestore.FieldValue.delete(),\n detachedFrom: { listingId, version: installedVersion },\n },\n // `hosts/{hostId}/components` is private to its host; no scope.\n forkScope: null,\n props: readPublishedProps(version.props),\n }\n } else if (artifactType === 'layout') {\n const existing = await hostRef\n .collection('templates')\n .where('source.listingId', '==', listingId)\n .get()\n const doc = existing.docs.find(\n (entry) => !entry.get('deletedAt') && entry.get('kind') === 'layout',\n )\n if (!doc) return res.status(404).json({ error: 'Not installed on this site' })\n const layout = versionSnapshot.get('layout') as any\n incoming = { rootId: layout?.rootId, nodes: layout?.nodes }\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('source.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n target = {\n ref: doc.ref,\n current: {\n rootId: doc.get('rootId'),\n // DECODED, because everything downstream compares by VALUE: the\n // divergence hash, and `planArtifactUpdate`'s three-way diff over\n // dotted paths like `nodes.abc123.props.title`. A stored `Bytes`\n // has no such paths, so the merge would see the whole tree as\n // removed and write an empty one back (AGL-1151).\n nodes: decodeStoredNodes(doc.get('nodes')),\n },\n write: (content) => ({\n rootId: content?.rootId ?? null,\n // Compressed at rest, like every other writer of this document.\n nodes: Buffer.from(encodeStoredNodes(content?.nodes ?? {})!),\n }),\n detach: {\n // The customer's own from here on: `authored`, the provenance the\n // templates library's Source filter calls \"Saved here\" (AGL-3321).\n source: { type: 'authored' },\n detachedFrom: { listingId, version: installedVersion },\n },\n // `hosts/{hostId}/templates` is private to its host; no scope.\n forkScope: null,\n props: readPublishedProps(layout?.props),\n }\n } else if (artifactType === 'datasetSchema') {\n if (!orgId) {\n return res.status(404).json({ error: 'Site has no owning organization' })\n }\n const orgRef = firestore.collection('orgs').doc(orgId)\n const datasets = await orgRef.collection('datasets').get()\n const doc = datasets.docs.find(\n (entry) =>\n entry.get('source.listingId') === listingId && !entry.get('deletedAt'),\n )\n if (!doc) {\n return res.status(404).json({ error: 'Not installed in this organization' })\n }\n // Relink the incoming schema onto THIS org's datasets exactly as install\n // does — the base holds the relinked shape, so diffing the published one\n // would report every reference field as a user edit.\n const byLabel: Record<string, string> = {}\n for (const entry of datasets.docs) {\n const label = String(entry.get('displayName') ?? '').toLowerCase()\n if (label && !byLabel[label]) byLabel[label] = entry.id\n }\n const { schema } = resolveInstalledDatasetSchema(\n versionSnapshot.get('datasetSchema') as any,\n byLabel,\n )\n incoming = schema\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('source.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n const current = doc.get('model') ?? { order: doc.get('fields') ?? [], fields: {} }\n const summary = summarizeSchemaChange(current as any, schema as any)\n // The count is read for the preview, not estimated: \"3 fields will be\n // removed\" means nothing without \"from 1,240 records\".\n const records = await doc.ref\n .collection('records')\n .count()\n .get()\n .catch(() => null)\n schemaSummary = {\n added: summary.added,\n removed: summary.removed,\n retyped: summary.retyped,\n additiveOnly: summary.additiveOnly,\n recordCount: records?.data().count ?? 0,\n }\n const installedScope = doc.get('visibleTo')\n target = {\n ref: doc.ref,\n current,\n write: (content) => ({\n model: content,\n // The v1 flat list the older editor still reads, kept in step.\n fields: content?.order ?? [],\n }),\n // A fork INHERITS the copy it forked from, never a fresh default: a\n // dataset restricted to one client's site must not reappear org-wide\n // because somebody took a publisher update as a separate copy. An\n // absent scope reads as org-wide everywhere else (`visibleToHost`),\n // so it does here. A stored empty array — \"visible to nobody\" — is\n // passed through and throws at the write rather than being widened,\n // which is the right direction to fail in.\n forkScope: Array.isArray(installedScope)\n ? (installedScope as ScopeToken[])\n : [ORG_SCOPE_TOKEN],\n }\n } else if (artifactType === 'theme') {\n // A theme lives on the host document itself, so there is no artifact doc\n // to look up and no \"not installed on this site\" — the site either runs\n // this listing's theme or it does not.\n if (hostSnapshot.get('themeInstalledFrom.listingId') !== listingId) {\n return res.status(404).json({ error: 'Not installed on this site' })\n }\n incoming = versionSnapshot.get('theme') ?? {}\n installedVersion =\n String(hostSnapshot.get('themeInstalledFrom.version') ?? '') || null\n baseSha = hostSnapshot.get('themeInstalledFrom.sha256') ?? null\n target = {\n ref: hostRef,\n current: hostSnapshot.get('theme') ?? {},\n write: (content) => ({ theme: content ?? {} }),\n // No `detach`: a site has exactly one theme, so \"install as a separate\n // copy\" has nowhere to put the second one. Merge is the only safe way\n // to take a theme update, and the preview says so.\n //\n // A theme is a FIELD on the host document, so there is no document to\n // scope even if it could fork.\n forkScope: null,\n }\n } else if (artifactType === 'template') {\n // A published template bundle's screens carry no stable identity — only a\n // displayName and a slug — so there is nothing to pair an old screen to a\n // new one by. Any merge would be a guess dressed up as a diff.\n notMergeable =\n 'Template bundles have no stable per-screen identity, so their screens ' +\n 'cannot be matched across versions. Installing the new version replaces ' +\n 'this bundle in your Templates library — pages you already created from ' +\n 'the old templates are ordinary screens and are untouched.'\n } else if (artifactType === 'emailTemplate') {\n // Already safe by construction: an email template installs as an inactive\n // draft version, so taking a new one changes nothing that is being sent.\n notMergeable =\n 'Email templates install as a draft version and never replace what your ' +\n 'site is sending. Add the new version as another draft, then activate ' +\n 'it when you are ready.'\n }\n\n if (notMergeable) {\n const preview: UpdatePreview = {\n artifactType,\n installedVersion: null,\n availableVersion,\n mergeable: false,\n reason: notMergeable,\n safe: [],\n kept: [],\n conflicts: [],\n unchanged: 0,\n identical: false,\n }\n return res.status(200).json({ preview })\n }\n if (!target) {\n return res.status(404).json({ error: 'Nothing installed to update' })\n }\n\n const baseSnapshot = baseSha\n ? await firestore\n .collection(ARTIFACT_BASE_COLLECTION)\n .doc(baseSha)\n .get()\n .catch(() => null)\n : null\n const base = baseSnapshot?.exists ? baseSnapshot.get('content') : undefined\n const mergeable = base !== undefined\n\n let plan: ArtifactUpdatePlan | null = null\n if (mergeable) plan = planArtifactUpdate(base, target.current, incoming)\n\n if (action === 'preview') {\n const preview: UpdatePreview = {\n artifactType,\n installedVersion,\n availableVersion,\n mergeable,\n ...(mergeable\n ? {}\n : {\n reason:\n 'This was installed before update tracking recorded an ' +\n 'original, so there is no way to tell your changes from the ' +\n 'publisher’s. Installing the new version as a separate copy ' +\n 'keeps yours intact.',\n }),\n safe: trimChanges(plan?.safe ?? []),\n kept: trimChanges(plan?.kept ?? []),\n conflicts: trimChanges(plan?.conflicts ?? []),\n unchanged: plan?.unchanged ?? 0,\n identical: plan?.identical ?? false,\n ...(schemaSummary ? { schema: schemaSummary } : {}),\n }\n return res.status(200).json({ preview })\n }\n\n // ---- apply ----\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n if (mode === 'merge') {\n if (!plan) {\n return res.status(409).json({\n error:\n 'No original snapshot for this install — it can only be taken as a new copy',\n })\n }\n // A schema change that removes or retypes a field reinterprets rows that\n // already exist. It is applicable, but never without the caller having\n // been told the count and said yes to it specifically.\n if (schemaSummary && !schemaSummary.additiveOnly && !confirmDestructive) {\n return res.status(409).json({\n error:\n `This update removes or retypes ${\n schemaSummary.removed.length + schemaSummary.retyped.length\n } field(s) on a dataset holding ${schemaSummary.recordCount} record(s).`,\n needsConfirmation: true,\n schema: schemaSummary,\n })\n }\n const merged = applyArtifactUpdate(plan, target.current, { takePaths })\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: artifactType as never,\n // The base for NEXT time is the publisher's version, not the merged\n // result: the base answers \"what did the publisher ship\", and seeding\n // it with the merge would quietly launder this update's kept edits into\n // the publisher's column, where the next update could take them away.\n content: incoming,\n })\n await target.ref.set(\n {\n ...target.write(merged.content),\n ...(target.props && { props: target.props }),\n // A theme is a FIELD on the host document, not a document of its own,\n // so it namespaces its provenance (`themeInstalledFrom`) and has no\n // legacy `source`/`marketplace` pair — writing those here would put a\n // stray marketplace stamp on the host itself, where `resolveProvenance`\n // would later read it as the host being an installed artifact.\n ...(artifactType === 'theme'\n ? { themeInstalledFrom: provenance.installedFrom }\n : {\n installedFrom: provenance.installedFrom,\n // The legacy per-type version fields the console still reads.\n ...(artifactType === 'component'\n ? {\n marketplace: {\n listingId,\n profileId: listing.profileId ?? null,\n version: listing.latestVersion ?? null,\n },\n }\n : {\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n }),\n }),\n updatedAt: now,\n },\n { merge: true },\n )\n // Per-version tally (AGL-1036): this install just moved versions, which\n // is the whole reason the per-version count exists.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType,\n from: installedVersion,\n to: availableVersion,\n })\n return res.status(200).json({\n updated: true,\n mode,\n version: availableVersion,\n applied: merged.applied.length,\n keptLocal: plan.kept.length,\n skipped: merged.skipped,\n baseStored: provenance.baseStored,\n })\n }\n\n // ---- copy ----\n if (!target.detach) {\n // Only types with a detachable link get a copy from here. A dataset's\n // \"new copy\" is a whole new dataset, which consumes org quota and lands\n // empty — exactly what the install route already does, with the quota\n // check this one does not have.\n //\n // This return is also, today, the only thing keeping the fork below\n // from creating an unstamped `orgs/{orgId}/datasets` document\n // (AGL-1478): a dataset never reaches it because it has no `detach`.\n // That is a guard by accident, three statements away from the write\n // and phrased as a quota argument — give `datasetSchema` a `detach`\n // for any reason and the scope hole opens with it. `Target.forkScope`\n // is the guard that stays true whichever way this branch goes.\n return res.status(400).json({\n error:\n artifactType === 'theme'\n ? // A site has one theme, so there is no second place to put a\n // copy. Merging keeps this site's edits; the way back to the\n // previous theme is the install route's `revert`.\n 'A site has only one theme, so this update can only be merged. ' +\n 'Your edits to fields the publisher did not touch are kept.'\n : 'Install a fresh copy of this from the listing instead',\n })\n }\n // The customised copy is detached rather than deleted or overwritten: it\n // keeps working everywhere it is used, and only stops being the document\n // this listing updates. Without the detach two documents would claim the\n // same install and the next update would pick between them arbitrarily.\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: artifactType as never,\n content: incoming,\n })\n const batch = firestore.batch()\n if (target.detach) {\n batch.set(target.ref, { ...target.detach, updatedAt: now }, { merge: true })\n }\n const collectionRef = target.ref.parent\n const freshRef = collectionRef.doc(createResourceUid())\n const carried = (await target.ref.get()).data() ?? {}\n const freshName = String(listing.displayName ?? carried.displayName ?? 'Untitled')\n batch.set(freshRef, {\n // Everything that is not content travels from the copy being replaced —\n // the display name, description and kind — so the new one lands in the\n // same place in the same library rather than as an unrecognisable stub.\n ...(carried.kind ? { kind: carried.kind } : {}),\n displayName: freshName,\n ...(listing.description ? { description: listing.description } : {}),\n // Not part of the `carried` spread above, deliberately: a spread\n // cannot carry a field the source is missing, and \"the source had one\"\n // is not the question a scoped collection asks. `Target.forkScope`\n // makes every artifact type answer it (AGL-1478), and this throws\n // rather than storing a scope nobody can see through.\n ...newResourceScopeFields(target.forkScope),\n ...target.write(incoming),\n ...(target.props\n ? { props: target.props }\n : Array.isArray(carried.props)\n ? { props: carried.props }\n : {}),\n ...(artifactType === 'component'\n ? {\n marketplace: {\n listingId,\n profileId: listing.profileId ?? null,\n version: listing.latestVersion ?? null,\n },\n }\n : {\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n }),\n installedFrom: provenance.installedFrom,\n deletedAt: null,\n // The keys the fresh copy's list finds it by (AGL-3321), for whichever\n // artifact collection it lands in.\n ...artifactCreateListKeys(collectionRef.id, {\n kind: carried.kind,\n displayName: freshName,\n source: { type: 'marketplace' },\n }),\n createdAt: now,\n updatedAt: now,\n })\n await batch.commit()\n // Per-version tally (AGL-1036). Still a move, not a second install: the\n // detached copy stops being tracked against the listing, so the version it\n // held is genuinely vacated.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType,\n from: installedVersion,\n to: availableVersion,\n })\n return res.status(200).json({\n updated: true,\n mode,\n version: availableVersion,\n newId: freshRef.id,\n detached: Boolean(target.detach),\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Update failed' })\n }\n}\n\nexport default updateArtifactHandler\n"],"names":["artifactCreateListKeys","createResourceUid","decodeStoredNodes","encodeStoredNodes","newResourceScopeFields","ORG_SCOPE_TOKEN","applyArtifactUpdate","planArtifactUpdate","summarizeSchemaChange","ARTIFACT_BASE_COLLECTION","firebaseAdmin","getOrgForHost","resolveOrgPermissions","listingArtifactType","resolveInstalledDatasetSchema","readPublishedProps","recordInstallProvenance","canActAsPublisher","requirePurchase","recordVersionMove","isPublisherSecurityLocked","trimChanges","changes","slice","updateArtifactHandler","req","res","method","status","json","error","listingId","String","body","hostId","action","mode","takePaths","Array","isArray","map","path","confirmDestructive","Boolean","authorization","headers","idToken","startsWith","length","undefined","listing","decoded","app","auth","verifyIdToken","membership","uid","permissions","installPlugins","firestore","hostRef","collection","doc","hostSnapshot","get","exists","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","Number","unpaid","buyerUid","buyerOrgId","orgId","ownsListing","artifactType","versionSnapshot","latestVersion","availableVersion","target","incoming","installedVersion","baseSha","notMergeable","schemaSummary","existing","where","limit","docs","find","entry","version","rootId","nodes","ref","current","write","content","Buffer","from","detach","marketplace","FieldValue","delete","detachedFrom","forkScope","props","layout","source","type","orgRef","datasets","byLabel","label","toLowerCase","id","schema","order","fields","summary","records","count","catch","added","removed","retyped","additiveOnly","recordCount","installedScope","model","theme","preview","mergeable","reason","safe","kept","conflicts","unchanged","identical","baseSnapshot","base","plan","now","serverTimestamp","needsConfirmation","merged","provenance","set","themeInstalledFrom","installedFrom","updatedAt","merge","to","updated","applied","keptLocal","skipped","baseStored","batch","collectionRef","parent","freshRef","carried","freshName","displayName","kind","description","createdAt","commit","newId","detached","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,uEAAuE;AACvE,yEAAyE;AACzE,iCAAiC;AACjC,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,iBAAiB,EACjBC,sBAAsB,EACtBC,eAAe,QAGV,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,kBAAkB,EAClBC,qBAAqB,QAGhB,6BAAyB;AAChC,SAASC,wBAAwB,QAAQ,gDAA+C;AACxF,SAASC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aAAa;YACvCpF,WAAW;WAGRrE,uBAAuBmK,cAAc5C,EAAE,EAAE;YAC1CkD,MAAMH,QAAQG,IAAI;YAClBD,aAAaD;YACbvD,QAAQ;gBAAEC,MAAM;YAAc;QAChC;YACA0D,WAAWzB;YACXQ,WAAWR;;QAEb,MAAMgB,MAAMU,MAAM;QAClB,wEAAwE;QACxE,2EAA2E;QAC3E,6BAA6B;QAC7B,MAAMzJ,kBAAkB;YACtBwC;YACAO;YACAa;YACAwB,MAAMlB;YACNuE,IAAI1E;QACN;QACA,OAAOxD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAC1BgI,SAAS;YACTzH;YACA2D,SAASb;YACT2F,OAAOR,SAAS9C,EAAE;YAClBuD,UAAUnI,QAAQwC,OAAOqB,MAAM;YAC/ByD,YAAYX,WAAWW,UAAU;QACnC;IACF,EAAE,OAAOnI,OAAO;QACdiJ,QAAQjJ,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAgB;IACvD;AACF,EAAC;AAED,eAAeN,sBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/update-artifact.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n// The leaf module, not the server barrel: the list keys every artifact\n// create stamps (AGL-3321), which the install specs' closed-world barrel\n// mocks have no reason to stage.\nimport { artifactCreateListKeys } from '@aglyn/aglyn/app-utils/artifact-list-keys'\nimport {\n createResourceUid,\n decodeStoredNodes,\n encodeStoredNodes,\n newResourceScopeFields,\n ORG_SCOPE_TOKEN,\n type PluginApiHandler,\n type ScopeToken,\n} from '@aglyn/aglyn/server'\nimport {\n applyArtifactUpdate,\n planArtifactUpdate,\n summarizeSchemaChange,\n type ArtifactChange,\n type ArtifactUpdatePlan,\n} from '../model/artifact-merge'\nimport { ARTIFACT_BASE_COLLECTION } from '@aglyn/aglyn/app-utils/marketplace-provenance'\nimport { dropPluginSiteCache } from '@aglyn/aglyn/plugin-manager/plugin-site-cache'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n listingArtifactType,\n resolveInstalledDatasetSchema,\n} from '../model/marketplace'\nimport { readPublishedProps } from '../model/marketplace-props'\nimport { recordInstallProvenance } from './provenance'\nimport { canActAsPublisher } from './publisher-profile'\nimport { requirePurchase } from './purchase-entitlement'\nimport { recordVersionMove } from './version-stats'\nimport { isPublisherSecurityLocked } from './sale-risk'\n\n/**\n * Updating a COPIED marketplace artifact (AGL-1018).\n *\n * The install routes update by overwriting: a component re-install writes the\n * publisher's tree straight over the workspace's copy, and a template or layout\n * re-install soft-deletes the previous bundle. Both are silent, and both throw\n * away work the customer did after installing.\n *\n * This route never overwrites without saying what will be lost. `preview`\n * classifies every field against AGL-1015's base snapshot and returns the plan;\n * `apply` writes only what the plan (and, for conflicts, the caller) chose.\n * There are two ways to take a new version and both are safe:\n *\n * * **merge** — take the publisher's changes to fields nobody here edited, keep\n * this workspace's edits, and overwrite a contested field only when it was\n * explicitly picked.\n * * **copy** — install the new version fresh and DETACH the customised copy,\n * which keeps it as an ordinary workspace artifact rather than deleting it.\n *\n * Without a base snapshot only `copy` is offered. Inventing an origin to diff\n * against is how a merge becomes confidently wrong.\n */\n\ntype Mode = 'merge' | 'copy'\n\n/** What a preview tells the client, and what the dialog renders. */\ninterface UpdatePreview {\n artifactType: string\n installedVersion: string | null\n availableVersion: string | null\n /** A three-way merge is possible: a base snapshot exists and the type supports it. */\n mergeable: boolean\n /** Why not, when it isn't. */\n reason?: string\n safe: ArtifactChange[]\n kept: ArtifactChange[]\n conflicts: ArtifactChange[]\n unchanged: number\n identical: boolean\n /** Dataset schemas only: what the change does to existing records. */\n schema?: {\n added: string[]\n removed: string[]\n retyped: string[]\n additiveOnly: boolean\n recordCount: number\n }\n}\n\n/** Everything the route needs to diff and write one copied artifact. */\ninterface Target {\n ref: FirebaseFirestore.DocumentReference\n /** The copy as it is now, in the same shape the base snapshot holds. */\n current: unknown\n /** Fields to write alongside merged content. */\n write: (content: any) => Record<string, unknown>\n /** Fields that detach this copy from its listing, for `copy` mode. */\n detach?: Record<string, unknown>\n /**\n * The AGL-1037 scope the FORKED copy is created with, or `null` when the\n * destination collection is not scoped (AGL-1478).\n *\n * Required, and required on purpose. `copy` mode writes a brand-new\n * document into `target.ref.parent` — whatever collection that turns out\n * to be — from a spread of carried fields, and a spread cannot carry a\n * field the source never had. For `orgs/{orgId}/datasets` that is the\n * AGL-1466 bug exactly: an unstamped dataset is not \"unrestricted\", it is\n * matched by no `array-contains-any` reader in the product, so it renders\n * on no site and is missing from the workflows and reference-health cards\n * even for an org-wide member.\n *\n * Making it optional with a sensible default would have been the smaller\n * diff and is the thing that fails: the two `mediaFolders` creators that\n * each forgot `visibleTo` were both written by people who had the field\n * in front of them. A sixth artifact type cannot be added here without\n * answering this, which is the only guarantee that survives a stranger.\n *\n * `null` is a real answer, not an escape hatch: components live in\n * `hosts/{hostId}/components` and layouts in `hosts/{hostId}/templates`,\n * both private to their host by construction and neither carrying a scope.\n */\n forkScope: readonly ScopeToken[] | null\n /**\n * The declared properties the new version carries (AGL-2933), for a\n * component or layout, sanitized; `undefined` when the version was published\n * before properties were carried, or the type declares none.\n *\n * Not part of the merged content. Every base snapshot recorded before this\n * field existed holds only the tree, so diffing properties three ways would\n * read each installed copy's declarations as a local edit to keep. They are\n * the publisher's contract with the tree instead: whatever the merge takes\n * of the nodes binds to them, so the incoming list replaces the installed\n * one, in both modes.\n */\n props?: ReturnType<typeof readPublishedProps>\n}\n\nconst trimChanges = (changes: ArtifactChange[]): ArtifactChange[] =>\n // The dialog lists changes; a 400-node tree that changed wholesale would\n // otherwise ship its entire content twice through a JSON response.\n changes.slice(0, 200)\n\nexport const updateArtifactHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const listingId = String(req.body?.listingId ?? '')\n const hostId = String(req.body?.hostId ?? '')\n const action = req.body?.action === 'apply' ? 'apply' : 'preview'\n const mode: Mode = req.body?.mode === 'copy' ? 'copy' : 'merge'\n const takePaths: string[] = Array.isArray(req.body?.takePaths)\n ? req.body.takePaths.map((path: unknown) => String(path))\n : []\n const confirmDestructive = Boolean(req.body?.confirmDestructive)\n if (!listingId || !hostId) {\n return res.status(400).json({ error: 'Missing listingId or hostId' })\n }\n const authorization = String(req.headers.authorization ?? '')\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return res.status(401).json({ error: 'Unauthenticated' })\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n // The same gate installing uses: taking a new version of something is\n // installing it, and a role that cannot install must not be able to\n // rewrite an installed artifact through a different door.\n const membership = await resolveOrgPermissions(decoded.uid, { hostId })\n if (!membership.permissions.installPlugins) {\n return res.status(403).json({\n error: 'Your organization role does not allow installing from the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hostSnapshot = await hostRef.get()\n if (!hostSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown site' })\n }\n\n const listingRef = firestore.collection('marketplaceListings').doc(listingId)\n const listingSnapshot = await listingRef.get()\n const listing = listingSnapshot.data() as any\n if (\n !listing ||\n listing.deletedAt ||\n // Staff takedown blocks new installs on EVERY artifact type\n // (AGL-2290). AGL-948 extended takedown past plugins in the browse\n // predicate and in `resolveMarketplacePluginVersion`, but the gate that\n // decides whether content is HANDED OVER was only ever added to\n // `install-plugin.ts`. So a component, theme, template, layout, email\n // template or dataset schema that staff had taken down stayed\n // installable by anyone holding its listing id — which makes takedown a\n // suggestion for six of the seven artifact types.\n //\n // No owner exemption, matching `install-plugin.ts`: a takedown is a\n // moderation decision about the artifact, not about who is asking.\n listing.hiddenAt ||\n // A publisher under a SECURITY lock hands nothing over (AGL-3365).\n (await isPublisherSecurityLocked(firestore, listing.profileId))\n ) {\n return res.status(404).json({ error: 'Unknown listing' })\n }\n // Taking a NEW version of a paid listing is buying content, and this\n // route never asked whether the caller still owned it (AGL-1699). The\n // install routes gate; this one only checked the org ROLE, so a buyer\n // who was refunded — and even in `copy` mode, which installs the new\n // version fresh — kept pulling every future paid release through here.\n //\n // Deliberately not a regression for anyone legitimate: a live purchase,\n // a free listing, or the publisher's own listing all pass, and nobody\n // without one of those could have had an installed copy to update.\n // The `priceUsd > 0` test is out here rather than left to the helper so\n // a free listing — most of them — does not pay for a publisher lookup.\n const priceUsd = Number(listing.priceUsd ?? 0)\n if (priceUsd > 0) {\n const unpaid = await requirePurchase({\n firestore,\n buyerUid: decoded.uid,\n // THE ORG THE LICENCE HAS TO COVER (AGL-2331). `membership.orgId` is\n // resolved server-side from the caller's own membership by the\n // permission gate above — never a request-body field — so this is the\n // workspace the install actually lands in, and the only one a purchase\n // can entitle here.\n buyerOrgId: membership.orgId ?? '',\n listingId,\n priceUsd,\n ownsListing: await canActAsPublisher(\n firestore,\n decoded.uid,\n listing.profileId,\n ),\n })\n if (unpaid) return res.status(402).json(unpaid)\n }\n\n const artifactType = listingArtifactType(listing)\n if (artifactType === 'plugin') {\n // Plugins are pinned, not copied: an update moves a pointer at immutable\n // bytes (AGL-1017) and has nothing to merge.\n return res.status(400).json({\n error: 'Plugins update by re-pinning — use the install route',\n })\n }\n\n const versionSnapshot = await listingRef\n .collection('versions')\n .doc(String(listing.latestVersion))\n .get()\n if (!versionSnapshot.exists) {\n return res.status(404).json({ error: 'Listing version missing' })\n }\n const availableVersion =\n listing.latestVersion == null ? null : String(listing.latestVersion)\n\n const orgId = (await getOrgForHost(hostId))?.orgId ?? ''\n\n /** The installed copy, the base it was installed from, and the offer. */\n let target: Target | null = null\n let incoming: unknown = null\n let installedVersion: string | null = null\n let baseSha: string | null = null\n let notMergeable: string | undefined\n let schemaSummary: UpdatePreview['schema']\n\n if (artifactType === 'component') {\n const existing = await hostRef\n .collection('components')\n .where('marketplace.listingId', '==', listingId)\n .limit(1)\n .get()\n const doc = existing.docs.find((entry) => !entry.get('deletedAt'))\n if (!doc) return res.status(404).json({ error: 'Not installed on this site' })\n const version = versionSnapshot.data() as any\n incoming = { rootId: version.rootId, nodes: version.nodes }\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('marketplace.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n target = {\n ref: doc.ref,\n current: {\n rootId: doc.get('rootId'),\n // DECODED, because everything downstream compares by VALUE: the\n // divergence hash, and `planArtifactUpdate`'s three-way diff over\n // dotted paths like `nodes.abc123.props.title`. A stored `Bytes`\n // has no such paths, so the merge would see the whole tree as\n // removed and write an empty one back (AGL-1151).\n nodes: decodeStoredNodes(doc.get('nodes')),\n },\n write: (content) => ({\n rootId: content?.rootId ?? null,\n // Compressed at rest, like every other writer of this document.\n nodes: Buffer.from(encodeStoredNodes(content?.nodes ?? {})!),\n }),\n // Detaching keeps the customised component as an ordinary one: it stays\n // on every page that uses it, and only stops being tracked against the\n // listing — which is what makes \"install as a new copy\" non-destructive\n // without leaving two documents claiming to be the same install.\n detach: {\n marketplace: firebaseAdmin.firestore.FieldValue.delete(),\n detachedFrom: { listingId, version: installedVersion },\n },\n // `hosts/{hostId}/components` is private to its host; no scope.\n forkScope: null,\n props: readPublishedProps(version.props),\n }\n } else if (artifactType === 'layout') {\n const existing = await hostRef\n .collection('templates')\n .where('source.listingId', '==', listingId)\n .get()\n const doc = existing.docs.find(\n (entry) => !entry.get('deletedAt') && entry.get('kind') === 'layout',\n )\n if (!doc) return res.status(404).json({ error: 'Not installed on this site' })\n const layout = versionSnapshot.get('layout') as any\n incoming = { rootId: layout?.rootId, nodes: layout?.nodes }\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('source.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n target = {\n ref: doc.ref,\n current: {\n rootId: doc.get('rootId'),\n // DECODED, because everything downstream compares by VALUE: the\n // divergence hash, and `planArtifactUpdate`'s three-way diff over\n // dotted paths like `nodes.abc123.props.title`. A stored `Bytes`\n // has no such paths, so the merge would see the whole tree as\n // removed and write an empty one back (AGL-1151).\n nodes: decodeStoredNodes(doc.get('nodes')),\n },\n write: (content) => ({\n rootId: content?.rootId ?? null,\n // Compressed at rest, like every other writer of this document.\n nodes: Buffer.from(encodeStoredNodes(content?.nodes ?? {})!),\n }),\n detach: {\n // The customer's own from here on: `authored`, the provenance the\n // templates library's Source filter calls \"Saved here\" (AGL-3321).\n source: { type: 'authored' },\n detachedFrom: { listingId, version: installedVersion },\n },\n // `hosts/{hostId}/templates` is private to its host; no scope.\n forkScope: null,\n props: readPublishedProps(layout?.props),\n }\n } else if (artifactType === 'datasetSchema') {\n if (!orgId) {\n return res.status(404).json({ error: 'Site has no owning organization' })\n }\n const orgRef = firestore.collection('orgs').doc(orgId)\n const datasets = await orgRef.collection('datasets').get()\n const doc = datasets.docs.find(\n (entry) =>\n entry.get('source.listingId') === listingId && !entry.get('deletedAt'),\n )\n if (!doc) {\n return res.status(404).json({ error: 'Not installed in this organization' })\n }\n // Relink the incoming schema onto THIS org's datasets exactly as install\n // does — the base holds the relinked shape, so diffing the published one\n // would report every reference field as a user edit.\n const byLabel: Record<string, string> = {}\n for (const entry of datasets.docs) {\n const label = String(entry.get('displayName') ?? '').toLowerCase()\n if (label && !byLabel[label]) byLabel[label] = entry.id\n }\n const { schema } = resolveInstalledDatasetSchema(\n versionSnapshot.get('datasetSchema') as any,\n byLabel,\n )\n incoming = schema\n installedVersion = String(\n doc.get('installedFrom.version') ?? doc.get('source.version') ?? '',\n ) || null\n baseSha = doc.get('installedFrom.sha256') ?? null\n const current = doc.get('model') ?? { order: doc.get('fields') ?? [], fields: {} }\n const summary = summarizeSchemaChange(current as any, schema as any)\n // The count is read for the preview, not estimated: \"3 fields will be\n // removed\" means nothing without \"from 1,240 records\".\n const records = await doc.ref\n .collection('records')\n .count()\n .get()\n .catch(() => null)\n schemaSummary = {\n added: summary.added,\n removed: summary.removed,\n retyped: summary.retyped,\n additiveOnly: summary.additiveOnly,\n recordCount: records?.data().count ?? 0,\n }\n const installedScope = doc.get('visibleTo')\n target = {\n ref: doc.ref,\n current,\n write: (content) => ({\n model: content,\n // The v1 flat list the older editor still reads, kept in step.\n fields: content?.order ?? [],\n }),\n // A fork INHERITS the copy it forked from, never a fresh default: a\n // dataset restricted to one client's site must not reappear org-wide\n // because somebody took a publisher update as a separate copy. An\n // absent scope reads as org-wide everywhere else (`visibleToHost`),\n // so it does here. A stored empty array — \"visible to nobody\" — is\n // passed through and throws at the write rather than being widened,\n // which is the right direction to fail in.\n forkScope: Array.isArray(installedScope)\n ? (installedScope as ScopeToken[])\n : [ORG_SCOPE_TOKEN],\n }\n } else if (artifactType === 'theme') {\n // A theme lives on the host document itself, so there is no artifact doc\n // to look up and no \"not installed on this site\" — the site either runs\n // this listing's theme or it does not.\n if (hostSnapshot.get('themeInstalledFrom.listingId') !== listingId) {\n return res.status(404).json({ error: 'Not installed on this site' })\n }\n incoming = versionSnapshot.get('theme') ?? {}\n installedVersion =\n String(hostSnapshot.get('themeInstalledFrom.version') ?? '') || null\n baseSha = hostSnapshot.get('themeInstalledFrom.sha256') ?? null\n target = {\n ref: hostRef,\n current: hostSnapshot.get('theme') ?? {},\n write: (content) => ({ theme: content ?? {} }),\n // No `detach`: a site has exactly one theme, so \"install as a separate\n // copy\" has nowhere to put the second one. Merge is the only safe way\n // to take a theme update, and the preview says so.\n //\n // A theme is a FIELD on the host document, so there is no document to\n // scope even if it could fork.\n forkScope: null,\n }\n } else if (artifactType === 'template') {\n // A published template bundle's screens carry no stable identity — only a\n // displayName and a slug — so there is nothing to pair an old screen to a\n // new one by. Any merge would be a guess dressed up as a diff.\n notMergeable =\n 'Template bundles have no stable per-screen identity, so their screens ' +\n 'cannot be matched across versions. Installing the new version replaces ' +\n 'this bundle in your Templates library — pages you already created from ' +\n 'the old templates are ordinary screens and are untouched.'\n } else if (artifactType === 'emailTemplate') {\n // Already safe by construction: an email template installs as an inactive\n // draft version, so taking a new one changes nothing that is being sent.\n notMergeable =\n 'Email templates install as a draft version and never replace what your ' +\n 'site is sending. Add the new version as another draft, then activate ' +\n 'it when you are ready.'\n }\n\n if (notMergeable) {\n const preview: UpdatePreview = {\n artifactType,\n installedVersion: null,\n availableVersion,\n mergeable: false,\n reason: notMergeable,\n safe: [],\n kept: [],\n conflicts: [],\n unchanged: 0,\n identical: false,\n }\n return res.status(200).json({ preview })\n }\n if (!target) {\n return res.status(404).json({ error: 'Nothing installed to update' })\n }\n\n const baseSnapshot = baseSha\n ? await firestore\n .collection(ARTIFACT_BASE_COLLECTION)\n .doc(baseSha)\n .get()\n .catch(() => null)\n : null\n const base = baseSnapshot?.exists ? baseSnapshot.get('content') : undefined\n const mergeable = base !== undefined\n\n let plan: ArtifactUpdatePlan | null = null\n if (mergeable) plan = planArtifactUpdate(base, target.current, incoming)\n\n if (action === 'preview') {\n const preview: UpdatePreview = {\n artifactType,\n installedVersion,\n availableVersion,\n mergeable,\n ...(mergeable\n ? {}\n : {\n reason:\n 'This was installed before update tracking recorded an ' +\n 'original, so there is no way to tell your changes from the ' +\n 'publisher’s. Installing the new version as a separate copy ' +\n 'keeps yours intact.',\n }),\n safe: trimChanges(plan?.safe ?? []),\n kept: trimChanges(plan?.kept ?? []),\n conflicts: trimChanges(plan?.conflicts ?? []),\n unchanged: plan?.unchanged ?? 0,\n identical: plan?.identical ?? false,\n ...(schemaSummary ? { schema: schemaSummary } : {}),\n }\n return res.status(200).json({ preview })\n }\n\n // ---- apply ----\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n if (mode === 'merge') {\n if (!plan) {\n return res.status(409).json({\n error:\n 'No original snapshot for this install — it can only be taken as a new copy',\n })\n }\n // A schema change that removes or retypes a field reinterprets rows that\n // already exist. It is applicable, but never without the caller having\n // been told the count and said yes to it specifically.\n if (schemaSummary && !schemaSummary.additiveOnly && !confirmDestructive) {\n return res.status(409).json({\n error:\n `This update removes or retypes ${\n schemaSummary.removed.length + schemaSummary.retyped.length\n } field(s) on a dataset holding ${schemaSummary.recordCount} record(s).`,\n needsConfirmation: true,\n schema: schemaSummary,\n })\n }\n const merged = applyArtifactUpdate(plan, target.current, { takePaths })\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: artifactType as never,\n // The base for NEXT time is the publisher's version, not the merged\n // result: the base answers \"what did the publisher ship\", and seeding\n // it with the merge would quietly launder this update's kept edits into\n // the publisher's column, where the next update could take them away.\n content: incoming,\n })\n await target.ref.set(\n {\n ...target.write(merged.content),\n ...(target.props && { props: target.props }),\n // A theme is a FIELD on the host document, not a document of its own,\n // so it namespaces its provenance (`themeInstalledFrom`) and has no\n // legacy `source`/`marketplace` pair — writing those here would put a\n // stray marketplace stamp on the host itself, where `resolveProvenance`\n // would later read it as the host being an installed artifact.\n ...(artifactType === 'theme'\n ? { themeInstalledFrom: provenance.installedFrom }\n : {\n installedFrom: provenance.installedFrom,\n // The legacy per-type version fields the console still reads.\n ...(artifactType === 'component'\n ? {\n marketplace: {\n listingId,\n profileId: listing.profileId ?? null,\n version: listing.latestVersion ?? null,\n },\n }\n : {\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n }),\n }),\n updatedAt: now,\n },\n { merge: true },\n )\n // A merged THEME repaints every page of the site the moment it lands,\n // and nothing publishes it — so the site's cached pages go now rather\n // than within the hour (AGL-3386). Awaited before the response, and it\n // never throws: a failed drop leaves the update applied.\n if (artifactType === 'theme') {\n await dropPluginSiteCache({\n hostIds: [hostId],\n reason: 'marketplace theme updated',\n })\n }\n // Per-version tally (AGL-1036): this install just moved versions, which\n // is the whole reason the per-version count exists.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType,\n from: installedVersion,\n to: availableVersion,\n })\n return res.status(200).json({\n updated: true,\n mode,\n version: availableVersion,\n applied: merged.applied.length,\n keptLocal: plan.kept.length,\n skipped: merged.skipped,\n baseStored: provenance.baseStored,\n })\n }\n\n // ---- copy ----\n if (!target.detach) {\n // Only types with a detachable link get a copy from here. A dataset's\n // \"new copy\" is a whole new dataset, which consumes org quota and lands\n // empty — exactly what the install route already does, with the quota\n // check this one does not have.\n //\n // This return is also, today, the only thing keeping the fork below\n // from creating an unstamped `orgs/{orgId}/datasets` document\n // (AGL-1478): a dataset never reaches it because it has no `detach`.\n // That is a guard by accident, three statements away from the write\n // and phrased as a quota argument — give `datasetSchema` a `detach`\n // for any reason and the scope hole opens with it. `Target.forkScope`\n // is the guard that stays true whichever way this branch goes.\n return res.status(400).json({\n error:\n artifactType === 'theme'\n ? // A site has one theme, so there is no second place to put a\n // copy. Merging keeps this site's edits; the way back to the\n // previous theme is the install route's `revert`.\n 'A site has only one theme, so this update can only be merged. ' +\n 'Your edits to fields the publisher did not touch are kept.'\n : 'Install a fresh copy of this from the listing instead',\n })\n }\n // The customised copy is detached rather than deleted or overwritten: it\n // keeps working everywhere it is used, and only stops being the document\n // this listing updates. Without the detach two documents would claim the\n // same install and the next update would pick between them arbitrarily.\n const provenance = await recordInstallProvenance({\n firestore,\n listingId,\n listing,\n version: listing.latestVersion,\n artifactType: artifactType as never,\n content: incoming,\n })\n const batch = firestore.batch()\n if (target.detach) {\n batch.set(target.ref, { ...target.detach, updatedAt: now }, { merge: true })\n }\n const collectionRef = target.ref.parent\n const freshRef = collectionRef.doc(createResourceUid())\n const carried = (await target.ref.get()).data() ?? {}\n const freshName = String(listing.displayName ?? carried.displayName ?? 'Untitled')\n batch.set(freshRef, {\n // Everything that is not content travels from the copy being replaced —\n // the display name, description and kind — so the new one lands in the\n // same place in the same library rather than as an unrecognisable stub.\n ...(carried.kind ? { kind: carried.kind } : {}),\n displayName: freshName,\n ...(listing.description ? { description: listing.description } : {}),\n // Not part of the `carried` spread above, deliberately: a spread\n // cannot carry a field the source is missing, and \"the source had one\"\n // is not the question a scoped collection asks. `Target.forkScope`\n // makes every artifact type answer it (AGL-1478), and this throws\n // rather than storing a scope nobody can see through.\n ...newResourceScopeFields(target.forkScope),\n ...target.write(incoming),\n ...(target.props\n ? { props: target.props }\n : Array.isArray(carried.props)\n ? { props: carried.props }\n : {}),\n ...(artifactType === 'component'\n ? {\n marketplace: {\n listingId,\n profileId: listing.profileId ?? null,\n version: listing.latestVersion ?? null,\n },\n }\n : {\n source: {\n type: 'marketplace' as const,\n listingId,\n version: listing.latestVersion ?? null,\n },\n }),\n installedFrom: provenance.installedFrom,\n deletedAt: null,\n // The keys the fresh copy's list finds it by (AGL-3321), for whichever\n // artifact collection it lands in.\n ...artifactCreateListKeys(collectionRef.id, {\n kind: carried.kind,\n displayName: freshName,\n source: { type: 'marketplace' },\n }),\n createdAt: now,\n updatedAt: now,\n })\n await batch.commit()\n // Per-version tally (AGL-1036). Still a move, not a second install: the\n // detached copy stops being tracked against the listing, so the version it\n // held is genuinely vacated.\n await recordVersionMove({\n firestore,\n listingRef,\n artifactType,\n from: installedVersion,\n to: availableVersion,\n })\n return res.status(200).json({\n updated: true,\n mode,\n version: availableVersion,\n newId: freshRef.id,\n detached: Boolean(target.detach),\n baseStored: provenance.baseStored,\n })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Update failed' })\n }\n}\n\nexport default updateArtifactHandler\n"],"names":["artifactCreateListKeys","createResourceUid","decodeStoredNodes","encodeStoredNodes","newResourceScopeFields","ORG_SCOPE_TOKEN","applyArtifactUpdate","planArtifactUpdate","summarizeSchemaChange","ARTIFACT_BASE_COLLECTION","dropPluginSiteCache","firebaseAdmin","getOrgForHost","resolveOrgPermissions","listingArtifactType","resolveInstalledDatasetSchema","readPublishedProps","recordInstallProvenance","canActAsPublisher","requirePurchase","recordVersionMove","isPublisherSecurityLocked","trimChanges","changes","slice","updateArtifactHandler","req","res","method","status","json","error","listingId","String","body","hostId","action","mode","takePaths","Array","isArray","map","path","confirmDestructive","Boolean","authorization","headers","idToken","startsWith","length","undefined","listing","decoded","app","auth","verifyIdToken","membership","uid","permissions","installPlugins","firestore","hostRef","collection","doc","hostSnapshot","get","exists","listingRef","listingSnapshot","data","deletedAt","hiddenAt","profileId","priceUsd","Number","unpaid","buyerUid","buyerOrgId","orgId","ownsListing","artifactType","versionSnapshot","latestVersion","availableVersion","target","incoming","installedVersion","baseSha","notMergeable","schemaSummary","existing","where","limit","docs","find","entry","version","rootId","nodes","ref","current","write","content","Buffer","from","detach","marketplace","FieldValue","delete","detachedFrom","forkScope","props","layout","source","type","orgRef","datasets","byLabel","label","toLowerCase","id","schema","order","fields","summary","records","count","catch","added","removed","retyped","additiveOnly","recordCount","installedScope","model","theme","preview","mergeable","reason","safe","kept","conflicts","unchanged","identical","baseSnapshot","base","plan","now","serverTimestamp","needsConfirmation","merged","provenance","set","themeInstalledFrom","installedFrom","updatedAt","merge","hostIds","to","updated","applied","keptLocal","skipped","baseStored","batch","collectionRef","parent","freshRef","carried","freshName","displayName","kind","description","createdAt","commit","newId","detached","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,uEAAuE;AACvE,yEAAyE;AACzE,iCAAiC;AACjC,SAASA,sBAAsB,QAAQ,4CAA2C;AAClF,SACEC,iBAAiB,EACjBC,iBAAiB,EACjBC,iBAAiB,EACjBC,sBAAsB,EACtBC,eAAe,QAGV,sBAAqB;AAC5B,SACEC,mBAAmB,EACnBC,kBAAkB,EAClBC,qBAAqB,QAGhB,6BAAyB;AAChC,SAASC,wBAAwB,QAAQ,gDAA+C;AACxF,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF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