@aglyn/plugins-forms 1.0.0-beta.285 → 1.0.0-beta.287
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aglyn/plugins-forms",
|
|
3
|
-
"version": "1.0.0-beta.
|
|
3
|
+
"version": "1.0.0-beta.287",
|
|
4
4
|
"license": "Apache-2.0",
|
|
5
5
|
"homepage": "https://aglyn.com",
|
|
6
6
|
"repository": {
|
|
@@ -25,19 +25,19 @@
|
|
|
25
25
|
"./package.json": "./package.json"
|
|
26
26
|
},
|
|
27
27
|
"dependencies": {
|
|
28
|
-
"@aglyn/aglyn": "1.0.0-beta.
|
|
29
|
-
"@aglyn/shared-data-enums": "1.0.0-beta.
|
|
30
|
-
"@aglyn/shared-data-mdi": "1.0.0-beta.
|
|
31
|
-
"@aglyn/shared-ui-jsx": "1.0.0-beta.
|
|
32
|
-
"@aglyn/shared-ui-jsx-forms": "1.0.0-beta.
|
|
33
|
-
"@aglyn/shared-ui-snackstack": "1.0.0-beta.
|
|
34
|
-
"@aglyn/shared-util-email": "1.0.0-beta.
|
|
35
|
-
"@aglyn/shared-util-http": "1.0.0-beta.
|
|
36
|
-
"@aglyn/shared-util-timestamp": "1.0.0-beta.
|
|
37
|
-
"@aglyn/shared-util-tools": "1.0.0-beta.
|
|
38
|
-
"@aglyn/tenant-data-admin": "1.0.0-beta.
|
|
39
|
-
"@aglyn/tenant-feature-instance": "1.0.0-beta.
|
|
40
|
-
"@aglyn/tenant-runtime": "1.0.0-beta.
|
|
28
|
+
"@aglyn/aglyn": "1.0.0-beta.287",
|
|
29
|
+
"@aglyn/shared-data-enums": "1.0.0-beta.287",
|
|
30
|
+
"@aglyn/shared-data-mdi": "1.0.0-beta.287",
|
|
31
|
+
"@aglyn/shared-ui-jsx": "1.0.0-beta.287",
|
|
32
|
+
"@aglyn/shared-ui-jsx-forms": "1.0.0-beta.287",
|
|
33
|
+
"@aglyn/shared-ui-snackstack": "1.0.0-beta.287",
|
|
34
|
+
"@aglyn/shared-util-email": "1.0.0-beta.287",
|
|
35
|
+
"@aglyn/shared-util-http": "1.0.0-beta.287",
|
|
36
|
+
"@aglyn/shared-util-timestamp": "1.0.0-beta.287",
|
|
37
|
+
"@aglyn/shared-util-tools": "1.0.0-beta.287",
|
|
38
|
+
"@aglyn/tenant-data-admin": "1.0.0-beta.287",
|
|
39
|
+
"@aglyn/tenant-feature-instance": "1.0.0-beta.287",
|
|
40
|
+
"@aglyn/tenant-runtime": "1.0.0-beta.287",
|
|
41
41
|
"@swc/helpers": "0.5.23"
|
|
42
42
|
},
|
|
43
43
|
"peerDependencies": {
|
|
@@ -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 { holdsSiteKey, siteKeyRefusal } from "@aglyn/aglyn/app-utils/host-permissions";
|
|
18
|
+
import { encodeStoredNodes, isHostPluginEnabled, pluginRequestFromWeb } from "@aglyn/aglyn/server";
|
|
18
19
|
import { emailUnverifiedResponse, firebaseAdmin, getOrgForHost, isImpersonationSession, logHostActivity } from "@aglyn/tenant-data-admin";
|
|
19
20
|
import { isRefusedIdToken } from "@aglyn/tenant-data-admin/server/id-token-refusal";
|
|
20
21
|
import { Timestamp } from "firebase-admin/firestore";
|
|
@@ -105,7 +106,7 @@ import { announceFormPublish } from "./form-publish-announce.js";
|
|
|
105
106
|
});
|
|
106
107
|
}
|
|
107
108
|
try {
|
|
108
|
-
var
|
|
109
|
+
var _ref3;
|
|
109
110
|
const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken);
|
|
110
111
|
if (!decoded.email_verified && !isImpersonationSession(decoded)) {
|
|
111
112
|
return emailUnverifiedResponse();
|
|
@@ -126,10 +127,9 @@ import { announceFormPublish } from "./form-publish-announce.js";
|
|
|
126
127
|
// the version-create route next door uses: creating a draft version
|
|
127
128
|
// changes nothing a visitor sees, and moving the pointer is the act that
|
|
128
129
|
// does.
|
|
129
|
-
|
|
130
|
-
if (!hostRoleCanPublish(memberRole)) {
|
|
130
|
+
if (!holdsSiteKey(hostSnapshot, decoded.uid, 'site.publish')) {
|
|
131
131
|
return Response.json({
|
|
132
|
-
error: '
|
|
132
|
+
error: siteKeyRefusal('site.publish')
|
|
133
133
|
}, {
|
|
134
134
|
status: 403
|
|
135
135
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/server/form-promote-route.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 encodeStoredNodes,\n hostRoleCanPublish,\n isHostPluginEnabled,\n pluginRequestFromWeb,\n type PluginWebApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n getOrgForHost,\n isImpersonationSession,\n logHostActivity,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { Timestamp } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { isFormPromotionRefusal, resolveFormPromotion } from './form-promotion'\nimport { announceFormPublish } from './form-publish-announce'\n\n/**\n * PROMOTING A FORM: make one version the one the site serves.\n *\n * ## What promotion means, and why a form cannot borrow the component answer\n *\n * A reusable component's parent document IS the published copy — the tenant\n * reads every component's tree in one collection query on each render, which\n * is what keeps composing a page to a single read — so promoting a component\n * is a copy of the version's tree onto the parent plus a move of the\n * `versionId` pointer. A form is stored the same way for the same reason, so\n * the mechanics look identical: copy `nodes`, carry `rootId`, move the\n * pointer.\n *\n * They are not identical, and the difference is the whole reason this is a\n * server route rather than one more `updateDoc` in a card. A component is only\n * ever DRAWN: the worst a bad promotion does is make a page ugly, and the page\n * still renders. A form is drawn AND it is a contract — `/api/forms/submit`\n * keys submissions on the id the form node carries, reads marketing consent\n * out of a field the document NAMES, and creates a lead from an address it\n * expects to find. Every one of those couplings is resolved by NAME at submit\n * time, so a design can break them, and breaking them is silent in every\n * case: the form still renders, the visitor still submits, the row still\n * lands, and the thing the merchant believed they were collecting is not\n * there.\n *\n * So promotion RUNS `checkFormContract` against the tree it is about to write,\n * and a violation refuses the write with the violations in the body. The\n * besigner's own Save & publish runs the same check for the same reason; this\n * route exists because promotion must also be reachable from the form's page,\n * where an author picks a version out of history and never opens the canvas\n * at all — and a second promotion path that skipped the check would make the\n * check optional.\n *\n * ## Why the check runs HERE and not only in the browser\n *\n * The rules can express \"only a publisher may move `versionId`\". They cannot\n * express \"and only if the tree you are moving it to still names its own\n * fields\", because that is a walk of a compressed node map. A console-side\n * check is advice; this is the enforcement, and it is the reason the route\n * reads the version document itself rather than accepting a tree from the\n * caller. Nothing about the design crosses the wire inbound — a client that\n * could send its own `nodes` could send a tree that passes the check and\n * publish a different one.\n *\n * `POST /api/forms/promote`, served by the console's plugin API dispatcher,\n * which has already refused an unverified account, a locked-down site or\n * organization and a site that switched Forms off before this runs. It is the\n * route `plugins.config.json` names as a form's `besignerDocuments` publish,\n * so the besigner's Save & publish and the form page's version history reach\n * the same check.\n *\n * Body: `{ hostId, formId, versionId }`.\n * 422 with `{ violations }` when the contract would break; the shape is the\n * pure module's own, so the console renders the same sentences the besigner\n * does without either side parsing prose.\n */\nexport const formPromoteHandler: PluginWebApiHandler = async (request) => {\n const { method, body, headers: rawHeaders } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n\n const hostId = String(body?.hostId ?? '')\n const formId = String(body?.formId ?? '')\n const versionId = String(body?.versionId ?? '')\n if (!hostId || !formId || !versionId) {\n return Response.json(\n { error: 'Missing hostId, formId or versionId' },\n { status: 400 },\n )\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\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 Response.json({ error: 'Unknown site' }, { status: 404 })\n }\n // PUBLISH, not write. The `author` role edits content and may not make it\n // live — the same line the rules draw at `canPublishHostContent`, and the\n // reason this is `hostRoleCanPublish` rather than the `hostRoleCanWrite`\n // the version-create route next door uses: creating a draft version\n // changes nothing a visitor sees, and moving the pointer is the act that\n // does.\n const memberRole = (hostSnapshot.get('memberRoles') ?? {})[decoded.uid]\n if (!hostRoleCanPublish(memberRole)) {\n return Response.json(\n { error: 'Publishing requires the editor or admin role' },\n { status: 403 },\n )\n }\n\n const ownerOrg = await getOrgForHost(hostId)\n const org = (ownerOrg?.org ?? {}) as { enabledPlugins?: string[] }\n\n const formRef = hostRef.collection('forms').doc(formId)\n const [formSnapshot, versionSnapshot] = await Promise.all([\n formRef.get(),\n formRef.collection('versions').doc(versionId).get(),\n ])\n if (!formSnapshot.exists) {\n return Response.json({ error: 'Unknown form' }, { status: 404 })\n }\n if (!versionSnapshot.exists) {\n return Response.json({ error: 'Unknown version' }, { status: 404 })\n }\n\n /*\n * THE CHECK, BEFORE THE WRITE — and it is the same decision the besigner's\n * publish makes, in one shared module, so the two promotion paths cannot\n * disagree about which designs may ship.\n */\n const resolved = resolveFormPromotion({\n formId,\n form: formSnapshot.data() as Record<string, unknown>,\n storedNodes: versionSnapshot.get('nodes'),\n // The site's own plugin set (AGL-3029): a site that switched Forms off\n // does not draw a form or accept its submissions, so none goes live.\n formsOnForSite: isHostPluginEnabled(org, hostSnapshot.data(), BUNDLE_ID),\n })\n if (isFormPromotionRefusal(resolved)) {\n return Response.json(resolved.body, { status: resolved.status })\n }\n\n await formRef.update({\n // Compressed at rest (AGL-1151). `resolveFormPromotion` hands back the\n // DECODED tree because the contract check has to walk it; the storage\n // form is decided here, at the write, and matches what the besigner's\n // own publish writes to this same document.\n nodes: Buffer.from(encodeStoredNodes(resolved.nodes)!),\n ...(resolved.rootId ? { rootId: resolved.rootId } : {}),\n fields: resolved.fields,\n versionId,\n updatedAt: Timestamp.now(),\n })\n /*\n * The pages that place this form are now serving fields it no longer has.\n *\n * Fired without awaiting, exactly as the component publish path does: the\n * write above already succeeded, the scan reads every screen, layout and\n * component on the site, and nobody is watching one URL for a form publish\n * the way they watch a page after publishing it. `announceFormPublish`\n * absorbs its own failures — the render cache's TTL is the backstop.\n */\n void announceFormPublish({ firestore, hostId, formId })\n // A form files under `content`: `HostActivityTarget['type']` is a\n // PERSISTED value `activity-presenter.ts` branches on, and a member no\n // presenter knows renders as an unlinked row.\n await logHostActivity(\n hostId,\n { uid: decoded.uid, email: decoded.email ? String(decoded.email) : null },\n 'Published a version of the form',\n {\n type: 'content',\n id: formId,\n versionId,\n ...(formSnapshot.get('displayName')\n ? { name: String(formSnapshot.get('displayName')) }\n : {}),\n },\n )\n return Response.json({ ok: true, versionId }, { status: 200 })\n } catch (error) {\n // A refused credential is a 401, not a fault of ours (AGL-1993); anything\n // else keeps the answer below.\n if (isRefusedIdToken(error)) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n console.error('[forms] publish failed', error)\n return Response.json({ error: 'Publish failed' }, { status: 500 })\n }\n}\n"],"names":["encodeStoredNodes","hostRoleCanPublish","isHostPluginEnabled","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","getOrgForHost","isImpersonationSession","logHostActivity","isRefusedIdToken","Timestamp","BUNDLE_ID","isFormPromotionRefusal","resolveFormPromotion","announceFormPublish","formPromoteHandler","request","headers","method","body","rawHeaders","Response","json","error","status","authorization","idToken","startsWith","slice","length","undefined","hostId","String","formId","versionId","hostSnapshot","decoded","app","auth","verifyIdToken","email_verified","firestore","hostRef","collection","doc","get","exists","memberRole","uid","ownerOrg","org","formRef","formSnapshot","versionSnapshot","Promise","all","resolved","form","data","storedNodes","formsOnForSite","update","nodes","Buffer","from","rootId","fields","updatedAt","now","email","type","id","name","ok","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,iBAAiB,EACjBC,kBAAkB,EAClBC,mBAAmB,EACnBC,oBAAoB,QAEf,sBAAqB;AAC5B,SACEC,uBAAuB,EACvBC,aAAa,EACbC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,QACV,2BAA0B;AACjC,SAASC,gBAAgB,QAAQ,mDAAkD;AACnF,SAASC,SAAS,QAAQ,2BAA0B;AACpD,SAASC,SAAS,QAAQ,gCAA4B;AACtD,SAASC,sBAAsB,EAAEC,oBAAoB,QAAQ,sBAAkB;AAC/E,SAASC,mBAAmB,QAAQ,6BAAyB;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAuDC,GACD,OAAO,MAAMC,qBAA0C,OAAOC;QAMtCC;IALtB,MAAM,EAAEC,MAAM,EAAEC,IAAI,EAAEF,SAASG,UAAU,EAAE,GAAG,MAAMjB,qBAAqBa;IACzE,MAAMC,UAAUG;IAChB,IAAIF,WAAW,QAAQ;QACrB,OAAOG,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAqB,GAA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C;YACrDC,QAAQV,SAASU,MAAM;YACvBhC;YACAiC,WAAWzD,UAAU0D,GAAG;;QAE1B;;;;;;;;KAQC,GACD,KAAKtD,oBAAoB;YAAE2B;YAAWV;YAAQE;QAAO;QACrD,kEAAkE;QAClE,uEAAuE;QACvE,8CAA8C;QAC9C,MAAMzB,gBACJuB,QACA;YAAEiB,KAAKZ,QAAQY,GAAG;YAAEqB,OAAOjC,QAAQiC,KAAK,GAAGrC,OAAOI,QAAQiC,KAAK,IAAI;QAAK,GACxE,mCACA;YACEC,MAAM;YACNC,IAAItC;YACJC;WACIkB,aAAaP,GAAG,CAAC,iBACjB;YAAE2B,MAAMxC,OAAOoB,aAAaP,GAAG,CAAC;QAAgB,IAChD,CAAC;QAGT,OAAOxB,SAASC,IAAI,CAAC;YAAEmD,IAAI;YAAMvC;QAAU,GAAG;YAAEV,QAAQ;QAAI;IAC9D,EAAE,OAAOD,OAAO;QACd,0EAA0E;QAC1E,+BAA+B;QAC/B,IAAId,iBAAiBc,QAAQ;YAC3B,OAAOF,SAASC,IAAI,CAAC;gBAAEC,OAAO;YAAkB,GAAG;gBAAEC,QAAQ;YAAI;QACnE;QACAkD,QAAQnD,KAAK,CAAC,0BAA0BA;QACxC,OAAOF,SAASC,IAAI,CAAC;YAAEC,OAAO;QAAiB,GAAG;YAAEC,QAAQ;QAAI;IAClE;AACF,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/forms/src/lib/server/form-promote-route.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 { holdsSiteKey, siteKeyRefusal } from '@aglyn/aglyn/app-utils/host-permissions'\nimport {\n encodeStoredNodes,\n isHostPluginEnabled,\n pluginRequestFromWeb,\n type PluginWebApiHandler,\n} from '@aglyn/aglyn/server'\nimport {\n emailUnverifiedResponse,\n firebaseAdmin,\n getOrgForHost,\n isImpersonationSession,\n logHostActivity,\n} from '@aglyn/tenant-data-admin'\nimport { isRefusedIdToken } from '@aglyn/tenant-data-admin/server/id-token-refusal'\nimport { Timestamp } from 'firebase-admin/firestore'\nimport { BUNDLE_ID } from '../constants/bundle-common'\nimport { isFormPromotionRefusal, resolveFormPromotion } from './form-promotion'\nimport { announceFormPublish } from './form-publish-announce'\n\n/**\n * PROMOTING A FORM: make one version the one the site serves.\n *\n * ## What promotion means, and why a form cannot borrow the component answer\n *\n * A reusable component's parent document IS the published copy — the tenant\n * reads every component's tree in one collection query on each render, which\n * is what keeps composing a page to a single read — so promoting a component\n * is a copy of the version's tree onto the parent plus a move of the\n * `versionId` pointer. A form is stored the same way for the same reason, so\n * the mechanics look identical: copy `nodes`, carry `rootId`, move the\n * pointer.\n *\n * They are not identical, and the difference is the whole reason this is a\n * server route rather than one more `updateDoc` in a card. A component is only\n * ever DRAWN: the worst a bad promotion does is make a page ugly, and the page\n * still renders. A form is drawn AND it is a contract — `/api/forms/submit`\n * keys submissions on the id the form node carries, reads marketing consent\n * out of a field the document NAMES, and creates a lead from an address it\n * expects to find. Every one of those couplings is resolved by NAME at submit\n * time, so a design can break them, and breaking them is silent in every\n * case: the form still renders, the visitor still submits, the row still\n * lands, and the thing the merchant believed they were collecting is not\n * there.\n *\n * So promotion RUNS `checkFormContract` against the tree it is about to write,\n * and a violation refuses the write with the violations in the body. The\n * besigner's own Save & publish runs the same check for the same reason; this\n * route exists because promotion must also be reachable from the form's page,\n * where an author picks a version out of history and never opens the canvas\n * at all — and a second promotion path that skipped the check would make the\n * check optional.\n *\n * ## Why the check runs HERE and not only in the browser\n *\n * The rules can express \"only a publisher may move `versionId`\". They cannot\n * express \"and only if the tree you are moving it to still names its own\n * fields\", because that is a walk of a compressed node map. A console-side\n * check is advice; this is the enforcement, and it is the reason the route\n * reads the version document itself rather than accepting a tree from the\n * caller. Nothing about the design crosses the wire inbound — a client that\n * could send its own `nodes` could send a tree that passes the check and\n * publish a different one.\n *\n * `POST /api/forms/promote`, served by the console's plugin API dispatcher,\n * which has already refused an unverified account, a locked-down site or\n * organization and a site that switched Forms off before this runs. It is the\n * route `plugins.config.json` names as a form's `besignerDocuments` publish,\n * so the besigner's Save & publish and the form page's version history reach\n * the same check.\n *\n * Body: `{ hostId, formId, versionId }`.\n * 422 with `{ violations }` when the contract would break; the shape is the\n * pure module's own, so the console renders the same sentences the besigner\n * does without either side parsing prose.\n */\nexport const formPromoteHandler: PluginWebApiHandler = async (request) => {\n const { method, body, headers: rawHeaders } = await pluginRequestFromWeb(request)\n const headers = rawHeaders as Partial<Record<string, string>>\n if (method !== 'POST') {\n return Response.json({ error: 'Method not allowed' }, { status: 405 })\n }\n const authorization = headers.authorization ?? ''\n const idToken = authorization.startsWith('Bearer ')\n ? authorization.slice('Bearer '.length)\n : undefined\n if (!idToken) return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n\n const hostId = String(body?.hostId ?? '')\n const formId = String(body?.formId ?? '')\n const versionId = String(body?.versionId ?? '')\n if (!hostId || !formId || !versionId) {\n return Response.json(\n { error: 'Missing hostId, formId or versionId' },\n { status: 400 },\n )\n }\n\n try {\n const decoded = await firebaseAdmin.app().auth().verifyIdToken(idToken)\n if (!decoded.email_verified && !isImpersonationSession(decoded)) {\n return emailUnverifiedResponse()\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 Response.json({ error: 'Unknown site' }, { status: 404 })\n }\n // PUBLISH, not write. The `author` role edits content and may not make it\n // live — the same line the rules draw at `canPublishHostContent`, and the\n // reason this is `hostRoleCanPublish` rather than the `hostRoleCanWrite`\n // the version-create route next door uses: creating a draft version\n // changes nothing a visitor sees, and moving the pointer is the act that\n // does.\n if (!holdsSiteKey(hostSnapshot, decoded.uid, 'site.publish')) {\n return Response.json(\n { error: siteKeyRefusal('site.publish') },\n { status: 403 },\n )\n }\n\n const ownerOrg = await getOrgForHost(hostId)\n const org = (ownerOrg?.org ?? {}) as { enabledPlugins?: string[] }\n\n const formRef = hostRef.collection('forms').doc(formId)\n const [formSnapshot, versionSnapshot] = await Promise.all([\n formRef.get(),\n formRef.collection('versions').doc(versionId).get(),\n ])\n if (!formSnapshot.exists) {\n return Response.json({ error: 'Unknown form' }, { status: 404 })\n }\n if (!versionSnapshot.exists) {\n return Response.json({ error: 'Unknown version' }, { status: 404 })\n }\n\n /*\n * THE CHECK, BEFORE THE WRITE — and it is the same decision the besigner's\n * publish makes, in one shared module, so the two promotion paths cannot\n * disagree about which designs may ship.\n */\n const resolved = resolveFormPromotion({\n formId,\n form: formSnapshot.data() as Record<string, unknown>,\n storedNodes: versionSnapshot.get('nodes'),\n // The site's own plugin set (AGL-3029): a site that switched Forms off\n // does not draw a form or accept its submissions, so none goes live.\n formsOnForSite: isHostPluginEnabled(org, hostSnapshot.data(), BUNDLE_ID),\n })\n if (isFormPromotionRefusal(resolved)) {\n return Response.json(resolved.body, { status: resolved.status })\n }\n\n await formRef.update({\n // Compressed at rest (AGL-1151). `resolveFormPromotion` hands back the\n // DECODED tree because the contract check has to walk it; the storage\n // form is decided here, at the write, and matches what the besigner's\n // own publish writes to this same document.\n nodes: Buffer.from(encodeStoredNodes(resolved.nodes)!),\n ...(resolved.rootId ? { rootId: resolved.rootId } : {}),\n fields: resolved.fields,\n versionId,\n updatedAt: Timestamp.now(),\n })\n /*\n * The pages that place this form are now serving fields it no longer has.\n *\n * Fired without awaiting, exactly as the component publish path does: the\n * write above already succeeded, the scan reads every screen, layout and\n * component on the site, and nobody is watching one URL for a form publish\n * the way they watch a page after publishing it. `announceFormPublish`\n * absorbs its own failures — the render cache's TTL is the backstop.\n */\n void announceFormPublish({ firestore, hostId, formId })\n // A form files under `content`: `HostActivityTarget['type']` is a\n // PERSISTED value `activity-presenter.ts` branches on, and a member no\n // presenter knows renders as an unlinked row.\n await logHostActivity(\n hostId,\n { uid: decoded.uid, email: decoded.email ? String(decoded.email) : null },\n 'Published a version of the form',\n {\n type: 'content',\n id: formId,\n versionId,\n ...(formSnapshot.get('displayName')\n ? { name: String(formSnapshot.get('displayName')) }\n : {}),\n },\n )\n return Response.json({ ok: true, versionId }, { status: 200 })\n } catch (error) {\n // A refused credential is a 401, not a fault of ours (AGL-1993); anything\n // else keeps the answer below.\n if (isRefusedIdToken(error)) {\n return Response.json({ error: 'Unauthenticated' }, { status: 401 })\n }\n console.error('[forms] publish failed', error)\n return Response.json({ error: 'Publish failed' }, { status: 500 })\n }\n}\n"],"names":["holdsSiteKey","siteKeyRefusal","encodeStoredNodes","isHostPluginEnabled","pluginRequestFromWeb","emailUnverifiedResponse","firebaseAdmin","getOrgForHost","isImpersonationSession","logHostActivity","isRefusedIdToken","Timestamp","BUNDLE_ID","isFormPromotionRefusal","resolveFormPromotion","announceFormPublish","formPromoteHandler","request","headers","method","body","rawHeaders","Response","json","error","status","authorization","idToken","startsWith","slice","length","undefined","hostId","String","formId","versionId","decoded","app","auth","verifyIdToken","email_verified","firestore","hostRef","collection","doc","hostSnapshot","get","exists","uid","ownerOrg","org","formRef","formSnapshot","versionSnapshot","Promise","all","resolved","form","data","storedNodes","formsOnForSite","update","nodes","Buffer","from","rootId","fields","updatedAt","now","email","type","id","name","ok","console"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,YAAY,EAAEC,cAAc,QAAQ,0CAAyC;AACtF,SACEC,iBAAiB,EACjBC,mBAAmB,EACnBC,oBAAoB,QAEf,sBAAqB;AAC5B,SACEC,uBAAuB,EACvBC,aAAa,EACbC,aAAa,EACbC,sBAAsB,EACtBC,eAAe,QACV,2BAA0B;AACjC,SAASC,gBAAgB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