@aglyn/plugins-marketplace 1.0.0-beta.199 → 1.0.0-beta.201
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 +14 -14
- package/src/lib/components/marketplace-browse.component.js +104 -169
- package/src/lib/components/marketplace-browse.component.js.map +1 -1
- package/src/lib/components/marketplace-reports-page.component.js +9 -0
- package/src/lib/components/marketplace-reports-page.component.js.map +1 -1
- package/src/lib/components/org-licences-panel.component.js +212 -170
- package/src/lib/components/org-licences-panel.component.js.map +1 -1
- package/src/lib/components/org-seller-panel.component.js +23 -5
- package/src/lib/components/org-seller-panel.component.js.map +1 -1
- package/src/lib/components/plugin-reviews-queue.component.d.ts +9 -0
- package/src/lib/components/plugin-reviews-queue.component.js +190 -114
- package/src/lib/components/plugin-reviews-queue.component.js.map +1 -1
- package/src/lib/hooks/use-listing-name-lookup.d.ts +34 -0
- package/src/lib/hooks/use-listing-name-lookup.js +131 -0
- package/src/lib/hooks/use-listing-name-lookup.js.map +1 -0
- package/src/lib/model/listing-query.d.ts +140 -0
- package/src/lib/model/listing-query.js +393 -0
- package/src/lib/model/listing-query.js.map +1 -0
- package/src/lib/model/marketplace.d.ts +11 -0
- package/src/lib/model/marketplace.js.map +1 -1
- package/src/lib/server/admin-reports.js +30 -12
- package/src/lib/server/admin-reports.js.map +1 -1
- package/src/lib/server/admin-reviews.js +180 -128
- package/src/lib/server/admin-reviews.js.map +1 -1
- package/src/lib/server/admin-trust.js +2 -1
- package/src/lib/server/admin-trust.js.map +1 -1
- package/src/lib/server/billing-webhook.js +13 -1
- package/src/lib/server/billing-webhook.js.map +1 -1
- package/src/lib/server/checkout.js +3 -1
- package/src/lib/server/checkout.js.map +1 -1
- package/src/lib/server/install-email-starter.js +9 -2
- package/src/lib/server/install-email-starter.js.map +1 -1
- package/src/lib/server/install-layout.js +17 -5
- package/src/lib/server/install-layout.js.map +1 -1
- package/src/lib/server/install-template.js +15 -5
- package/src/lib/server/install-template.js.map +1 -1
- package/src/lib/server/install.js +10 -2
- package/src/lib/server/install.js.map +1 -1
- package/src/lib/server/listing-query-fields.d.ts +38 -0
- package/src/lib/server/listing-query-fields.js +50 -0
- package/src/lib/server/listing-query-fields.js.map +1 -0
- package/src/lib/server/publish-dataset-schema.js +6 -2
- package/src/lib/server/publish-dataset-schema.js.map +1 -1
- package/src/lib/server/publish-email-starter.js +6 -2
- package/src/lib/server/publish-email-starter.js.map +1 -1
- package/src/lib/server/publish-email-template.js +6 -2
- package/src/lib/server/publish-email-template.js.map +1 -1
- package/src/lib/server/publish-layout.js +6 -2
- package/src/lib/server/publish-layout.js.map +1 -1
- package/src/lib/server/publish-plugin.js +75 -7
- package/src/lib/server/publish-plugin.js.map +1 -1
- package/src/lib/server/publish-template.js +6 -2
- package/src/lib/server/publish-template.js.map +1 -1
- package/src/lib/server/publish-theme.js +6 -2
- package/src/lib/server/publish-theme.js.map +1 -1
- package/src/lib/server/publish.js +6 -2
- package/src/lib/server/publish.js.map +1 -1
- package/src/lib/server/update-artifact.js +18 -4
- package/src/lib/server/update-artifact.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-starter.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\n\n/**\n * Publishes a site's campaign email design as a marketplace starter.\n *\n * The source is a `kind: 'email'` SCREEN — the document `createEmailScreen`\n * writes and the screen besigner edits — not an entry in the transactional\n * catalog. That is the whole difference from `publish-email-template`, and it\n * is why the two exist separately: a transactional design is a design FOR a\n * fixed key and installs onto that same key; a starter belongs to no key and\n * installs as a new email of the buyer's own.\n *\n * ## Two things this reads that the transactional publisher does not\n *\n * **The nodes are compressed.** A screen version is written through\n * `screenVersionConverter`, so `nodes` comes back from the Admin SDK as a\n * msgpack `Buffer`. `publish-email-template.ts` reads its `nodes` raw and says\n * why — its besigner saves with a bare `setDoc` and no converter — and copying\n * that line here would publish a Buffer: truthy, non-empty by `Object.keys`\n * (those are byte indices), and scanning as a design with no blocks in it.\n *\n * **The tree is inspected, not just sanitized.** `sanitizeMarketplaceDefinition`\n * DROPS an unsafe URL and publishes what is left, which is right for a page.\n * Here the URL rules are the product: a remote image in an email is a read\n * receipt for whoever hosts it, and quietly removing one teaches the publisher\n * nothing. So `inspectEmailStarter` runs first and REFUSES.\n */\nexport const publishEmailStarterHandler: 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 screenId = String(req.body?.screenId ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) return res.status(400).json({ error: priceRefusal })\n if (!hostId || !screenId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, screenId, or displayName' })\n }\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.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to 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\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const screenRef = hostRef.collection('screens').doc(screenId)\n const screenSnapshot = await screenRef.get()\n const screen = screenSnapshot.data() as Record<string, unknown> | undefined\n if (!screen || screen['deletedAt']) {\n return res.status(404).json({ error: 'Unknown email' })\n }\n if (screen['kind'] !== 'email') {\n return res\n .status(422)\n .json({ error: 'That screen is a page, not an email' })\n }\n const activeVersionId = screen['versionId']\n if (!activeVersionId) {\n return res\n .status(404)\n .json({ error: 'This email has no saved design yet — design and save it first' })\n }\n const versionSnapshot = await screenRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n\n /*\n * The site's reusable blocks INLINED before anything is judged (AGL-3287).\n * A buyer's org has none of this site's components, so a placement has to\n * travel as the blocks it renders — and inlining first is what puts a\n * shared footer's links and images in front of the inspection below, as\n * the send path would mail them. An undecodable payload is left as stored,\n * so the inspection still refuses it by name.\n */\n const stored = versionSnapshot.get('nodes')\n const readable = decodeStoredNodes<Record<string, unknown>>(stored)\n let design: unknown = stored\n if (readable && typeof readable === 'object' && !Array.isArray(readable)) {\n const inlined = await inlineReusableBlocks(readable, {\n firestore,\n hostId,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n design = inlined.nodes\n }\n // The inspection decodes, so it is also the guard against publishing a\n // node map nothing could read — it refuses rather than reporting a\n // compressed payload as a clean design.\n const inspection = inspectEmailStarter(design)\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res.status(422).json({\n error: violation,\n violations: inspection.violations,\n })\n }\n if (!inspection.nodes || !Object.keys(inspection.nodes).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n // Runs after the inspection and over the same decoded map. It enforces the\n // component-id allowlist and trims node keys; the URL rules it also carries\n // can no longer fire, because a design that would have tripped them was\n // refused above rather than silently trimmed.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: inspection.nodes },\n { componentIds: MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (publisher org, source screen). Re-publishing the same\n // email bumps its version rather than minting a second listing, which is\n // what makes \"update available\" mean anything to everyone who installed it.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('sourceScreenId', '==', screenId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailStarter',\n sourceHostId: hostId,\n sourceScreenId: screenId,\n displayName: displayName.trim(),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n // Copy is part of the design and travels with it.\n subject: String(screen['emailSubject'] ?? ''),\n preheader: String(screen['emailPreheader'] ?? ''),\n // The hosts this design would send a recipient to, recorded at publish\n // so the listing page can show them BEFORE somebody installs. A tenant\n // about to mail their own customers under their own name is entitled to\n // see the domains a stranger's template points them at, and no\n // allowlist can make that judgment for them.\n linkHosts: inspection.linkHosts,\n // Absent `reviewState` is the un-reviewed default, and it is written\n // NOWHERE here on purpose: a publisher who could stamp their own\n // version approved would make the field decorative. Staff write it.\n publishedAt: now,\n })\n\n return res\n .status(200)\n .json({ listingId: listingRef.id, version, linkHosts: inspection.linkHosts })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter publish failed' })\n }\n}\n\nexport default publishEmailStarterHandler\n"],"names":["CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","publishEmailStarterHandler","req","res","method","status","json","error","hostId","String","body","screenId","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","authorization","headers","idToken","startsWith","length","undefined","hostSnapshot","existing","screen","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","orgForHost","org","orgId","publisher","refusal","sells","screenRef","screenSnapshot","data","activeVersionId","versionSnapshot","stored","readable","design","Array","isArray","inlined","rootId","ok","nodes","inspection","violation","violations","Object","keys","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","set","profileId","artifactType","sourceHostId","sourceScreenId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","linkHosts","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,gBAAgB,EAChBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,gDAAgD,EAChDC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AAEpE;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,MAAMC,6BAA+C,OAAOC,KAAKC;iDAkBzCD;QAdPA,WACEA,YACGA,YACAA,YACHA,YACWA;IARnC,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD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AAC;AAED,eAAeN,2BAA0B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-starter.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 { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { decodeStoredNodes } from '@aglyn/aglyn/app-utils/stored-nodes'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n emailStarterRefusal,\n inspectEmailStarter,\n MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's campaign email design as a marketplace starter.\n *\n * The source is a `kind: 'email'` SCREEN — the document `createEmailScreen`\n * writes and the screen besigner edits — not an entry in the transactional\n * catalog. That is the whole difference from `publish-email-template`, and it\n * is why the two exist separately: a transactional design is a design FOR a\n * fixed key and installs onto that same key; a starter belongs to no key and\n * installs as a new email of the buyer's own.\n *\n * ## Two things this reads that the transactional publisher does not\n *\n * **The nodes are compressed.** A screen version is written through\n * `screenVersionConverter`, so `nodes` comes back from the Admin SDK as a\n * msgpack `Buffer`. `publish-email-template.ts` reads its `nodes` raw and says\n * why — its besigner saves with a bare `setDoc` and no converter — and copying\n * that line here would publish a Buffer: truthy, non-empty by `Object.keys`\n * (those are byte indices), and scanning as a design with no blocks in it.\n *\n * **The tree is inspected, not just sanitized.** `sanitizeMarketplaceDefinition`\n * DROPS an unsafe URL and publishes what is left, which is right for a page.\n * Here the URL rules are the product: a remote image in an email is a read\n * receipt for whoever hosts it, and quietly removing one teaches the publisher\n * nothing. So `inspectEmailStarter` runs first and REFUSES.\n */\nexport const publishEmailStarterHandler: 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 screenId = String(req.body?.screenId ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) return res.status(400).json({ error: priceRefusal })\n if (!hostId || !screenId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, screenId, or displayName' })\n }\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.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to 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\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const screenRef = hostRef.collection('screens').doc(screenId)\n const screenSnapshot = await screenRef.get()\n const screen = screenSnapshot.data() as Record<string, unknown> | undefined\n if (!screen || screen['deletedAt']) {\n return res.status(404).json({ error: 'Unknown email' })\n }\n if (screen['kind'] !== 'email') {\n return res\n .status(422)\n .json({ error: 'That screen is a page, not an email' })\n }\n const activeVersionId = screen['versionId']\n if (!activeVersionId) {\n return res\n .status(404)\n .json({ error: 'This email has no saved design yet — design and save it first' })\n }\n const versionSnapshot = await screenRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n\n /*\n * The site's reusable blocks INLINED before anything is judged (AGL-3287).\n * A buyer's org has none of this site's components, so a placement has to\n * travel as the blocks it renders — and inlining first is what puts a\n * shared footer's links and images in front of the inspection below, as\n * the send path would mail them. An undecodable payload is left as stored,\n * so the inspection still refuses it by name.\n */\n const stored = versionSnapshot.get('nodes')\n const readable = decodeStoredNodes<Record<string, unknown>>(stored)\n let design: unknown = stored\n if (readable && typeof readable === 'object' && !Array.isArray(readable)) {\n const inlined = await inlineReusableBlocks(readable, {\n firestore,\n hostId,\n rootId: CANVAS_ROOT_ELEMENT_ID,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n design = inlined.nodes\n }\n // The inspection decodes, so it is also the guard against publishing a\n // node map nothing could read — it refuses rather than reporting a\n // compressed payload as a clean design.\n const inspection = inspectEmailStarter(design)\n const violation = emailStarterRefusal(inspection)\n if (violation) {\n return res.status(422).json({\n error: violation,\n violations: inspection.violations,\n })\n }\n if (!inspection.nodes || !Object.keys(inspection.nodes).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n // Runs after the inspection and over the same decoded map. It enforces the\n // component-id allowlist and trims node keys; the URL rules it also carries\n // can no longer fire, because a design that would have tripped them was\n // refused above rather than silently trimmed.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId: CANVAS_ROOT_ELEMENT_ID, nodes: inspection.nodes },\n { componentIds: MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (publisher org, source screen). Re-publishing the same\n // email bumps its version rather than minting a second listing, which is\n // what makes \"update available\" mean anything to everyone who installed it.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('sourceScreenId', '==', screenId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailStarter',\n sourceHostId: hostId,\n sourceScreenId: screenId,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n // Copy is part of the design and travels with it.\n subject: String(screen['emailSubject'] ?? ''),\n preheader: String(screen['emailPreheader'] ?? ''),\n // The hosts this design would send a recipient to, recorded at publish\n // so the listing page can show them BEFORE somebody installs. A tenant\n // about to mail their own customers under their own name is entitled to\n // see the domains a stranger's template points them at, and no\n // allowlist can make that judgment for them.\n linkHosts: inspection.linkHosts,\n // Absent `reviewState` is the un-reviewed default, and it is written\n // NOWHERE here on purpose: a publisher who could stamp their own\n // version approved would make the field decorative. Staff write it.\n publishedAt: now,\n })\n\n return res\n .status(200)\n .json({ listingId: listingRef.id, version, linkHosts: inspection.linkHosts })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Email starter publish failed' })\n }\n}\n\nexport default publishEmailStarterHandler\n"],"names":["displayNameSearchFields","CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","emailStarterRefusal","inspectEmailStarter","MARKETPLACE_EMAIL_STARTER_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","refreshListingQueryFields","publishEmailStarterHandler","req","res","method","status","json","error","hostId","String","body","screenId","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","authorization","headers","idToken","startsWith","length","undefined","hostSnapshot","existing","screen","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","orgForHost","org","orgId","publisher","refusal","sells","screenRef","screenSnapshot","data","activeVersionId","versionSnapshot","stored","readable","design","Array","isArray","inlined","rootId","ok","nodes","inspection","violation","violations","Object","keys","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","set","profileId","artifactType","sourceHostId","sourceScreenId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","linkHosts","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,sBAAsB,EACtBC,gBAAgB,EAChBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,iBAAiB,QAAQ,sCAAqC;AACvE,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,mBAAmB,EACnBC,mBAAmB,EACnBC,gDAAgD,EAChDC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,yBAAyB,QAAQ,4BAAwB;AAElE;;;;;;;;;;;;;;;;;;;;;;;;CAwBC,GACD,OAAO,MAAMC,6BAA+C,OAAOC,KAAKC;iDAkBzCD;QAdPA,WACEA,YACGA,YACAA,YACHA,YACWA;IARnC,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,WAAWF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,QAAQ,oBAAI;IAC9C,MAAMC,cAAcH,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUU,WAAW,oBAAI,IAAIC,KAAK,CAAC,GAAG;IACjE,MAAMC,cAAcL,iBAAOP,aAAAA,I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WAAWX;YACXY,gBAAgBtG,cAAciD,SAAS,CAAC0C,UAAU,CAACY,UAAU,CAAC;gBAC5Dd;gBACAe,aAAaxG,cAAciD,SAAS,CAACwD,SAAS,CAACf,GAAG;YACpD;YAEF;YAAEgB,OAAO;QAAK;QAEhB,gFAAgF;QAChF,MAAMhG,0BAA0B2E;QAChC,MAAMA,WACHlC,UAAU,CAAC,YACXC,GAAG,CAACjC,OAAOsE,UACXI,GAAG,CAAC;YACHpB,QAAQQ,UAAUR,MAAM;YACxBE,OAAOM,UAAUN,KAAK;YACtB,kDAAkD;YAClDgC,SAASxF,QAAOqB,uBAAAA,MAAM,CAAC,eAAe,YAAtBA,uBAA0B;YAC1CoE,WAAWzF,QAAOqB,yBAAAA,MAAM,CAAC,iBAAiB,YAAxBA,yBAA4B;YAC9C,uEAAuE;YACvE,uEAAuE;YACvE,wEAAwE;YACxE,+DAA+D;YAC/D,6CAA6C;YAC7CqE,WAAWjC,WAAWiC,SAAS;YAC/B,qEAAqE;YACrE,iEAAiE;YACjE,oEAAoE;YACpEL,aAAad;QACf;QAEF,OAAO7E,IACJE,MAAM,CAAC,KACPC,IAAI,CAAC;YAAE8F,WAAWzB,WAAW0B,EAAE;YAAEtB;YAASoB,WAAWjC,WAAWiC,SAAS;QAAC;IAC/E,EAAE,OAAO5F,OAAO;QACd+F,QAAQ/F,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAA+B;IACtE;AACF,EAAC;AAED,eAAeN,2BAA0B"}
|
|
@@ -14,7 +14,8 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import {
|
|
17
|
+
*/ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
|
|
18
|
+
import { checkEntitlement, createResourceUid, decodeStoredNodes } from "@aglyn/aglyn/server";
|
|
18
19
|
import { inlineReusableBlocks } from "./publish-email-blocks.js";
|
|
19
20
|
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
20
21
|
import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
|
|
@@ -22,6 +23,7 @@ import { EMAIL_NODE_ROOT_ID, getTenantEmail, isTenantEmailEditable, TENANT_EMAIL
|
|
|
22
23
|
import { MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST, marketplacePriceRefusal, sanitizeMarketplaceDefinition } from "../model/index.js";
|
|
23
24
|
import { resolvePublisherProfile } from "./publisher-profile.js";
|
|
24
25
|
import { publishPreconditionRefusal } from "./publish-preconditions.js";
|
|
26
|
+
import { refreshListingQueryFields } from "./listing-query-fields.js";
|
|
25
27
|
/**
|
|
26
28
|
* Publishes a site's designed transactional email to the marketplace
|
|
27
29
|
* (AGL-657).
|
|
@@ -182,7 +184,7 @@ import { publishPreconditionRefusal } from "./publish-preconditions.js";
|
|
|
182
184
|
sourceHostId: hostId,
|
|
183
185
|
emailTemplateKey: templateKey,
|
|
184
186
|
displayName: displayName.trim()
|
|
185
|
-
}, description.trim() && {
|
|
187
|
+
}, displayNameSearchFields(displayName.trim()), description.trim() && {
|
|
186
188
|
description: description.trim()
|
|
187
189
|
}, category.trim() && {
|
|
188
190
|
category: category.trim()
|
|
@@ -201,6 +203,8 @@ import { publishPreconditionRefusal } from "./publish-preconditions.js";
|
|
|
201
203
|
}), {
|
|
202
204
|
merge: true
|
|
203
205
|
});
|
|
206
|
+
// The lists this listing appears in query by fields derived from it (AGL-3321).
|
|
207
|
+
await refreshListingQueryFields(listingRef);
|
|
204
208
|
await listingRef.collection('versions').doc(String(version)).set({
|
|
205
209
|
rootId: sanitized.rootId,
|
|
206
210
|
nodes: sanitized.nodes,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-template.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n EMAIL_NODE_ROOT_ID,\n getTenantEmail,\n isTenantEmailEditable,\n TENANT_EMAIL_COLLECTION,\n} from '@aglyn/shared-util-email'\nimport {\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\n\n/**\n * Publishes a site's designed transactional email to the marketplace\n * (AGL-657).\n *\n * An email design is a node tree like any other artifact, but it does NOT live\n * in the host's screen routing map — which is exactly why `publish-template`\n * could never capture one (it only sees `hostSnapshot.get('screens')`). The\n * tree lives at `hosts/{h}/emailTemplates/{key}/versions/{versionId}`, so this\n * reads it directly.\n *\n * `templateKey` is a fixed catalog key ('booking-confirmed', …), not a free\n * id: a published email means \"a design FOR this transactional email\", so the\n * key travels with the listing and the installer lands on the same key.\n */\nexport const publishEmailTemplateHandler: PluginApiHandler = async (\n req,\n res,\n) => {\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 templateKey = String(req.body?.templateKey ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n // The price floor and ceiling, from ONE validator (AGL-2343): a paid listing\n // under `MARKETPLACE_MIN_PRICE_USD` loses money on every sale, because\n // marketplace checkout is a destination charge whose Stripe fee is debited\n // from the platform's balance. Also enforced in `publishPreconditionRefusal`\n // below, so a door that drops this line is still covered.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\n }\n if (!hostId || !templateKey || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, templateKey, or displayName' })\n }\n const entry = getTenantEmail(templateKey)\n if (!entry || !isTenantEmailEditable(entry)) {\n return res.status(400).json({ error: 'Not a designable email template' })\n }\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.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to 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\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const templateRef = hostRef\n .collection(TENANT_EMAIL_COLLECTION)\n .doc(templateKey)\n const templateSnapshot = await templateRef.get()\n const activeVersionId = templateSnapshot.get('versionId')\n if (!templateSnapshot.exists || !activeVersionId) {\n return res.status(404).json({\n error: 'This email has no published design yet — design and save it first',\n })\n }\n const versionSnapshot = await templateRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n // Decoded, like the screen and layout publish paths (AGL-1395): the email\n // besigner now compresses through a converter as those do, and versions\n // written before it did are still plain maps, which come back unchanged.\n //\n // `sanitizeMarketplaceDefinition` below would refuse an undecoded tree\n // rather than publish garbage, so this is the difference between the\n // feature working and a publish that always says the design is invalid.\n const stored = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!stored || !Object.keys(stored).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n const rootId = versionSnapshot.get('rootId') ?? EMAIL_NODE_ROOT_ID\n // The site's reusable blocks INLINED (AGL-3287): a listing is installed\n // into another org, which has none of this site's components, and the\n // sanitizer below refuses a component reference outright.\n const inlined = await inlineReusableBlocks(stored, {\n firestore,\n hostId,\n rootId,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n const nodes = inlined.nodes\n // Emails are built from `plugins-email` blocks only, so the page allowlist\n // is REPLACED rather than extended — see MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST\n // for why `emailHtml` is not on the list.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n { componentIds: MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (source site, template key).\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('emailTemplateKey', '==', templateKey)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailTemplate',\n sourceHostId: hostId,\n emailTemplateKey: templateKey,\n displayName: displayName.trim(),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n emailTemplateKey: templateKey,\n // The copy fields are part of the design, not the tree.\n subject: String(templateSnapshot.get('subject') ?? ''),\n preheader: String(templateSnapshot.get('preheader') ?? ''),\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Publish failed' })\n }\n}\n\nexport default publishEmailTemplateHandler\n"],"names":["checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","EMAIL_NODE_ROOT_ID","getTenantEmail","isTenantEmailEditable","TENANT_EMAIL_COLLECTION","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","publishEmailTemplateHandler","req","res","method","status","json","error","hostId","String","body","templateKey","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","entry","authorization","headers","idToken","startsWith","length","undefined","hostSnapshot","versionSnapshot","existing","templateSnapshot","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","orgForHost","org","orgId","publisher","refusal","sells","templateRef","activeVersionId","stored","Object","keys","rootId","inlined","ok","nodes","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","set","profileId","artifactType","sourceHostId","emailTemplateKey","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,kBAAkB,EAClBC,cAAc,EACdC,qBAAqB,EACrBC,uBAAuB,QAClB,2BAA0B;AACjC,SACEC,wCAAwC,EACxCC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AAEpE;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,8BAAgD,OAC3DC,KACAC;iDA8B6BD;QAzBPA,WACKA,YACAA,YACAA,YACHA,YACWA;IARnC,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBA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AS,CAACgC,UAAU,CAACY,UAAU,CAAC;gBAC5Dd;gBACAe,aAAajG,cAAcoD,SAAS,CAAC8C,SAAS,CAACf,GAAG;YACpD;YAEF;YAAEgB,OAAO;QAAK;QAEhB,MAAMrB,WACHxB,UAAU,CAAC,YACXC,GAAG,CAACnC,OAAO8D,UACXI,GAAG,CAAC;YACHhB,QAAQI,UAAUJ,MAAM;YACxBG,OAAOC,UAAUD,KAAK;YACtBiB,kBAAkBpE;YAClB,wDAAwD;YACxD8E,SAAShF,QAAOuB,wBAAAA,iBAAiBa,GAAG,CAAC,sBAArBb,wBAAmC;YACnD0D,WAAWjF,QAAOuB,yBAAAA,iBAAiBa,GAAG,CAAC,wBAArBb,yBAAqC;YACvDsD,aAAad;QACf;QAEF,OAAOrE,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEqF,WAAWxB,WAAWyB,EAAE;YAAErB;QAAQ;IAClE,EAAE,OAAOhE,OAAO;QACdsF,QAAQtF,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC;AAED,eAAeN,4BAA2B"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-email-template.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 { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { inlineReusableBlocks } from './publish-email-blocks'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n EMAIL_NODE_ROOT_ID,\n getTenantEmail,\n isTenantEmailEditable,\n TENANT_EMAIL_COLLECTION,\n} from '@aglyn/shared-util-email'\nimport {\n MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST,\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/**\n * Publishes a site's designed transactional email to the marketplace\n * (AGL-657).\n *\n * An email design is a node tree like any other artifact, but it does NOT live\n * in the host's screen routing map — which is exactly why `publish-template`\n * could never capture one (it only sees `hostSnapshot.get('screens')`). The\n * tree lives at `hosts/{h}/emailTemplates/{key}/versions/{versionId}`, so this\n * reads it directly.\n *\n * `templateKey` is a fixed catalog key ('booking-confirmed', …), not a free\n * id: a published email means \"a design FOR this transactional email\", so the\n * key travels with the listing and the installer lands on the same key.\n */\nexport const publishEmailTemplateHandler: PluginApiHandler = async (\n req,\n res,\n) => {\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 templateKey = String(req.body?.templateKey ?? '')\n const displayName = String(req.body?.displayName ?? '').slice(0, 80)\n const description = String(req.body?.description ?? '').slice(0, 500)\n const category = String(req.body?.category ?? '').slice(0, 40)\n const priceUsd = Math.round(Number(req.body?.priceUsd ?? 0)) || 0\n // The price floor and ceiling, from ONE validator (AGL-2343): a paid listing\n // under `MARKETPLACE_MIN_PRICE_USD` loses money on every sale, because\n // marketplace checkout is a destination charge whose Stripe fee is debited\n // from the platform's balance. Also enforced in `publishPreconditionRefusal`\n // below, so a door that drops this line is still covered.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\n }\n if (!hostId || !templateKey || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, templateKey, or displayName' })\n }\n const entry = getTenantEmail(templateKey)\n if (!entry || !isTenantEmailEditable(entry)) {\n return res.status(400).json({ error: 'Not a designable email template' })\n }\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.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to 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\n const orgForHost = await getOrgForHost(hostId)\n if (!checkEntitlement(orgForHost?.org ?? {}, 'marketplaceSelling')) {\n return res\n .status(403)\n .json({ error: 'Publishing to the marketplace requires a Pro plan' })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'templates',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const templateRef = hostRef\n .collection(TENANT_EMAIL_COLLECTION)\n .doc(templateKey)\n const templateSnapshot = await templateRef.get()\n const activeVersionId = templateSnapshot.get('versionId')\n if (!templateSnapshot.exists || !activeVersionId) {\n return res.status(404).json({\n error: 'This email has no published design yet — design and save it first',\n })\n }\n const versionSnapshot = await templateRef\n .collection('versions')\n .doc(String(activeVersionId))\n .get()\n // Decoded, like the screen and layout publish paths (AGL-1395): the email\n // besigner now compresses through a converter as those do, and versions\n // written before it did are still plain maps, which come back unchanged.\n //\n // `sanitizeMarketplaceDefinition` below would refuse an undecoded tree\n // rather than publish garbage, so this is the difference between the\n // feature working and a publish that always says the design is invalid.\n const stored = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!stored || !Object.keys(stored).length) {\n return res.status(404).json({ error: 'This email design is empty' })\n }\n const rootId = versionSnapshot.get('rootId') ?? EMAIL_NODE_ROOT_ID\n // The site's reusable blocks INLINED (AGL-3287): a listing is installed\n // into another org, which has none of this site's components, and the\n // sanitizer below refuses a component reference outright.\n const inlined = await inlineReusableBlocks(stored, {\n firestore,\n hostId,\n rootId,\n })\n if (inlined.ok === false) {\n return res.status(422).json({ error: inlined.error })\n }\n const nodes = inlined.nodes\n // Emails are built from `plugins-email` blocks only, so the page allowlist\n // is REPLACED rather than extended — see MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST\n // for why `emailHtml` is not on the list.\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n { componentIds: MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST },\n )\n if (sanitized.ok === false) {\n return res.status(422).json({ error: sanitized.error })\n }\n\n // One listing per (source site, template key).\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceHostId', '==', hostId)\n .where('emailTemplateKey', '==', templateKey)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n await listingRef.set(\n {\n profileId: publisher.orgId,\n artifactType: 'emailTemplate',\n sourceHostId: hostId,\n emailTemplateKey: templateKey,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef\n .collection('versions')\n .doc(String(version))\n .set({\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n emailTemplateKey: templateKey,\n // The copy fields are part of the design, not the tree.\n subject: String(templateSnapshot.get('subject') ?? ''),\n preheader: String(templateSnapshot.get('preheader') ?? ''),\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Publish failed' })\n }\n}\n\nexport default publishEmailTemplateHandler\n"],"names":["displayNameSearchFields","checkEntitlement","createResourceUid","decodeStoredNodes","inlineReusableBlocks","firebaseAdmin","getOrgForHost","resolveOrgPermissions","EMAIL_NODE_ROOT_ID","getTenantEmail","isTenantEmailEditable","TENANT_EMAIL_COLLECTION","MARKETPLACE_EMAIL_COMPONENT_ID_ALLOWLIST","marketplacePriceRefusal","sanitizeMarketplaceDefinition","resolvePublisherProfile","publishPreconditionRefusal","refreshListingQueryFields","publishEmailTemplateHandler","req","res","method","status","json","error","hostId","String","body","templateKey","displayName","slice","description","category","priceUsd","Math","round","Number","priceRefusal","trim","entry","authorization","headers","idToken","startsWith","length","undefined","hostSnapshot","versionSnapshot","existing","templateSnapshot","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","orgForHost","org","orgId","publisher","refusal","sells","templateRef","activeVersionId","stored","Object","keys","rootId","inlined","ok","nodes","sanitized","componentIds","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","set","profileId","artifactType","sourceHostId","emailTemplateKey","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","subject","preheader","listingId","id","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,oBAAoB,QAAQ,4BAAwB;AAC7D,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,kBAAkB,EAClBC,cAAc,EACdC,qBAAqB,EACrBC,uBAAuB,QAClB,2BAA0B;AACjC,SACEC,wCAAwC,EACxCC,uBAAuB,EACvBC,6BAA6B,QACxB,oBAAU;AACjB,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,yBAAyB,QAAQ,4BAAwB;AAElE;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,8BAAgD,OAC3DC,KACAC;iDA8B6BD;QAzBPA,WACKA,YACAA,YACAA,YACHA,YACWA;IARnC,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,cAAcF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,WAAW,oBAAI;IACpD,MAAMC,cAAcH,iBAAOP,aA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AG;YACpD;YAEF;YAAEgB,OAAO;QAAK;QAEhB,gFAAgF;QAChF,MAAMxF,0BAA0BmE;QAChC,MAAMA,WACHxB,UAAU,CAAC,YACXC,GAAG,CAACnC,OAAO8D,UACXI,GAAG,CAAC;YACHhB,QAAQI,UAAUJ,MAAM;YACxBG,OAAOC,UAAUD,KAAK;YACtBiB,kBAAkBpE;YAClB,wDAAwD;YACxD8E,SAAShF,QAAOuB,wBAAAA,iBAAiBa,GAAG,CAAC,sBAArBb,wBAAmC;YACnD0D,WAAWjF,QAAOuB,yBAAAA,iBAAiBa,GAAG,CAAC,wBAArBb,yBAAqC;YACvDsD,aAAad;QACf;QAEF,OAAOrE,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEqF,WAAWxB,WAAWyB,EAAE;YAAErB;QAAQ;IAClE,EAAE,OAAOhE,OAAO;QACdsF,QAAQtF,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAiB;IACxD;AACF,EAAC;AAED,eAAeN,4BAA2B"}
|
|
@@ -14,13 +14,15 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import {
|
|
17
|
+
*/ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
|
|
18
|
+
import { CANVAS_ROOT_ELEMENT_ID, checkEntitlement, createResourceUid, decodeStoredNodes } from "@aglyn/aglyn/server";
|
|
18
19
|
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
19
20
|
import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
|
|
20
21
|
import { marketplacePriceRefusal, sanitizeMarketplaceDefinition } from "../model/marketplace.js";
|
|
21
22
|
import { sanitizeMarketplaceProps } from "../model/marketplace-props.js";
|
|
22
23
|
import { resolvePublisherProfile } from "./publisher-profile.js";
|
|
23
24
|
import { publishPreconditionRefusal } from "./publish-preconditions.js";
|
|
25
|
+
import { refreshListingQueryFields } from "./listing-query-fields.js";
|
|
24
26
|
/** The node marking where a bound screen's content grafts in. */ const LAYOUT_SLOT_COMPONENT_ID = 'layoutSlot';
|
|
25
27
|
/**
|
|
26
28
|
* Publishes a shared layout to the marketplace (AGL-671).
|
|
@@ -198,7 +200,7 @@ import { publishPreconditionRefusal } from "./publish-preconditions.js";
|
|
|
198
200
|
sourceHostId: hostId,
|
|
199
201
|
sourceLayoutId: layoutId,
|
|
200
202
|
displayName: displayName.trim()
|
|
201
|
-
}, description.trim() && {
|
|
203
|
+
}, displayNameSearchFields(displayName.trim()), description.trim() && {
|
|
202
204
|
description: description.trim()
|
|
203
205
|
}, category.trim() && {
|
|
204
206
|
category: category.trim()
|
|
@@ -217,6 +219,8 @@ import { publishPreconditionRefusal } from "./publish-preconditions.js";
|
|
|
217
219
|
}), {
|
|
218
220
|
merge: true
|
|
219
221
|
});
|
|
222
|
+
// The lists this listing appears in query by fields derived from it (AGL-3321).
|
|
223
|
+
await refreshListingQueryFields(listingRef);
|
|
220
224
|
await listingRef.collection('versions').doc(String(version)).set({
|
|
221
225
|
// `props` is always a list, even an empty one: install and update read a
|
|
222
226
|
// version with none as one published before properties were carried.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-layout.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model/marketplace'\nimport { sanitizeMarketplaceProps } from '../model/marketplace-props'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\n\n/** The node marking where a bound screen's content grafts in. */\nconst LAYOUT_SLOT_COMPONENT_ID = 'layoutSlot'\n\n/**\n * Publishes a shared layout to the marketplace (AGL-671).\n *\n * Layouts were the one design asset that could not be shared at all:\n * `publish-template` captures screens and theme only, and `layoutSlot` is\n * excluded from the marketplace allowlist as \"layout chrome\". Both are\n * addressed here — the slot is permitted for this artifact type\n * specifically, since a layout without one is chrome with nowhere to put\n * the page.\n *\n * Gates mirror template publishing exactly: org permission, host role,\n * `marketplaceSelling`, an org publisher profile, and payouts configured\n * before anything can be sold.\n */\nexport const publishLayoutHandler: 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 layoutId = String(req.body?.layoutId ?? '')\n const displayName = String(req.body?.displayName ?? '')\n const description = String(req.body?.description ?? '')\n const category = String(req.body?.category ?? '')\n const priceUsd = Math.max(0, Math.round(Number(req.body?.priceUsd ?? 0)))\n if (!hostId || !layoutId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, layoutId or displayName' })\n }\n // The price floor and ceiling, from ONE validator (AGL-2343). This door had\n // NO price validation at all: it clamped to zero and stored whatever came in,\n // so both a $1 listing that loses money on every sale and a $250,000 one were\n // publishable here. Also enforced in `publishPreconditionRefusal` below.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\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.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n\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\n const orgForHost = await getOrgForHost(hostId)\n const org = orgForHost?.org ?? {}\n if (!checkEntitlement(org as any, 'marketplaceSelling')) {\n return res.status(403).json({\n error: 'Publishing to the marketplace requires a Pro plan',\n })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'layouts',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const layoutRef = hostRef.collection('layouts').doc(layoutId)\n const layoutSnapshot = await layoutRef.get()\n if (!layoutSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown layout' })\n }\n const versionId = layoutSnapshot.get('versionId')\n if (!versionId) {\n return res.status(422).json({\n error: 'Publish this layout on your site first — there is no ' +\n 'published version to share',\n })\n }\n const versionSnapshot = await layoutRef\n .collection('versions')\n .doc(String(versionId))\n .get()\n // `nodes` is stored in more than one form and the besigner writes the\n // COMPRESSED one, which the Admin SDK materialises as a Node `Buffer`\n // (AGL-1395). Read raw, this was worse than the template path: the length\n // check passed on the BYTE COUNT, and the root search below walked byte\n // INDICES — byte 0 is a number, a number has no `parentId`, so `rootId`\n // resolved to `'0'` and the sanitizer built a wrapper around nothing.\n // Every besigner-edited layout was refused as empty or slotless.\n const nodes = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!nodes || !Object.keys(nodes).length) {\n return res.status(422).json({ error: 'Layout version has no content' })\n }\n\n // The layout properties its tree binds to (AGL-2933), from the same\n // version. A default the sanitizer refuses is cleared and its property\n // kept — see `sanitizeMarketplaceProps`.\n const props = sanitizeMarketplaceProps(versionSnapshot.get('props'))\n if (props.ok === false) {\n return res.status(422).json({ error: props.error })\n }\n\n // Layout versions have no explicit rootId. The besigner canvas roots them\n // at the same wrapper screens use, so prefer it outright; the parentless\n // search stays as the fallback for anything authored before that, and\n // matches how the renderer walks them. Preferring the wrapper also means a\n // top-level node that relies on child arrays alone — legal, see\n // `compose-layout-nodes` — can no longer win the search over the real root.\n const rootId: string =\n (nodes[CANVAS_ROOT_ELEMENT_ID] && CANVAS_ROOT_ELEMENT_ID) ||\n Object.keys(nodes).find((id) => !nodes[id]?.parentId) ||\n Object.keys(nodes)[0] ||\n ''\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n {\n extraComponentIds: [LAYOUT_SLOT_COMPONENT_ID],\n // A link or image bound whole to a Link or Image property travels\n // bound (AGL-2933).\n declaredProps: props.props,\n },\n )\n // `=== false` rather than `!sanitized.ok`: the compiler does not narrow\n // the union on the negated form here, and publish-template hit the same\n // thing first.\n if (sanitized.ok === false) {\n return res.status(400).json({ error: sanitized.error })\n }\n // A layout whose slot did not survive would render as chrome with the\n // page content missing — better to refuse than to publish that.\n const hasSlot = Object.values(sanitized.nodes).some(\n (node: any) => node.componentId === LAYOUT_SLOT_COMPONENT_ID,\n )\n if (!hasSlot) {\n return res.status(422).json({\n error:\n 'This layout has no content slot, so pages using it would have ' +\n 'nowhere to render',\n })\n }\n\n // One listing per source layout; re-publish bumps the version.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceLayoutId', '==', layoutId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n await listingRef.set(\n {\n artifactType: 'layout',\n profileId: publisher.orgId,\n sourceHostId: hostId,\n sourceLayoutId: layoutId,\n displayName: displayName.trim(),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n await listingRef.collection('versions').doc(String(version)).set({\n // `props` is always a list, even an empty one: install and update read a\n // version with none as one published before properties were carried.\n layout: {\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n props: props.props,\n },\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Layout publish failed' })\n }\n}\n\nexport default publishLayoutHandler\n"],"names":["CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","firebaseAdmin","getOrgForHost","resolveOrgPermissions","marketplacePriceRefusal","sanitizeMarketplaceDefinition","sanitizeMarketplaceProps","resolvePublisherProfile","publishPreconditionRefusal","LAYOUT_SLOT_COMPONENT_ID","publishLayoutHandler","req","res","method","status","json","error","hostId","String","body","layoutId","displayName","description","category","priceUsd","Math","max","round","Number","trim","priceRefusal","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","existing","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","orgForHost","org","orgId","publisher","refusal","sells","layoutRef","layoutSnapshot","versionId","versionSnapshot","nodes","Object","keys","props","ok","rootId","find","id","parentId","sanitized","extraComponentIds","declaredProps","hasSlot","values","some","node","componentId","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","set","artifactType","profileId","sourceHostId","sourceLayoutId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","layout","listingId","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,sBAAsB,EACtBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,uBAAuB,EACvBC,6BAA6B,QACxB,0BAAsB;AAC7B,SAASC,wBAAwB,QAAQ,gCAA4B;AACrE,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AAEpE,+DAA+D,GAC/D,MAAMC,2BAA2B;AAEjC;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,uBAAyC,OAAOC,KAAKC;iDAuBnCD;QAnBPA,WACEA,YACGA,YACAA,YACHA,YACuBA;IAR/C,IAAIA,IAAIE,MAAM,KAAK,QAAQ;QACzB,OAAOD,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAqB;IAC5D;IACA,MAAMC,SAASC,gBAAOP,YAAAA,IAAIQ,IAAI,qBAARR,UAAUM,MAAM,mBAAI;IAC1C,MAAMG,WAAWF,iBAAOP,aAAAA,IAAIQ,IAAI,qBAARR,WAAUS,QAAQ,oBAAI;IAC9C,MAAMC,cAA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,MAAM;YAAEP,aAAaA,YAAYO,IAAI;QAAG,GACxDN,SAASM,IAAI,MAAM;YAAEN,UAAUA,SAASM,IAAI;QAAG;YACnDL;YACAyE,eAAeT;YACfU,WAAW;WACP3D,SAAS8C,KAAK,IAAI;YAAEc,WAAWV;QAAI;YACvCW,WAAWX;YACXY,gBAAgBpG,cAAc+C,SAAS,CAAC0C,UAAU,CAACY,UAAU,CAAC;gBAC5Dd;gBACAe,aAAatG,cAAc+C,SAAS,CAACwD,SAAS,CAACf,GAAG;YACpD;YAEF;YAAEgB,OAAO;QAAK;QAEhB,MAAMrB,WAAWlC,UAAU,CAAC,YAAYC,GAAG,CAACjC,OAAOsE,UAAUI,GAAG,CAAC;YAC/D,yEAAyE;YACzE,qEAAqE;YACrEc,QAAQ;gBACNpC,QAAQI,UAAUJ,MAAM;gBACxBL,OAAOS,UAAUT,KAAK;gBACtBG,OAAOA,MAAMA,KAAK;YACpB;YACAmC,aAAad;QACf;QAEA,OAAO7E,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAE4F,WAAWvB,WAAWZ,EAAE;YAAEgB;QAAQ;IAClE,EAAE,OAAOxE,OAAO;QACd4F,QAAQ5F,KAAK,CAACA;QACd,OAAOJ,IAAIE,MAAM,CAAC,KAAKC,IAAI,CAAC;YAAEC,OAAO;QAAwB;IAC/D;AACF,EAAC;AAED,eAAeN,qBAAoB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/marketplace/src/lib/server/publish-layout.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 { displayNameSearchFields } from '@aglyn/aglyn/app-utils/name-search'\nimport {\n CANVAS_ROOT_ELEMENT_ID,\n checkEntitlement,\n createResourceUid,\n decodeStoredNodes,\n} from '@aglyn/aglyn/server'\nimport { type PluginApiHandler } from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { resolveOrgPermissions } from '@aglyn/tenant-runtime/org-permissions'\nimport {\n marketplacePriceRefusal,\n sanitizeMarketplaceDefinition,\n} from '../model/marketplace'\nimport { sanitizeMarketplaceProps } from '../model/marketplace-props'\nimport { resolvePublisherProfile } from './publisher-profile'\nimport { publishPreconditionRefusal } from './publish-preconditions'\nimport { refreshListingQueryFields } from './listing-query-fields'\n\n/** The node marking where a bound screen's content grafts in. */\nconst LAYOUT_SLOT_COMPONENT_ID = 'layoutSlot'\n\n/**\n * Publishes a shared layout to the marketplace (AGL-671).\n *\n * Layouts were the one design asset that could not be shared at all:\n * `publish-template` captures screens and theme only, and `layoutSlot` is\n * excluded from the marketplace allowlist as \"layout chrome\". Both are\n * addressed here — the slot is permitted for this artifact type\n * specifically, since a layout without one is chrome with nowhere to put\n * the page.\n *\n * Gates mirror template publishing exactly: org permission, host role,\n * `marketplaceSelling`, an org publisher profile, and payouts configured\n * before anything can be sold.\n */\nexport const publishLayoutHandler: 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 layoutId = String(req.body?.layoutId ?? '')\n const displayName = String(req.body?.displayName ?? '')\n const description = String(req.body?.description ?? '')\n const category = String(req.body?.category ?? '')\n const priceUsd = Math.max(0, Math.round(Number(req.body?.priceUsd ?? 0)))\n if (!hostId || !layoutId || !displayName.trim()) {\n return res\n .status(400)\n .json({ error: 'Missing hostId, layoutId or displayName' })\n }\n // The price floor and ceiling, from ONE validator (AGL-2343). This door had\n // NO price validation at all: it clamped to zero and stored whatever came in,\n // so both a $1 listing that loses money on every sale and a $250,000 one were\n // publishable here. Also enforced in `publishPreconditionRefusal` below.\n const priceRefusal = marketplacePriceRefusal(priceUsd)\n if (priceRefusal) {\n return res.status(400).json({ error: priceRefusal })\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.publishToMarketplace) {\n return res.status(403).json({\n error:\n 'Your organization role does not allow publishing to the marketplace',\n })\n }\n const firestore = firebaseAdmin.app().firestore()\n\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\n const orgForHost = await getOrgForHost(hostId)\n const org = orgForHost?.org ?? {}\n if (!checkEntitlement(org as any, 'marketplaceSelling')) {\n return res.status(403).json({\n error: 'Publishing to the marketplace requires a Pro plan',\n })\n }\n if (!orgForHost?.orgId) {\n return res.status(409).json({ error: 'Site has no owning organization' })\n }\n\n const publisher = await resolvePublisherProfile(firestore, orgForHost.orgId)\n // Profile, payouts AND the publisher agreement, in one gate\n // (AGL-2282) — see `publishPreconditionRefusal`.\n const refusal = publishPreconditionRefusal(publisher, {\n priceUsd,\n sells: 'layouts',\n })\n if (refusal) return res.status(refusal.status).json(refusal.body)\n\n const layoutRef = hostRef.collection('layouts').doc(layoutId)\n const layoutSnapshot = await layoutRef.get()\n if (!layoutSnapshot.exists) {\n return res.status(404).json({ error: 'Unknown layout' })\n }\n const versionId = layoutSnapshot.get('versionId')\n if (!versionId) {\n return res.status(422).json({\n error: 'Publish this layout on your site first — there is no ' +\n 'published version to share',\n })\n }\n const versionSnapshot = await layoutRef\n .collection('versions')\n .doc(String(versionId))\n .get()\n // `nodes` is stored in more than one form and the besigner writes the\n // COMPRESSED one, which the Admin SDK materialises as a Node `Buffer`\n // (AGL-1395). Read raw, this was worse than the template path: the length\n // check passed on the BYTE COUNT, and the root search below walked byte\n // INDICES — byte 0 is a number, a number has no `parentId`, so `rootId`\n // resolved to `'0'` and the sanitizer built a wrapper around nothing.\n // Every besigner-edited layout was refused as empty or slotless.\n const nodes = decodeStoredNodes<Record<string, any>>(\n versionSnapshot.get('nodes'),\n )\n if (!nodes || !Object.keys(nodes).length) {\n return res.status(422).json({ error: 'Layout version has no content' })\n }\n\n // The layout properties its tree binds to (AGL-2933), from the same\n // version. A default the sanitizer refuses is cleared and its property\n // kept — see `sanitizeMarketplaceProps`.\n const props = sanitizeMarketplaceProps(versionSnapshot.get('props'))\n if (props.ok === false) {\n return res.status(422).json({ error: props.error })\n }\n\n // Layout versions have no explicit rootId. The besigner canvas roots them\n // at the same wrapper screens use, so prefer it outright; the parentless\n // search stays as the fallback for anything authored before that, and\n // matches how the renderer walks them. Preferring the wrapper also means a\n // top-level node that relies on child arrays alone — legal, see\n // `compose-layout-nodes` — can no longer win the search over the real root.\n const rootId: string =\n (nodes[CANVAS_ROOT_ELEMENT_ID] && CANVAS_ROOT_ELEMENT_ID) ||\n Object.keys(nodes).find((id) => !nodes[id]?.parentId) ||\n Object.keys(nodes)[0] ||\n ''\n const sanitized = sanitizeMarketplaceDefinition(\n { rootId, nodes },\n {\n extraComponentIds: [LAYOUT_SLOT_COMPONENT_ID],\n // A link or image bound whole to a Link or Image property travels\n // bound (AGL-2933).\n declaredProps: props.props,\n },\n )\n // `=== false` rather than `!sanitized.ok`: the compiler does not narrow\n // the union on the negated form here, and publish-template hit the same\n // thing first.\n if (sanitized.ok === false) {\n return res.status(400).json({ error: sanitized.error })\n }\n // A layout whose slot did not survive would render as chrome with the\n // page content missing — better to refuse than to publish that.\n const hasSlot = Object.values(sanitized.nodes).some(\n (node: any) => node.componentId === LAYOUT_SLOT_COMPONENT_ID,\n )\n if (!hasSlot) {\n return res.status(422).json({\n error:\n 'This layout has no content slot, so pages using it would have ' +\n 'nowhere to render',\n })\n }\n\n // One listing per source layout; re-publish bumps the version.\n const existing = await firestore\n .collection('marketplaceListings')\n .where('profileId', '==', publisher.orgId)\n .where('sourceLayoutId', '==', layoutId)\n .limit(1)\n .get()\n const listingRef = existing.empty\n ? firestore.collection('marketplaceListings').doc(createResourceUid())\n : existing.docs[0].ref\n const version = existing.empty\n ? 1\n : Number(existing.docs[0].get('latestVersion') ?? 0) + 1\n const now = firebaseAdmin.firestore.FieldValue.serverTimestamp()\n\n await listingRef.set(\n {\n artifactType: 'layout',\n profileId: publisher.orgId,\n sourceHostId: hostId,\n sourceLayoutId: layoutId,\n displayName: displayName.trim(),\n // The keys a listing is searched by (AGL-3321): the template gallery's\n // marketplace shelf asks `nameTokens` on its query.\n ...displayNameSearchFields(displayName.trim()),\n ...(description.trim() && { description: description.trim() }),\n ...(category.trim() && { category: category.trim() }),\n priceUsd,\n latestVersion: version,\n deletedAt: null,\n ...(existing.empty && { createdAt: now }),\n updatedAt: now,\n versionHistory: firebaseAdmin.firestore.FieldValue.arrayUnion({\n version,\n publishedAt: firebaseAdmin.firestore.Timestamp.now(),\n }),\n },\n { merge: true },\n )\n // The lists this listing appears in query by fields derived from it (AGL-3321).\n await refreshListingQueryFields(listingRef)\n await listingRef.collection('versions').doc(String(version)).set({\n // `props` is always a list, even an empty one: install and update read a\n // version with none as one published before properties were carried.\n layout: {\n rootId: sanitized.rootId,\n nodes: sanitized.nodes,\n props: props.props,\n },\n publishedAt: now,\n })\n\n return res.status(200).json({ listingId: listingRef.id, version })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Layout publish failed' })\n }\n}\n\nexport default publishLayoutHandler\n"],"names":["displayNameSearchFields","CANVAS_ROOT_ELEMENT_ID","checkEntitlement","createResourceUid","decodeStoredNodes","firebaseAdmin","getOrgForHost","resolveOrgPermissions","marketplacePriceRefusal","sanitizeMarketplaceDefinition","sanitizeMarketplaceProps","resolvePublisherProfile","publishPreconditionRefusal","refreshListingQueryFields","LAYOUT_SLOT_COMPONENT_ID","publishLayoutHandler","req","res","method","status","json","error","hostId","String","body","layoutId","displayName","description","category","priceUsd","Math","max","round","Number","trim","priceRefusal","authorization","headers","idToken","startsWith","slice","length","undefined","hostSnapshot","existing","decoded","app","auth","verifyIdToken","membership","uid","permissions","publishToMarketplace","firestore","hostRef","collection","doc","get","exists","memberRole","orgForHost","org","orgId","publisher","refusal","sells","layoutRef","layoutSnapshot","versionId","versionSnapshot","nodes","Object","keys","props","ok","rootId","find","id","parentId","sanitized","extraComponentIds","declaredProps","hasSlot","values","some","node","componentId","where","limit","listingRef","empty","docs","ref","version","now","FieldValue","serverTimestamp","set","artifactType","profileId","sourceHostId","sourceLayoutId","latestVersion","deletedAt","createdAt","updatedAt","versionHistory","arrayUnion","publishedAt","Timestamp","merge","layout","listingId","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,uBAAuB,QAAQ,qCAAoC;AAC5E,SACEC,sBAAsB,EACtBC,gBAAgB,EAChBC,iBAAiB,EACjBC,iBAAiB,QACZ,sBAAqB;AAE5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,qBAAqB,QAAQ,wCAAuC;AAC7E,SACEC,uBAAuB,EACvBC,6BAA6B,QACxB,0BAAsB;AAC7B,SAASC,wBAAwB,QAAQ,gCAA4B;AACrE,SAASC,uBAAuB,QAAQ,yBAAqB;AAC7D,SAASC,0BAA0B,QAAQ,6BAAyB;AACpE,SAASC,yBAAyB,QAAQ,4BAAwB;AAElE,+DAA+D,GAC/D,MAAMC,2BAA2B;AAEjC;;;;;;;;;;;;;CAaC,GACD,OAAO,MAAMC,uBAAyC,OAAOC,KAAKC;iDAuBnCD;QAnBPA,WACEA,YACGA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C;AAED,eAAeN,qBAAoB"}
|
|
@@ -14,11 +14,13 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
|
14
14
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
15
|
* See the License for the specific language governing permissions and
|
|
16
16
|
* limitations under the License.
|
|
17
|
-
*/ import {
|
|
17
|
+
*/ import { displayNameSearchFields } from "@aglyn/aglyn/app-utils/name-search";
|
|
18
|
+
import { checkEntitlement, checkPluginBundle, createResourceUid, MAX_PLUGIN_BUNDLE_BYTES, pluginArtifactPath, PLUGIN_VERIFIER_VERSION, validatePluginManifest } from "@aglyn/aglyn/server";
|
|
18
19
|
import { firebaseAdmin, getOrgForUser, notifyStaff } from "@aglyn/tenant-data-admin";
|
|
19
20
|
import { resolveOrgPermissions } from "@aglyn/tenant-runtime/org-permissions";
|
|
20
21
|
import { canActAsPublisher, resolvePublisherProfile } from "./publisher-profile.js";
|
|
21
22
|
import { publishPreconditionRefusal } from "./publish-preconditions.js";
|
|
23
|
+
import { refreshListingQueryFields } from "./listing-query-fields.js";
|
|
22
24
|
import { attestationLabels, missingAttestations, missingAttestationSubjects, PUBLISHER_ATTESTATION } from "../model/publisher-attestation.js";
|
|
23
25
|
import { createHash } from "crypto";
|
|
24
26
|
import { marketplacePriceRefusal, missingPublicListingContent, validateListingContent } from "../model/marketplace.js";
|
|
@@ -81,13 +83,15 @@ const MAX_BUNDLE_BYTES = 5 * 1024 * 1024;
|
|
|
81
83
|
const nextName = typeof displayName === 'string' ? displayName.trim().slice(0, 80) : '';
|
|
82
84
|
await listingRef.set(_extends({}, verdict.content, typeof description === 'string' ? {
|
|
83
85
|
description: description.slice(0, 500)
|
|
84
|
-
} : {}, nextName ? {
|
|
86
|
+
} : {}, nextName ? _extends({
|
|
85
87
|
displayName: nextName
|
|
86
|
-
} : {}, {
|
|
88
|
+
}, displayNameSearchFields(nextName)) : {}, {
|
|
87
89
|
updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
|
|
88
90
|
}), {
|
|
89
91
|
merge: true
|
|
90
92
|
});
|
|
93
|
+
// A renamed listing is searched by its new name (AGL-3321).
|
|
94
|
+
await refreshListingQueryFields(listingRef);
|
|
91
95
|
return res.status(200).json({
|
|
92
96
|
ok: true
|
|
93
97
|
});
|
|
@@ -154,6 +158,9 @@ const MAX_BUNDLE_BYTES = 5 * 1024 * 1024;
|
|
|
154
158
|
}, {
|
|
155
159
|
merge: true
|
|
156
160
|
});
|
|
161
|
+
// Private leaves browse and public joins it, through the audience the
|
|
162
|
+
// browse query reads (AGL-3321).
|
|
163
|
+
await refreshListingQueryFields(listingRef);
|
|
157
164
|
return res.status(200).json({
|
|
158
165
|
ok: true,
|
|
159
166
|
visibility
|
|
@@ -165,9 +172,64 @@ const MAX_BUNDLE_BYTES = 5 * 1024 * 1024;
|
|
|
165
172
|
});
|
|
166
173
|
}
|
|
167
174
|
};
|
|
175
|
+
/**
|
|
176
|
+
* Unpublish or republish a listing (AGL-3321).
|
|
177
|
+
*
|
|
178
|
+
* This was the one client write to a listing: the seller panel set
|
|
179
|
+
* `deletedAt` directly. Browse now queries a listing's AUDIENCE, which
|
|
180
|
+
* follows from `deletedAt` among other fields, and a client write cannot
|
|
181
|
+
* re-derive it — so the toggle moved here, beside `set-visibility`, and the
|
|
182
|
+
* rules deny `deletedAt` to clients. Publisher-or-staff, like the other two
|
|
183
|
+
* listing actions; unlike them it reaches a listing that is already
|
|
184
|
+
* unpublished, since republishing is half of what it does.
|
|
185
|
+
*/ const setListingPublished = async (req, res)=>{
|
|
186
|
+
var _ref, _req_headers_authorization;
|
|
187
|
+
var _req_body, _req_body1;
|
|
188
|
+
const listingId = String((_ref = (_req_body = req.body) == null ? void 0 : _req_body.listingId) != null ? _ref : '');
|
|
189
|
+
const published = ((_req_body1 = req.body) == null ? void 0 : _req_body1.published) === true;
|
|
190
|
+
if (!listingId) return res.status(400).json({
|
|
191
|
+
error: 'Missing listingId'
|
|
192
|
+
});
|
|
193
|
+
const authorization = String((_req_headers_authorization = req.headers.authorization) != null ? _req_headers_authorization : '');
|
|
194
|
+
const idToken = authorization.startsWith('Bearer ') ? authorization.slice('Bearer '.length) : undefined;
|
|
195
|
+
if (!idToken) return res.status(401).json({
|
|
196
|
+
error: 'Unauthenticated'
|
|
197
|
+
});
|
|
198
|
+
try {
|
|
199
|
+
const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
|
|
200
|
+
const firestore = firebaseAdmin.app().firestore();
|
|
201
|
+
const listingRef = firestore.collection('marketplaceListings').doc(listingId);
|
|
202
|
+
const listing = (await listingRef.get()).data();
|
|
203
|
+
if (!listing) return res.status(404).json({
|
|
204
|
+
error: 'Unknown listing'
|
|
205
|
+
});
|
|
206
|
+
const isPublisher = await canActAsPublisher(firestore, decoded.uid, listing.profileId);
|
|
207
|
+
if (!isPublisher && decoded['staff'] !== true) {
|
|
208
|
+
return res.status(403).json({
|
|
209
|
+
error: 'Not your listing'
|
|
210
|
+
});
|
|
211
|
+
}
|
|
212
|
+
await listingRef.set({
|
|
213
|
+
deletedAt: published ? null : firebaseAdmin.firestore.FieldValue.serverTimestamp(),
|
|
214
|
+
updatedAt: firebaseAdmin.firestore.FieldValue.serverTimestamp()
|
|
215
|
+
}, {
|
|
216
|
+
merge: true
|
|
217
|
+
});
|
|
218
|
+
await refreshListingQueryFields(listingRef);
|
|
219
|
+
return res.status(200).json({
|
|
220
|
+
ok: true,
|
|
221
|
+
published
|
|
222
|
+
});
|
|
223
|
+
} catch (error) {
|
|
224
|
+
console.error(error);
|
|
225
|
+
return res.status(500).json({
|
|
226
|
+
error: 'Publishing change failed'
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
};
|
|
168
230
|
export const publishPluginHandler = async (req, res)=>{
|
|
169
231
|
var _req_body, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _headers_authorization;
|
|
170
|
-
var _req_body1, _req_body2;
|
|
232
|
+
var _req_body1, _req_body2, _req_body3;
|
|
171
233
|
if (req.method !== 'POST') {
|
|
172
234
|
return res.status(405).json({
|
|
173
235
|
error: 'Method not allowed'
|
|
@@ -183,6 +245,10 @@ export const publishPluginHandler = async (req, res)=>{
|
|
|
183
245
|
if (((_req_body2 = req.body) == null ? void 0 : _req_body2.action) === 'set-visibility') {
|
|
184
246
|
return setListingVisibility(req, res);
|
|
185
247
|
}
|
|
248
|
+
// Unpublish ⇄ republish (AGL-3321), which was a client write.
|
|
249
|
+
if (((_req_body3 = req.body) == null ? void 0 : _req_body3.action) === 'set-published') {
|
|
250
|
+
return setListingPublished(req, res);
|
|
251
|
+
}
|
|
186
252
|
const body = (_req_body = req.body) != null ? _req_body : {};
|
|
187
253
|
const headers = req.headers;
|
|
188
254
|
const displayName = String((_ref = body == null ? void 0 : body.displayName) != null ? _ref : '').slice(0, 80);
|
|
@@ -228,7 +294,7 @@ export const publishPluginHandler = async (req, res)=>{
|
|
|
228
294
|
});
|
|
229
295
|
try {
|
|
230
296
|
var _ref6, _membership_orgId, _ref7, _ref8, _manifest_contributes;
|
|
231
|
-
var _manifest_capabilities,
|
|
297
|
+
var _manifest_capabilities, _req_body4, _contentVerdict_content;
|
|
232
298
|
const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
|
|
233
299
|
// Act on the org the client is in (AGL-868), not a guessed first-org — a
|
|
234
300
|
// member can belong to several, and the plugin publishes under one of them.
|
|
@@ -382,7 +448,7 @@ export const publishPluginHandler = async (req, res)=>{
|
|
|
382
448
|
profileId: publisher.orgId,
|
|
383
449
|
pluginId: manifest.id,
|
|
384
450
|
displayName: displayName.trim()
|
|
385
|
-
}, description.trim() && {
|
|
451
|
+
}, displayNameSearchFields(displayName.trim()), description.trim() && {
|
|
386
452
|
description: description.trim()
|
|
387
453
|
}, category.trim() && {
|
|
388
454
|
category: category.trim()
|
|
@@ -405,12 +471,14 @@ export const publishPluginHandler = async (req, res)=>{
|
|
|
405
471
|
createdAt: now,
|
|
406
472
|
reviewStatus: 'submitted'
|
|
407
473
|
}, existing.empty && {
|
|
408
|
-
visibility: ((
|
|
474
|
+
visibility: ((_req_body4 = req.body) == null ? void 0 : _req_body4.visibility) === 'private' ? 'private' : 'public'
|
|
409
475
|
}, {
|
|
410
476
|
updatedAt: now
|
|
411
477
|
}), {
|
|
412
478
|
merge: true
|
|
413
479
|
});
|
|
480
|
+
// The lists this listing appears in query by fields derived from it (AGL-3321).
|
|
481
|
+
await refreshListingQueryFields(listingRef);
|
|
414
482
|
// Version snapshots are server-only; the loader reads sha256 + manifest
|
|
415
483
|
// to verify integrity and stamp CSP before executing.
|
|
416
484
|
await listingRef.collection('pluginVersions').doc(manifest.version).set(_extends({
|