@aglyn/plugins-workflows 1.17.0 → 1.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/org-automations-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n checkEntitlement,\n hostEventLabel,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport {\n hostIdsFromScope,\n isOrgWideScope,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n Chip,\n Menu,\n MenuItem,\n Stack,\n Switch,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n documentId,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n ORG_AUTOMATION_STEP_TYPES,\n ORG_AUTOMATION_TRIGGER_EVENTS,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n orgAutomationPausedHostIds,\n type OrgAutomationRow,\n readOrgAutomation,\n} from '../model/org-automations'\nimport {\n newOrgAutomationDraft,\n OrgAutomationEditor,\n orgAutomationBody,\n type OrgAutomationDraft,\n orgAutomationDraft,\n orgAutomationDraftFromProposal,\n} from './org-automation-editor.component'\nimport { ORG_AUTOMATIONS_ZONE, type OrgAutomationProposal } from './workflow-zones'\nimport { useOrgAutomationsApi } from './use-org-automations-api'\nimport { orgSiteName, type WorkflowsOrgMount } from './workflows-org-mount'\nimport { HOST_ACTION_STEP_LABELS, type HostActionStepType } from '../model/host-actions'\n\nexport interface OrgAutomationsCardProps {\n mount: WorkflowsOrgMount\n org?: Partial<AglynOrgBilling>\n /**\n * Whether the reader may write the organization's automations — an owner,\n * admin or editor. The route decides; this keeps a viewer from being\n * offered controls that are about to refuse them.\n */\n canEdit: boolean\n}\n\n/** The sites an automation runs on, by id: every org site for `['org']`. */\nfunction placedSiteIds(\n row: Pick<OrgAutomationRow, 'visibleTo'>,\n mount: WorkflowsOrgMount,\n): string[] {\n return isOrgWideScope(row.visibleTo)\n ? mount.hosts.map((host) => host.id)\n : hostIdsFromScope(row.visibleTo)\n}\n\n/** \"Runs on every site\" or \"Runs on Shop, Blog\". */\nfunction placementLine(\n row: Pick<OrgAutomationRow, 'visibleTo'>,\n mount: WorkflowsOrgMount,\n): string {\n if (isOrgWideScope(row.visibleTo)) return 'Runs on every site'\n const names = hostIdsFromScope(row.visibleTo).map((id) => orgSiteName(mount, id))\n return names.length ? `Runs on ${names.join(', ')}` : 'Runs on no site'\n}\n\n/**\n * THE ORGANIZATION'S AUTOMATIONS (AGL-3302): what the organization runs on\n * the sites it chooses.\n *\n * One ceilinged read of the live automations — the org hub admits only\n * org-wide members, who read every one — and every write through\n * `automations/manage` or `automations/pause`, because the collection is\n * closed to client writes. Each row says where it runs and where it is\n * paused; a paused site is resumed from its chip, and any placed site can be\n * paused from the row, which is the same control the site's own hub offers.\n */\nexport function OrgAutomationsCard(props: OrgAutomationsCardProps) {\n const { mount, org, canEdit } = props\n const firestore = useFirestore()\n const api = useOrgAutomationsApi()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n\n /*\n * Every LIVE automation, ceilinged at the organization's cap plus the probe\n * row. `deletedAt` is always written — `null` while live — so equality asks\n * for exactly the live ones and deleted documents never take a place in the\n * window. Ordered by document id, which the automatic single-field index\n * carries behind the equality, so the window is named rather than whatever\n * order Firestore returns; the list is sorted by name once it is in hand.\n */\n const { data: rows } = useFirestoreCollection<OrgAutomationRow>(\n () =>\n query(\n collection(firestore, 'orgs', mount.orgId, ORG_AUTOMATIONS_COLLECTION),\n where('deletedAt', '==', null),\n orderBy(documentId()),\n limit(ORG_AUTOMATIONS_MAX + 1),\n ),\n [firestore, mount.orgId],\n { idField: '$id' },\n )\n const automations = useMemo(\n () =>\n [...(rows ?? [])]\n .slice(0, ORG_AUTOMATIONS_MAX)\n .sort((a, b) => String(a.name ?? '').localeCompare(String(b.name ?? ''))),\n [rows],\n )\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const shown = useMemo(\n () => automations.slice(page * pageSize, page * pageSize + pageSize),\n [automations, page, pageSize],\n )\n\n const [draft, setDraft] = useState<OrgAutomationDraft | null>(null)\n /**\n * The editor has been opened at least once — the latch the pickers key on,\n * so Cancel and the next Edit do not buy the option lists twice.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n const [saving, setSaving] = useState(false)\n const [pauseMenu, setPauseMenu] = useState<{\n anchor: HTMLElement\n row: OrgAutomationRow\n } | null>(null)\n\n const entitled = checkEntitlement(org, 'actions')\n const fail = useCallback(\n (error: unknown) =>\n enqueueSnackbar((error as Error)?.message || 'The request could not be completed', {\n variant: 'warning',\n persist: false,\n }),\n [enqueueSnackbar],\n )\n\n const refuseUnentitled = useCallback(() => {\n enqueueSnackbar(\n 'Org automations are built from the actions builder, which requires a Pro plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }, [enqueueSnackbar])\n\n const handleAdd = useCallback(() => {\n if (!entitled) return refuseUnentitled()\n setDraft(newOrgAutomationDraft())\n }, [entitled, refuseUnentitled])\n\n /*\n * For the `orgAutomations` zone (AGL-3603): an automation another plugin\n * proposed opens in the editor as a new one, unsaved and switched off —\n * the same door Add org automation opens, so the plan is asked first and\n * Save is still the only write.\n */\n const propose = useCallback(\n (proposal: OrgAutomationProposal) => {\n if (!entitled) {\n refuseUnentitled()\n return false\n }\n const opened = orgAutomationDraftFromProposal(proposal)\n if (!opened) return false\n setDraft(opened)\n return true\n },\n [entitled, refuseUnentitled],\n )\n const ExtensionZone = useConsoleWidgetSlot()\n const automationsZone =\n ExtensionZone && canEdit ? (\n <ExtensionZone\n slot={ORG_AUTOMATIONS_ZONE.id}\n orgId={mount.orgId}\n triggers={ORG_AUTOMATION_TRIGGER_EVENTS}\n steps={ORG_AUTOMATION_STEP_TYPES}\n propose={propose}\n />\n ) : null\n\n const handleSave = useCallback(async () => {\n if (!draft) return\n const body = orgAutomationBody(draft)\n // The route's own reader, asked first so a mistake reads the same here as\n // it would coming back from the server — and costs no round trip.\n const read = readOrgAutomation(body)\n if (read.ok === false) {\n return void enqueueSnackbar(read.problem, { variant: 'warning', persist: false })\n }\n setSaving(true)\n try {\n await api('manage', {\n orgId: mount.orgId,\n action: draft.id ? 'update' : 'create',\n ...(draft.id ? { automationId: draft.id } : {}),\n automation: body,\n })\n setDraft(null)\n enqueueSnackbar('Org automation saved', { variant: 'success', persist: false })\n } catch (error) {\n fail(error)\n } finally {\n setSaving(false)\n }\n }, [draft, api, mount.orgId, enqueueSnackbar, fail])\n\n const handleToggle = useCallback(\n (row: OrgAutomationRow) => async (event: { target: { checked: boolean } }) => {\n try {\n await api('manage', {\n orgId: mount.orgId,\n action: 'setEnabled',\n automationId: row.$id,\n enabled: event.target.checked,\n })\n } catch (error) {\n fail(error)\n }\n },\n [api, mount.orgId, fail],\n )\n\n const handleDelete = useCallback(\n (row: OrgAutomationRow) => async () => {\n const confirmed = await confirm({\n title: 'Delete this org automation?',\n description:\n `\"${row.name}\" stops running on every site it is placed on, and ` +\n 'anyone waiting inside it stops too.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n try {\n await api('manage', {\n orgId: mount.orgId,\n action: 'delete',\n automationId: row.$id,\n })\n } catch (error) {\n fail(error)\n }\n },\n [confirm, api, mount.orgId, fail],\n )\n\n const setPaused = useCallback(\n async (row: OrgAutomationRow, hostId: string, paused: boolean) => {\n setPauseMenu(null)\n try {\n await api('pause', { hostId, automationId: row.$id, paused })\n } catch (error) {\n fail(error)\n }\n },\n [api, fail],\n )\n\n return (\n <CardDisplay\n header={'Org automations'}\n help={pluginDocsHelp('orgAutomations', { anchor: '#what-an-org-automation-is' })}\n // Other ways to start an org automation (AGL-3603), in the header.\n actions={automationsZone ?? undefined}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Write an automation once and run it on every site you choose. ' +\n 'Each run is that site’s own: its email goes from that site, it ' +\n 'counts on that site’s action runs, and the site can pause it ' +\n 'for itself. Pro plans and up.'}\n </Typography>\n {shown.map((row) => {\n const paused = orgAutomationPausedHostIds(row)\n const placed = placedSiteIds(row, mount)\n const pausable = placed.filter((hostId) => !paused.includes(hostId))\n return (\n <Stack\n key={row.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Switch\n size=\"small\"\n checked={row.enabled !== false}\n disabled={!canEdit}\n onChange={handleToggle(row)}\n slotProps={{ input: { 'aria-label': `Switch ${row.name} on or off` } }}\n />\n <Stack sx={{ flex: 1, minWidth: 0 }} spacing={0.25}>\n <Typography variant=\"body2\" noWrap>\n {row.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[\n `on ${hostEventLabel(row.trigger?.event)}`,\n (row.steps ?? [])\n .map(\n (step) =>\n HOST_ACTION_STEP_LABELS[step.type as HostActionStepType] ??\n step.type,\n )\n .filter(Boolean)\n .join(' → '),\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {placementLine(row, mount)}\n </Typography>\n {paused.length ? (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap', gap: 0.5 }}>\n {paused.map((hostId) => (\n <Chip\n key={hostId}\n size=\"small\"\n variant=\"outlined\"\n color=\"warning\"\n label={`Paused on ${orgSiteName(mount, hostId)}`}\n {...(canEdit\n ? { onDelete: () => void setPaused(row, hostId, false) }\n : {})}\n />\n ))}\n </Stack>\n ) : null}\n </Stack>\n {canEdit ? (\n <>\n <Button size=\"small\" onClick={() => setDraft(orgAutomationDraft(row))}>\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n disabled={!pausable.length}\n aria-haspopup=\"menu\"\n onClick={(event) =>\n setPauseMenu({ anchor: event.currentTarget, row })\n }\n >\n {'Pause on…'}\n </Button>\n <Button size=\"small\" color=\"error\" onClick={handleDelete(row)}>\n {'Delete'}\n </Button>\n </>\n ) : null}\n </Stack>\n )\n })}\n {automations.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No org automations yet.'}\n </Typography>\n ) : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={shown.length}\n count={automations.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {(rows?.length ?? 0) > ORG_AUTOMATIONS_MAX ? (\n <Alert severity=\"info\">\n {`Showing ${ORG_AUTOMATIONS_MAX} org automations, the most an ` +\n 'organization holds.'}\n </Alert>\n ) : null}\n {canEdit ? (\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add org automation'}\n </Button>\n ) : null}\n </Stack>\n <Menu\n anchorEl={pauseMenu?.anchor ?? null}\n open={Boolean(pauseMenu)}\n onClose={() => setPauseMenu(null)}\n >\n {pauseMenu\n ? placedSiteIds(pauseMenu.row, mount)\n .filter(\n (hostId) =>\n !orgAutomationPausedHostIds(pauseMenu.row).includes(hostId),\n )\n .map((hostId) => (\n <MenuItem\n key={hostId}\n onClick={() => void setPaused(pauseMenu.row, hostId, true)}\n >\n {`Pause on ${orgSiteName(mount, hostId)}`}\n </MenuItem>\n ))\n : null}\n </Menu>\n <OrgAutomationEditor\n mount={mount}\n draft={draft}\n onDraft={(update) =>\n setDraft((previous) => (previous ? update(previous) : previous))\n }\n opened={editorOpened}\n saving={saving}\n onSave={() => void handleSave()}\n onClose={() => setDraft(null)}\n />\n </CardDisplay>\n )\n}\nOrgAutomationsCard.displayName = 'OrgAutomationsCard'\n\nexport default OrgAutomationsCard\n"],"names":["checkEntitlement","hostEventLabel","pluginDocsHelp","hostIdsFromScope","isOrgWideScope","useConsoleWidgetSlot","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","useSnackbar","useFirestore","useFirestoreCollection","Alert","Button","Chip","Menu","MenuItem","Stack","Switch","Typography","collection","documentId","limit","orderBy","query","where","useCallback","useMemo","useState","ORG_AUTOMATION_STEP_TYPES","ORG_AUTOMATION_TRIGGER_EVENTS","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","orgAutomationPausedHostIds","readOrgAutomation","newOrgAutomationDraft","OrgAutomationEditor","orgAutomationBody","orgAutomationDraft","orgAutomationDraftFromProposal","ORG_AUTOMATIONS_ZONE","useOrgAutomationsApi","orgSiteName","HOST_ACTION_STEP_LABELS","placedSiteIds","row","mount","visibleTo","hosts","map","host","id","placementLine","names","length","join","OrgAutomationsCard","props","org","canEdit","firestore","api","enqueueSnackbar","confirm","data","rows","orgId","idField","automations","slice","sort","a","b","String","name","localeCompare","page","setPage","pageSize","setPageSize","shown","draft","setDraft","editorOpened","setEditorOpened","saving","setSaving","pauseMenu","setPauseMenu","entitled","fail","error","message","variant","persist","refuseUnentitled","handleAdd","propose","proposal","opened","ExtensionZone","automationsZone","slot","triggers","steps","handleSave","body","read","ok","problem","action","automationId","automation","handleToggle","event","$id","enabled","target","checked","handleDelete","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","setPaused","hostId","paused","header","help","anchor","actions","undefined","contentGutterX","contentGutterY","spacing","placed","pausable","filter","includes","direction","sx","alignItems","size","disabled","onChange","slotProps","input","flex","minWidth","noWrap","trigger","step","type","Boolean","useFlexGap","flexWrap","gap","label","onDelete","onClick","aria-haspopup","currentTarget","rowCount","count","onPageChange","onPageSizeChange","severity","alignSelf","anchorEl","open","onClose","onDraft","update","previous","onSave","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,gBAAgB,EAChBC,cAAc,EACdC,cAAc,QACT,eAAc;AACrB,SACEC,gBAAgB,EAChBC,cAAc,QACT,sCAAqC;AAC5C,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC,SACEC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,IAAI,EACJC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,KAAK,QACA,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SACEC,yBAAyB,EACzBC,6BAA6B,EAC7BC,0BAA0B,EAC1BC,mBAAmB,EACnBC,0BAA0B,EAE1BC,iBAAiB,QACZ,8BAA0B;AACjC,S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MAAM,oBAAI;gBAC/BwC,MAAMhB,QAAQtE;gBACduF,SAAS,IAAMtF,aAAa;0BAE3BD,YACG3C,cAAc2C,UAAU1C,GAAG,EAAEC,OAC1B+F,MAAM,CACL,CAACZ,SACC,CAAChG,2BAA2BsD,UAAU1C,GAAG,EAAEiG,QAAQ,CAACb,SAEvDhF,GAAG,CAAC,CAACgF,uBACJ,KAACjH;wBAECmJ,SAAS,IAAM,KAAKnC,UAAUzC,UAAU1C,GAAG,EAAEoF,QAAQ;kCAEpD,CAAC,SAAS,EAAEvF,YAAYI,OAAOmF,SAAS;uBAHpCA,WAMX;;0BAEN,KAAC7F;gBACCU,OAAOA;gBACPmC,OAAOA;gBACP8F,SAAS,CAACC,SACR9F,SAAS,CAAC+F,WAAcA,WAAWD,OAAOC,YAAYA;gBAExD9E,QAAQhB;gBACRE,QAAQA;gBACR6F,QAAQ,IAAM,KAAKzE;gBACnBqE,SAAS,IAAM5F,SAAS;;;;AAIhC;AACA1B,mBAAmB2H,WAAW,GAAG;AAEjC,eAAe3H,mBAAkB"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/org-automations-card.component.tsx"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport {\n type AglynOrgBilling,\n checkEntitlement,\n hostEventLabel,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\nimport {\n hostIdsFromScope,\n isOrgWideScope,\n scopeSharingOf,\n} from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport { CardDisplay, useConfirmationContext } from '@aglyn/shared-ui-jsx'\nimport { ListPagination } from '@aglyn/shared-ui-jsx/components/list-pagination.component'\nimport { TABLE_PAGE_SIZE_DEFAULT } from '@aglyn/shared-ui-jsx/const/table-pagination'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport {\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\nimport {\n Alert,\n Button,\n Chip,\n Menu,\n MenuItem,\n Stack,\n Switch,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n documentId,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { useCallback, useMemo, useState } from 'react'\nimport {\n ORG_AUTOMATION_STEP_TYPES,\n ORG_AUTOMATION_TRIGGER_EVENTS,\n ORG_AUTOMATIONS_COLLECTION,\n ORG_AUTOMATIONS_MAX,\n orgAutomationPausedHostIds,\n type OrgAutomationRow,\n readOrgAutomation,\n} from '../model/org-automations'\nimport {\n draftSharing,\n newOrgAutomationDraft,\n OrgAutomationEditor,\n orgAutomationBody,\n type OrgAutomationDraft,\n orgAutomationDraft,\n orgAutomationDraftFromProposal,\n} from './org-automation-editor.component'\nimport { ORG_AUTOMATIONS_ZONE, type OrgAutomationProposal } from './workflow-zones'\nimport { useOrgAutomationsApi } from './use-org-automations-api'\nimport { orgSiteName, type WorkflowsOrgMount } from './workflows-org-mount'\nimport { HOST_ACTION_STEP_LABELS, type HostActionStepType } from '../model/host-actions'\n\nexport interface OrgAutomationsCardProps {\n mount: WorkflowsOrgMount\n org?: Partial<AglynOrgBilling>\n /**\n * Whether the reader may write the organization's automations — an owner,\n * admin or editor. The route decides; this keeps a viewer from being\n * offered controls that are about to refuse them.\n */\n canEdit: boolean\n}\n\n/** The sites an automation runs on, by id: every org site for `['org']`. */\nfunction placedSiteIds(\n row: Pick<OrgAutomationRow, 'visibleTo'>,\n mount: WorkflowsOrgMount,\n): string[] {\n return isOrgWideScope(row.visibleTo)\n ? mount.hosts.map((host) => host.id)\n : hostIdsFromScope(row.visibleTo)\n}\n\n/**\n * \"Runs on every site\", \"Runs on Shop, Blog\" or, for one that runs on all\n * sites except some (AGL-4047), \"Runs on every site except Blog\".\n */\nfunction placementLine(\n row: Pick<OrgAutomationRow, 'visibleTo' | 'scopeMode' | 'scopeExcept'>,\n mount: WorkflowsOrgMount,\n): string {\n const sharing = scopeSharingOf(row as Record<string, unknown>)\n if (sharing.mode === 'all') return 'Runs on every site'\n if (sharing.mode === 'allExcept') {\n if (!sharing.includedHostIds.length) return 'Runs on no site'\n const leftOut = sharing.exceptHostIds.map((id) => orgSiteName(mount, id))\n return `Runs on every site except ${leftOut.join(', ')}`\n }\n const names = hostIdsFromScope(row.visibleTo).map((id) => orgSiteName(mount, id))\n return names.length ? `Runs on ${names.join(', ')}` : 'Runs on no site'\n}\n\n/**\n * THE ORGANIZATION'S AUTOMATIONS (AGL-3302): what the organization runs on\n * the sites it chooses.\n *\n * One ceilinged read of the live automations — the org hub admits only\n * org-wide members, who read every one — and every write through\n * `automations/manage` or `automations/pause`, because the collection is\n * closed to client writes. Each row says where it runs and where it is\n * paused; a paused site is resumed from its chip, and any placed site can be\n * paused from the row, which is the same control the site's own hub offers.\n */\nexport function OrgAutomationsCard(props: OrgAutomationsCardProps) {\n const { mount, org, canEdit } = props\n const firestore = useFirestore()\n const api = useOrgAutomationsApi()\n const { enqueueSnackbar } = useSnackbar()\n const { confirm } = useConfirmationContext()\n\n /*\n * Every LIVE automation, ceilinged at the organization's cap plus the probe\n * row. `deletedAt` is always written — `null` while live — so equality asks\n * for exactly the live ones and deleted documents never take a place in the\n * window. Ordered by document id, which the automatic single-field index\n * carries behind the equality, so the window is named rather than whatever\n * order Firestore returns; the list is sorted by name once it is in hand.\n */\n const { data: rows } = useFirestoreCollection<OrgAutomationRow>(\n () =>\n query(\n collection(firestore, 'orgs', mount.orgId, ORG_AUTOMATIONS_COLLECTION),\n where('deletedAt', '==', null),\n orderBy(documentId()),\n limit(ORG_AUTOMATIONS_MAX + 1),\n ),\n [firestore, mount.orgId],\n { idField: '$id' },\n )\n const automations = useMemo(\n () =>\n [...(rows ?? [])]\n .slice(0, ORG_AUTOMATIONS_MAX)\n .sort((a, b) => String(a.name ?? '').localeCompare(String(b.name ?? ''))),\n [rows],\n )\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const shown = useMemo(\n () => automations.slice(page * pageSize, page * pageSize + pageSize),\n [automations, page, pageSize],\n )\n\n const [draft, setDraft] = useState<OrgAutomationDraft | null>(null)\n /**\n * The editor has been opened at least once — the latch the pickers key on,\n * so Cancel and the next Edit do not buy the option lists twice.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n const [saving, setSaving] = useState(false)\n const [pauseMenu, setPauseMenu] = useState<{\n anchor: HTMLElement\n row: OrgAutomationRow\n } | null>(null)\n\n const entitled = checkEntitlement(org, 'actions')\n const fail = useCallback(\n (error: unknown) =>\n enqueueSnackbar((error as Error)?.message || 'The request could not be completed', {\n variant: 'warning',\n persist: false,\n }),\n [enqueueSnackbar],\n )\n\n const refuseUnentitled = useCallback(() => {\n enqueueSnackbar(\n 'Org automations are built from the actions builder, which requires a Pro plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }, [enqueueSnackbar])\n\n const handleAdd = useCallback(() => {\n if (!entitled) return refuseUnentitled()\n setDraft(newOrgAutomationDraft())\n }, [entitled, refuseUnentitled])\n\n /*\n * For the `orgAutomations` zone (AGL-3603): an automation another plugin\n * proposed opens in the editor as a new one, unsaved and switched off —\n * the same door Add org automation opens, so the plan is asked first and\n * Save is still the only write.\n */\n const propose = useCallback(\n (proposal: OrgAutomationProposal) => {\n if (!entitled) {\n refuseUnentitled()\n return false\n }\n const opened = orgAutomationDraftFromProposal(proposal)\n if (!opened) return false\n setDraft(opened)\n return true\n },\n [entitled, refuseUnentitled],\n )\n const ExtensionZone = useConsoleWidgetSlot()\n const automationsZone =\n ExtensionZone && canEdit ? (\n <ExtensionZone\n slot={ORG_AUTOMATIONS_ZONE.id}\n orgId={mount.orgId}\n triggers={ORG_AUTOMATION_TRIGGER_EVENTS}\n steps={ORG_AUTOMATION_STEP_TYPES}\n propose={propose}\n />\n ) : null\n\n const handleSave = useCallback(async () => {\n if (!draft) return\n const body = orgAutomationBody(draft)\n // The route's own reader, asked first so a mistake reads the same here as\n // it would coming back from the server — and costs no round trip.\n const read = readOrgAutomation(body)\n if (read.ok === false) {\n return void enqueueSnackbar(read.problem, { variant: 'warning', persist: false })\n }\n // Where it runs, against the workspace's sites, as the route will ask it\n // (AGL-4047). Leaving sites out waits for the sites; the route asks again.\n const placement =\n draft.sharing.mode !== 'allExcept' || mount.hostsReady\n ? draftSharing(draft, mount.hosts.map((host) => host.id))\n : null\n if (placement?.problem) {\n return void enqueueSnackbar(placement.problem, { variant: 'warning', persist: false })\n }\n setSaving(true)\n try {\n await api('manage', {\n orgId: mount.orgId,\n action: draft.id ? 'update' : 'create',\n ...(draft.id ? { automationId: draft.id } : {}),\n automation: body,\n })\n setDraft(null)\n enqueueSnackbar('Org automation saved', { variant: 'success', persist: false })\n } catch (error) {\n fail(error)\n } finally {\n setSaving(false)\n }\n }, [draft, api, mount.orgId, mount.hosts, mount.hostsReady, enqueueSnackbar, fail])\n\n const handleToggle = useCallback(\n (row: OrgAutomationRow) => async (event: { target: { checked: boolean } }) => {\n try {\n await api('manage', {\n orgId: mount.orgId,\n action: 'setEnabled',\n automationId: row.$id,\n enabled: event.target.checked,\n })\n } catch (error) {\n fail(error)\n }\n },\n [api, mount.orgId, fail],\n )\n\n const handleDelete = useCallback(\n (row: OrgAutomationRow) => async () => {\n const confirmed = await confirm({\n title: 'Delete this org automation?',\n description:\n `\"${row.name}\" stops running on every site it is placed on, and ` +\n 'anyone waiting inside it stops too.',\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n try {\n await api('manage', {\n orgId: mount.orgId,\n action: 'delete',\n automationId: row.$id,\n })\n } catch (error) {\n fail(error)\n }\n },\n [confirm, api, mount.orgId, fail],\n )\n\n const setPaused = useCallback(\n async (row: OrgAutomationRow, hostId: string, paused: boolean) => {\n setPauseMenu(null)\n try {\n await api('pause', { hostId, automationId: row.$id, paused })\n } catch (error) {\n fail(error)\n }\n },\n [api, fail],\n )\n\n return (\n <CardDisplay\n header={'Org automations'}\n help={pluginDocsHelp('orgAutomations', { anchor: '#what-an-org-automation-is' })}\n // Other ways to start an org automation (AGL-3603), in the header.\n actions={automationsZone ?? undefined}\n contentGutterX\n contentGutterY\n >\n <Stack spacing={1}>\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Write an automation once and run it on every site you choose. ' +\n 'Each run is that site’s own: its email goes from that site, it ' +\n 'counts on that site’s action runs, and the site can pause it ' +\n 'for itself. Pro plans and up.'}\n </Typography>\n {shown.map((row) => {\n const paused = orgAutomationPausedHostIds(row)\n const placed = placedSiteIds(row, mount)\n const pausable = placed.filter((hostId) => !paused.includes(hostId))\n return (\n <Stack\n key={row.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Switch\n size=\"small\"\n checked={row.enabled !== false}\n disabled={!canEdit}\n onChange={handleToggle(row)}\n slotProps={{ input: { 'aria-label': `Switch ${row.name} on or off` } }}\n />\n <Stack sx={{ flex: 1, minWidth: 0 }} spacing={0.25}>\n <Typography variant=\"body2\" noWrap>\n {row.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {[\n `on ${hostEventLabel(row.trigger?.event)}`,\n (row.steps ?? [])\n .map(\n (step) =>\n HOST_ACTION_STEP_LABELS[step.type as HostActionStepType] ??\n step.type,\n )\n .filter(Boolean)\n .join(' → '),\n ]\n .filter(Boolean)\n .join(' · ')}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {placementLine(row, mount)}\n </Typography>\n {paused.length ? (\n <Stack useFlexGap direction=\"row\" spacing={0.5} sx={{ flexWrap: 'wrap', gap: 0.5 }}>\n {paused.map((hostId) => (\n <Chip\n key={hostId}\n size=\"small\"\n variant=\"outlined\"\n color=\"warning\"\n label={`Paused on ${orgSiteName(mount, hostId)}`}\n {...(canEdit\n ? { onDelete: () => void setPaused(row, hostId, false) }\n : {})}\n />\n ))}\n </Stack>\n ) : null}\n </Stack>\n {canEdit ? (\n <>\n <Button size=\"small\" onClick={() => setDraft(orgAutomationDraft(row))}>\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n disabled={!pausable.length}\n aria-haspopup=\"menu\"\n onClick={(event) =>\n setPauseMenu({ anchor: event.currentTarget, row })\n }\n >\n {'Pause on…'}\n </Button>\n <Button size=\"small\" color=\"error\" onClick={handleDelete(row)}>\n {'Delete'}\n </Button>\n </>\n ) : null}\n </Stack>\n )\n })}\n {automations.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'No org automations yet.'}\n </Typography>\n ) : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={shown.length}\n count={automations.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {(rows?.length ?? 0) > ORG_AUTOMATIONS_MAX ? (\n <Alert severity=\"info\">\n {`Showing ${ORG_AUTOMATIONS_MAX} org automations, the most an ` +\n 'organization holds.'}\n </Alert>\n ) : null}\n {canEdit ? (\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add org automation'}\n </Button>\n ) : null}\n </Stack>\n <Menu\n anchorEl={pauseMenu?.anchor ?? null}\n open={Boolean(pauseMenu)}\n onClose={() => setPauseMenu(null)}\n >\n {pauseMenu\n ? placedSiteIds(pauseMenu.row, mount)\n .filter(\n (hostId) =>\n !orgAutomationPausedHostIds(pauseMenu.row).includes(hostId),\n )\n .map((hostId) => (\n <MenuItem\n key={hostId}\n onClick={() => void setPaused(pauseMenu.row, hostId, true)}\n >\n {`Pause on ${orgSiteName(mount, hostId)}`}\n </MenuItem>\n ))\n : null}\n </Menu>\n <OrgAutomationEditor\n mount={mount}\n draft={draft}\n onDraft={(update) =>\n setDraft((previous) => (previous ? update(previous) : previous))\n }\n opened={editorOpened}\n saving={saving}\n onSave={() => void handleSave()}\n onClose={() => setDraft(null)}\n />\n </CardDisplay>\n )\n}\nOrgAutomationsCard.displayName = 'OrgAutomationsCard'\n\nexport default OrgAutomationsCard\n"],"names":["checkEntitlement","hostEventLabel","pluginDocsHelp","hostIdsFromScope","isOrgWideScope","scopeSharingOf","useConsoleWidgetSlot","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","useSnackbar","useFirestore","useFirestoreCollection","Alert","Button","Chip","Menu","MenuItem","Stack","Switch","Typography","collection","documentId","limit","orderBy","query","where","useCallback","useMemo","useState","ORG_AUTOMATION_STEP_TYPES","ORG_AUTOMATION_TRIGGER_EVENTS","ORG_AUTOMATIONS_COLLECTION","ORG_AUTOMATIONS_MAX","orgAutomationPausedHostIds","readOrgAutomation","draftSharing","newOrgAutomationDraft","OrgAutomationEditor","orgAutomationBody","orgAutomationDraft","orgAutomationDraftFromProposal","ORG_AUTOMATIONS_ZONE","useOrgAutomationsApi","orgSiteName","HOST_ACTION_STEP_LABELS","placedSiteIds","row","mount","visibleTo","hosts","map","host","id","placementLine","sharing","mode","includedHostIds","length","leftOut","exceptHostIds","join","names","OrgAutomationsCard","props","org","canEdit","firestore","api","enqueueSnackbar","confirm","data","rows","orgId","idField","automations","slice","sort","a","b","String","name","localeCompare","page","setPage","pageSize","setPageSize","shown","draft","setDraft","editorOpened","setEditorOpened","saving","setSaving","pauseMenu","setPauseMenu","entitled","fail","error","message","variant","persist","refuseUnentitled","handleAdd","propose","proposal","opened","ExtensionZone","automationsZone","slot","triggers","steps","handleSave","body","read","ok","problem","placement","hostsReady","action","automationId","automation","handleToggle","event","$id","enabled","target","checked","handleDelete","confirmed","title","description","confirmationText","confirmationButtonProps","color","then","catch","setPaused","hostId","paused","header","help","anchor","actions","undefined","contentGutterX","contentGutterY","spacing","placed","pausable","filter","includes","direction","sx","alignItems","size","disabled","onChange","slotProps","input","flex","minWidth","noWrap","trigger","step","type","Boolean","useFlexGap","flexWrap","gap","label","onDelete","onClick","aria-haspopup","currentTarget","rowCount","count","onPageChange","onPageSizeChange","severity","alignSelf","anchorEl","open","onClose","onDraft","update","previous","onSave","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;AAEA,SAEEA,gBAAgB,EAChBC,cAAc,EACdC,cAAc,QACT,eAAc;AACrB,SACEC,gBAAgB,EAChBC,cAAc,EACdC,cAAc,QACT,sCAAqC;AAC5C,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SACEC,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC,SACEC,KAAK,EACLC,MAAM,EACNC,IAAI,EACJC,IAAI,EACJC,QAAQ,EACRC,KAAK,EACLC,MAAM,EACNC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU,EACVC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,KAAK,QACA,qBAAoB;AAC3B,SAASC,WAAW,EAAEC,OAAO,EAAEC,QAAQ,QAAQ,QAAO;AACtD,SACEC,yBAAyB,EACzBC,6BAA6B,EAC7BC,0BAA0B,EAC1BC,mBAAmB,EACnBC,0BAA0B,EAE1BC,iBAAiB,QACZ,8BAA0B;AACjC,SACEC,YAAY,EACZC,qBAAqB,EACrBC,mBAAmB,EACnBC,iBAAiB,EAEjBC,kBAAkB,EAClBC,8BAA8B,QACzB,uCAAmC;AAC1C,SAASC,oBAAoB,QAAoC,sBAAkB;AACnF,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
8
  * every one of those sites can use. A dataset or a campaign shared with some
9
9
  * of the org's sites and not the others would resolve on one site and fail
10
10
  * the step on the next, so a record is offered only when its own sharing
11
- * covers the automation's placement (`scopeCovers`). A list belongs to the
12
- * whole organization and is always offered.
11
+ * covers the automation's placement (`sharingCovers`, which also holds for
12
+ * the sites all sites except some will reach later, AGL-4047). A list belongs
13
+ * to the whole organization and is always offered.
13
14
  *
14
15
  * The site-only pickers — workflows, overlays, webhooks — are empty: no step
15
16
  * an org automation may hold points at one.
@@ -17,4 +18,6 @@ import { type AutomationStepPickerData } from './use-automation-step-pickers';
17
18
  * Read on the same latch and at the same ceiling as the site editor's, and
18
19
  * paid only by an author who opens the editor.
19
20
  */
20
- export declare function useOrgAutomationStepPickers(orgId: string, editorOpened: boolean, placement: readonly string[]): AutomationStepPickerData;
21
+ export declare function useOrgAutomationStepPickers(orgId: string, editorOpened: boolean,
22
+ /** The automation as its placement would leave it: `visibleTo`, and the marker for all sites except some. */
23
+ placement: Readonly<Record<string, unknown>>): AutomationStepPickerData;
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */ 'use client';
17
- import { scopeCovers } from "@aglyn/aglyn/app-utils/scope-tokens";
17
+ import { sharingCovers } from "@aglyn/aglyn/app-utils/scope-tokens";
18
18
  import { pluginContainerKind } from "@aglyn/aglyn/plugin-manager/plugin-containers";
19
19
  import { pluginRecordListQuery, pluginRecordPickerLabels, pluginRecordsFromRows } from "@aglyn/aglyn/plugin-manager/plugin-record-lists";
20
20
  import { useFirestore, useFirestoreCollection } from "@aglyn/tenant-feature-instance";
@@ -47,15 +47,16 @@ import { EDITOR_OPTION_CEILING } from "./use-automation-step-pickers.js";
47
47
  * every one of those sites can use. A dataset or a campaign shared with some
48
48
  * of the org's sites and not the others would resolve on one site and fail
49
49
  * the step on the next, so a record is offered only when its own sharing
50
- * covers the automation's placement (`scopeCovers`). A list belongs to the
51
- * whole organization and is always offered.
50
+ * covers the automation's placement (`sharingCovers`, which also holds for
51
+ * the sites all sites except some will reach later, AGL-4047). A list belongs
52
+ * to the whole organization and is always offered.
52
53
  *
53
54
  * The site-only pickers — workflows, overlays, webhooks — are empty: no step
54
55
  * an org automation may hold points at one.
55
56
  *
56
57
  * Read on the same latch and at the same ceiling as the site editor's, and
57
58
  * paid only by an author who opens the editor.
58
- */ export function useOrgAutomationStepPickers(orgId, editorOpened, placement) {
59
+ */ export function useOrgAutomationStepPickers(orgId, editorOpened, /** The automation as its placement would leave it: `visibleTo`, and the marker for all sites except some. */ placement) {
59
60
  var _pluginContainerKind;
60
61
  const firestore = useFirestore();
61
62
  /*
@@ -94,12 +95,12 @@ import { EDITOR_OPTION_CEILING } from "./use-automation-step-pickers.js";
94
95
  });
95
96
  const { rows: campaignDocs, truncated: campaignsTruncated } = ceilingedWindow(campaignRead, EDITOR_OPTION_CEILING);
96
97
  const pickers = useMemo(()=>{
97
- const covers = (row)=>scopeCovers(row == null ? void 0 : row.visibleTo, placement);
98
+ const covers = (row)=>sharingCovers(row != null ? row : null, placement);
98
99
  return {
99
100
  workflowOptions: [],
100
101
  overlayOptions: [],
101
102
  webhookOptions: [],
102
- datasetOptions: datasetOptionsOf(pluginRecordsFromRows('dataset', datasetRows).filter((dataset)=>scopeCovers(dataset.facts['visibleTo'], placement))),
103
+ datasetOptions: datasetOptionsOf(pluginRecordsFromRows('dataset', datasetRows).filter((dataset)=>sharingCovers(dataset.facts, placement))),
103
104
  listOptions: (listDocs != null ? listDocs : []).filter((list)=>!list.deletedAt && list.name).map((list)=>({
104
105
  id: list.$id,
105
106
  name: list.name
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/use-org-automation-step-pickers.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { scopeCovers } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { pluginContainerKind } from '@aglyn/aglyn/plugin-manager/plugin-containers'\nimport {\n pluginRecordListQuery,\n pluginRecordPickerLabels,\n pluginRecordsFromRows,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport type { PluginIndexedRecord } from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport {\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\n/*\n * The MODULE, not the barrel, for the two pure helpers — the cards' specs\n * mock `@aglyn/tenant-feature-instance` wholesale, and a query builder\n * imported through that barrel disappears under the mock.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { collection } from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport type { AutomationStepPickers } from './automation-step-fields.component'\n\n/**\n * The datasets an org automation can write to, by name, each told apart from\n * another of its name by who it is shared with, as their owner says it\n * (AGL-4047).\n */\nfunction datasetOptionsOf(records: readonly PluginIndexedRecord[]) {\n const labels = pluginRecordPickerLabels('dataset', records)\n return records\n .map((dataset) => ({ id: dataset.id, name: dataset.name, label: labels[dataset.id] }))\n .sort((a, b) => a.name.localeCompare(b.name))\n}\nimport {\n type AutomationStepPickerData,\n EDITOR_OPTION_CEILING,\n} from './use-automation-step-pickers'\n\n/**\n * WHAT AN ORG AUTOMATION'S STEPS CAN BE POINTED AT (AGL-3302).\n *\n * The site editor's pickers read one site's records; an org automation runs\n * on every site it is placed on, so its pickers read the ORGANIZATION's —\n * the lists, the datasets and the campaign containers — and offer only what\n * every one of those sites can use. A dataset or a campaign shared with some\n * of the org's sites and not the others would resolve on one site and fail\n * the step on the next, so a record is offered only when its own sharing\n * covers the automation's placement (`scopeCovers`). A list belongs to the\n * whole organization and is always offered.\n *\n * The site-only pickers — workflows, overlays, webhooks — are empty: no step\n * an org automation may hold points at one.\n *\n * Read on the same latch and at the same ceiling as the site editor's, and\n * paid only by an author who opens the editor.\n */\nexport function useOrgAutomationStepPickers(\n orgId: string,\n editorOpened: boolean,\n placement: readonly string[],\n): AutomationStepPickerData {\n const firestore = useFirestore()\n /*\n * The organization's own datasets, listed through the source the data\n * plugin publishes (AGL-3080): the org hub admits only org-wide members,\n * who read every dataset, and placement narrows them below.\n */\n const { data: datasetRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && orgId\n ? pluginRecordListQuery('dataset', firestore, {\n orgId,\n hostId: null,\n limit: EDITOR_OPTION_CEILING + 1,\n })\n : null,\n [firestore, orgId, editorOpened],\n { idField: '$id' },\n )\n const { rows: datasetRows, truncated: datasetsTruncated } =\n ceilingedWindow<any>(datasetRead, EDITOR_OPTION_CEILING)\n const { data: listRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && orgId\n ? collectionCeiling(\n collection(firestore, 'orgs', orgId, 'lists'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, orgId, editorOpened],\n { idField: '$id' },\n )\n const { rows: listDocs, truncated: listsTruncated } = ceilingedWindow<any>(\n listRead,\n EDITOR_OPTION_CEILING,\n )\n // The `campaign` container kind, where its declaration says it is stored.\n const campaignCollection = pluginContainerKind('campaign')?.orgCollection\n const { data: campaignRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && orgId && campaignCollection\n ? collectionCeiling(\n collection(firestore, 'orgs', orgId, campaignCollection),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, orgId, editorOpened, campaignCollection],\n { idField: '$id' },\n )\n const { rows: campaignDocs, truncated: campaignsTruncated } =\n ceilingedWindow<any>(campaignRead, EDITOR_OPTION_CEILING)\n\n const pickers = useMemo<AutomationStepPickers>(() => {\n const covers = (row: any) =>\n scopeCovers(row?.visibleTo as string[] | undefined, placement)\n return {\n workflowOptions: [],\n overlayOptions: [],\n webhookOptions: [],\n datasetOptions: datasetOptionsOf(\n pluginRecordsFromRows('dataset', datasetRows).filter((dataset) =>\n scopeCovers(dataset.facts['visibleTo'] as string[] | undefined, placement),\n ),\n ),\n listOptions: (listDocs ?? [])\n .filter((list: any) => !list.deletedAt && list.name)\n .map((list: any) => ({ id: list.$id as string, name: list.name as string }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n campaignOptions: (campaignDocs ?? [])\n .filter((campaign: any) => !campaign.deletedAt && campaign.name)\n .filter(covers)\n .map((campaign: any) => ({\n id: campaign.$id as string,\n name: campaign.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n }\n }, [datasetRows, listDocs, campaignDocs, placement])\n\n const truncated = [\n datasetsTruncated ? 'datasets' : null,\n listsTruncated ? 'audiences' : null,\n campaignsTruncated ? 'campaigns' : null,\n ].filter((name): name is string => name !== null)\n return { pickers, truncated }\n}\n"],"names":["scopeCovers","pluginContainerKind","pluginRecordListQuery","pluginRecordPickerLabels","pluginRecordsFromRows","useFirestore","useFirestoreCollection","ceilingedWindow","collectionCeiling","collection","useMemo","datasetOptionsOf","records","labels","map","dataset","id","name","label","sort","a","b","localeCompare","EDITOR_OPTION_CEILING","useOrgAutomationStepPickers","orgId","editorOpened","placement","firestore","data","datasetRead","hostId","limit","idField","rows","datasetRows","truncated","datasetsTruncated","listRead","listDocs","listsTruncated","campaignCollection","orgCollection","campaignRead","campaignDocs","campaignsTruncated","pickers","covers","row","visibleTo","workflowOptions","overlayOptions","webhookOptions","datasetOptions","filter","facts","listOptions","list","deletedAt","$id","campaignOptions","campaign"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAASA,WAAW,QAAQ,sCAAqC;AACjE,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SACEC,qBAAqB,EACrBC,wBAAwB,EACxBC,qBAAqB,QAChB,kDAAiD;AAExD,SACEC,Y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4C,SAAS5C,IAAI;gBACrB,CAAA,GACCE,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEH,IAAI,CAACK,aAAa,CAACD,EAAEJ,IAAI;QAC/C;IACF,GAAG;QAACkB;QAAaI;QAAUK;QAAcjB;KAAU;IAEnD,MAAMS,YAAY;QAChBC,oBAAoB,aAAa;QACjCG,iBAAiB,cAAc;QAC/BK,qBAAqB,cAAc;KACpC,CAACS,MAAM,CAAC,CAACrC,OAAyBA,SAAS;IAC5C,OAAO;QAAE6B;QAASV;IAAU;AAC9B"}
1
+ {"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/use-org-automation-step-pickers.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n'use client'\n\nimport { sharingCovers } from '@aglyn/aglyn/app-utils/scope-tokens'\nimport { pluginContainerKind } from '@aglyn/aglyn/plugin-manager/plugin-containers'\nimport {\n pluginRecordListQuery,\n pluginRecordPickerLabels,\n pluginRecordsFromRows,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport type { PluginIndexedRecord } from '@aglyn/aglyn/plugin-manager/plugin-record-index'\nimport {\n useFirestore,\n useFirestoreCollection,\n} from '@aglyn/tenant-feature-instance'\n/*\n * The MODULE, not the barrel, for the two pure helpers — the cards' specs\n * mock `@aglyn/tenant-feature-instance` wholesale, and a query builder\n * imported through that barrel disappears under the mock.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { collection } from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport type { AutomationStepPickers } from './automation-step-fields.component'\n\n/**\n * The datasets an org automation can write to, by name, each told apart from\n * another of its name by who it is shared with, as their owner says it\n * (AGL-4047).\n */\nfunction datasetOptionsOf(records: readonly PluginIndexedRecord[]) {\n const labels = pluginRecordPickerLabels('dataset', records)\n return records\n .map((dataset) => ({ id: dataset.id, name: dataset.name, label: labels[dataset.id] }))\n .sort((a, b) => a.name.localeCompare(b.name))\n}\nimport {\n type AutomationStepPickerData,\n EDITOR_OPTION_CEILING,\n} from './use-automation-step-pickers'\n\n/**\n * WHAT AN ORG AUTOMATION'S STEPS CAN BE POINTED AT (AGL-3302).\n *\n * The site editor's pickers read one site's records; an org automation runs\n * on every site it is placed on, so its pickers read the ORGANIZATION's —\n * the lists, the datasets and the campaign containers — and offer only what\n * every one of those sites can use. A dataset or a campaign shared with some\n * of the org's sites and not the others would resolve on one site and fail\n * the step on the next, so a record is offered only when its own sharing\n * covers the automation's placement (`sharingCovers`, which also holds for\n * the sites all sites except some will reach later, AGL-4047). A list belongs\n * to the whole organization and is always offered.\n *\n * The site-only pickers — workflows, overlays, webhooks — are empty: no step\n * an org automation may hold points at one.\n *\n * Read on the same latch and at the same ceiling as the site editor's, and\n * paid only by an author who opens the editor.\n */\nexport function useOrgAutomationStepPickers(\n orgId: string,\n editorOpened: boolean,\n /** The automation as its placement would leave it: `visibleTo`, and the marker for all sites except some. */\n placement: Readonly<Record<string, unknown>>,\n): AutomationStepPickerData {\n const firestore = useFirestore()\n /*\n * The organization's own datasets, listed through the source the data\n * plugin publishes (AGL-3080): the org hub admits only org-wide members,\n * who read every dataset, and placement narrows them below.\n */\n const { data: datasetRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && orgId\n ? pluginRecordListQuery('dataset', firestore, {\n orgId,\n hostId: null,\n limit: EDITOR_OPTION_CEILING + 1,\n })\n : null,\n [firestore, orgId, editorOpened],\n { idField: '$id' },\n )\n const { rows: datasetRows, truncated: datasetsTruncated } =\n ceilingedWindow<any>(datasetRead, EDITOR_OPTION_CEILING)\n const { data: listRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && orgId\n ? collectionCeiling(\n collection(firestore, 'orgs', orgId, 'lists'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, orgId, editorOpened],\n { idField: '$id' },\n )\n const { rows: listDocs, truncated: listsTruncated } = ceilingedWindow<any>(\n listRead,\n EDITOR_OPTION_CEILING,\n )\n // The `campaign` container kind, where its declaration says it is stored.\n const campaignCollection = pluginContainerKind('campaign')?.orgCollection\n const { data: campaignRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && orgId && campaignCollection\n ? collectionCeiling(\n collection(firestore, 'orgs', orgId, campaignCollection),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, orgId, editorOpened, campaignCollection],\n { idField: '$id' },\n )\n const { rows: campaignDocs, truncated: campaignsTruncated } =\n ceilingedWindow<any>(campaignRead, EDITOR_OPTION_CEILING)\n\n const pickers = useMemo<AutomationStepPickers>(() => {\n const covers = (row: any) => sharingCovers(row ?? null, placement)\n return {\n workflowOptions: [],\n overlayOptions: [],\n webhookOptions: [],\n datasetOptions: datasetOptionsOf(\n pluginRecordsFromRows('dataset', datasetRows).filter((dataset) =>\n sharingCovers(dataset.facts, placement),\n ),\n ),\n listOptions: (listDocs ?? [])\n .filter((list: any) => !list.deletedAt && list.name)\n .map((list: any) => ({ id: list.$id as string, name: list.name as string }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n campaignOptions: (campaignDocs ?? [])\n .filter((campaign: any) => !campaign.deletedAt && campaign.name)\n .filter(covers)\n .map((campaign: any) => ({\n id: campaign.$id as string,\n name: campaign.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n }\n }, [datasetRows, listDocs, campaignDocs, placement])\n\n const truncated = [\n datasetsTruncated ? 'datasets' : null,\n listsTruncated ? 'audiences' : null,\n campaignsTruncated ? 'campaigns' : null,\n ].filter((name): name is string => name !== null)\n return { pickers, truncated }\n}\n"],"names":["sharingCovers","pluginContainerKind","pluginRecordListQuery","pluginRecordPickerLabels","pluginRecordsFromRows","useFirestore","useFirestoreCollection","ceilingedWindow","collectionCeiling","collection","useMemo","datasetOptionsOf","records","labels","map","dataset","id","name","label","sort","a","b","localeCompare","EDITOR_OPTION_CEILING","useOrgAutomationStepPickers","orgId","editorOpened","placement","firestore","data","datasetRead","hostId","limit","idField","rows","datasetRows","truncated","datasetsTruncated","listRead","listDocs","listsTruncated","campaignCollection","orgCollection","campaignRead","campaignDocs","campaignsTruncated","pickers","covers","row","workflowOptions","overlayOptions","webhookOptions","datasetOptions","filter","facts","listOptions","list","deletedAt","$id","campaignOptions","campaign"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA,SAASA,aAAa,QAAQ,sCAAqC;AACnE,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SACEC,qBAAqB,EACrBC,wBAAwB,EACxBC,qBAAqB,QAChB,kDAAiD;AAExD,SACEC,YAAY,EACZC,sBAAsB,QACjB,iCAAgC;AACvC;;;;CAIC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,UAAU,QAAQ,qBAAoB;AAC/C,SAASC,OAAO,QAAQ,QAAO;AAG/B;;;;CAIC,GACD,SAASC,iBAAiBC,OAAuC;IAC/D,MAAMC,SAASV,yBAAyB,WAAWS;IACnD,OAAOA,QACJE,GAAG,CAAC,CAACC,UAAa,CAAA;YAAEC,IAAID,QAAQC,EAAE;YAAEC,MAAMF,QAAQE,IAAI;YAAEC,OAAOL,MAAM,CAACE,QAAQC,EAAE,CAAC;QAAC,CAAA,GAClFG,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEH,IAAI,CAACK,aAAa,CAACD,EAAEJ,IAAI;AAC/C;AACA,SAEEM,qBAAqB,QAChB,mCAA+B;AAEtC;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,SAASC,4BACdC,KAAa,EACbC,YAAqB,EACrB,2GA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B,aAAakB,MAAM,CAAC,CAACtC,UACpDf,cAAce,QAAQuC,KAAK,EAAE3B;YAGjC4B,aAAa,CAAChB,mBAAAA,WAAY,EAAE,EACzBc,MAAM,CAAC,CAACG,OAAc,CAACA,KAAKC,SAAS,IAAID,KAAKvC,IAAI,EAClDH,GAAG,CAAC,CAAC0C,OAAe,CAAA;oBAAExC,IAAIwC,KAAKE,GAAG;oBAAYzC,MAAMuC,KAAKvC,IAAI;gBAAW,CAAA,GACxEE,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEH,IAAI,CAACK,aAAa,CAACD,EAAEJ,IAAI;YAC7C0C,iBAAiB,CAACf,uBAAAA,eAAgB,EAAE,EACjCS,MAAM,CAAC,CAACO,WAAkB,CAACA,SAASH,SAAS,IAAIG,SAAS3C,IAAI,EAC9DoC,MAAM,CAACN,QACPjC,GAAG,CAAC,CAAC8C,WAAmB,CAAA;oBACvB5C,IAAI4C,SAASF,GAAG;oBAChBzC,MAAM2C,SAAS3C,IAAI;gBACrB,CAAA,GACCE,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAEH,IAAI,CAACK,aAAa,CAACD,EAAEJ,IAAI;QAC/C;IACF,GAAG;QAACkB;QAAaI;QAAUK;QAAcjB;KAAU;IAEnD,MAAMS,YAAY;QAChBC,oBAAoB,aAAa;QACjCG,iBAAiB,cAAc;QAC/BK,qBAAqB,cAAc;KACpC,CAACQ,MAAM,CAAC,CAACpC,OAAyBA,SAAS;IAC5C,OAAO;QAAE6B;QAASV;IAAU;AAC9B"}
@@ -14,7 +14,7 @@
14
14
  * See the License for the specific language governing permissions and
15
15
  * limitations under the License.
16
16
  */
17
- import { type ScopeToken } from '@aglyn/aglyn/app-utils/scope-tokens';
17
+ import { type SCOPE_MODE_ALL_EXCEPT, type ScopeSharingChoice, type ScopeToken } from '@aglyn/aglyn/app-utils/scope-tokens';
18
18
  import { type TriggerCombinator } from '@aglyn/aglyn/app-utils/site-interactions';
19
19
  import { type HostActionStep, type HostActionTriggerCondition } from './host-actions';
20
20
  /**
@@ -157,11 +157,31 @@ export interface OrgAutomationFields {
157
157
  /**
158
158
  * The sites it runs on, as scope tokens: `['org']` is every site of the
159
159
  * organization, now and later; `['host:{id}', …]` names up to thirty.
160
+ * For one that runs on all sites except some, the sites still in, which
161
+ * the route works out from the workspace's sites when it writes: the
162
+ * reader leaves it empty.
160
163
  */
161
164
  visibleTo: ScopeToken[];
165
+ /**
166
+ * How the editor chose the sites (AGL-4047), when it said so. Set, it
167
+ * decides: `allExcept` is written by the route as the included sites plus
168
+ * the sweep's marker (`scopeMode`, `scopeExcept`), and `all` or `selected`
169
+ * removes a marker the automation carried. Missing, as from a client that
170
+ * predates it, a save that leaves `visibleTo` as it was keeps the marker,
171
+ * and one that changes it removes it. Never stored under this name.
172
+ */
173
+ sharing?: ScopeSharingChoice;
162
174
  }
163
175
  /** `orgs/{orgId}/automations/{id}`, as it is stored. */
164
- export interface OrgAutomation extends OrgAutomationFields {
176
+ export interface OrgAutomation extends Omit<OrgAutomationFields, 'sharing'> {
177
+ /**
178
+ * Set on one that runs on all sites except some (AGL-4047): the marker the
179
+ * sweep keeps `visibleTo` up to date from as sites come and go. Only the
180
+ * manage route writes it, and it removes it with a field delete.
181
+ */
182
+ scopeMode?: typeof SCOPE_MODE_ALL_EXCEPT;
183
+ /** The sites left out, as scope tokens, beside `scopeMode`. */
184
+ scopeExcept?: ScopeToken[];
165
185
  /**
166
186
  * The sites that have paused it for themselves — each a site id, never a
167
187
  * scope token. The "host level control": a site's admin or editor adds or
@@ -193,10 +213,11 @@ export type OrgAutomationInput = Record<string, unknown>;
193
213
  * the two this vocabulary adds: the trigger must be an org trigger and every
194
214
  * step an org step. The placement must be a scope a save can store:
195
215
  * `normalizeVisibleTo` refuses an empty one and one over thirty sites rather
196
- * than guessing between sharing wider and taking access away.
216
+ * than guessing between sharing wider and taking access away. All sites
217
+ * except some (AGL-4047) must leave at least one site out.
197
218
  *
198
219
  * Whether each named site belongs to the organization is the route's to ask,
199
- * because it takes a read.
220
+ * because it takes a read, and so is which sites all-but-some reaches.
200
221
  */
201
222
  export declare function readOrgAutomation(input: unknown): {
202
223
  ok: true;
@@ -205,6 +226,14 @@ export declare function readOrgAutomation(input: unknown): {
205
226
  ok: false;
206
227
  problem: string;
207
228
  };
229
+ /**
230
+ * The sharing choice a STORED automation was written with, for a reader that
231
+ * has to say it back (AGL-4047): all sites except some, read off the marker,
232
+ * or null for one whose `visibleTo` already says everything.
233
+ */
234
+ export declare function orgAutomationStoredSharing(automation: Readonly<Record<string, unknown>> | null | undefined): Extract<ScopeSharingChoice, {
235
+ mode: 'allExcept';
236
+ }> | null;
208
237
  /** A stored document's pause list, read defensively. */
209
238
  export declare function orgAutomationPausedHostIds(automation: {
210
239
  pausedHostIds?: unknown;
@@ -230,6 +259,8 @@ export declare function orgAutomationRunsOnHost(automation: Parameters<typeof or
230
259
  /**
231
260
  * A pause list after the placement changed: a site the automation no longer
232
261
  * runs on has nothing left to pause, so its entry goes with it, and a site
233
- * placed on it again later starts unpaused.
262
+ * placed on it again later starts unpaused. A site left out of one that runs
263
+ * on all sites except some is not in `visibleTo`, so its pause goes too
264
+ * (AGL-4047).
234
265
  */
235
266
  export declare function prunePausedHostIds(pausedHostIds: readonly string[], visibleTo: readonly string[]): string[];
@@ -14,7 +14,7 @@ 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 { normalizeVisibleTo, visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
17
+ */ import { hostScopeToken, normalizeVisibleTo, ORG_SCOPE_TOKEN, scopeSharingOf, visibleToHost } from "@aglyn/aglyn/app-utils/scope-tokens";
18
18
  import { ACTION_MAX_CONDITIONS, ACTION_MAX_STEPS, TRIGGER_COMBINATORS, TRIGGER_CONDITION_OPS } from "@aglyn/aglyn/app-utils/site-interactions";
19
19
  import { HOST_ACTION_STEP_LABELS, validateHostAction } from "./host-actions.js";
20
20
  /**
@@ -298,6 +298,65 @@ function readCombinator(raw) {
298
298
  }
299
299
  return step;
300
300
  }
301
+ /** The most site ids one choice may name: far past any workspace. */ const SHARING_CHOICE_MAX_IDS = 1000;
302
+ const SHARING_PROBLEM = 'Choose every site, the sites, or every site except some, for it to run on';
303
+ /**
304
+ * A sharing choice off the wire (AGL-4047), or null when there is none. Ids are
305
+ * held to a document id's shape here; whether they are the workspace's is the
306
+ * route's to ask.
307
+ */ function readSharingChoice(raw) {
308
+ if (raw === undefined || raw === null) return {
309
+ ok: true,
310
+ choice: null
311
+ };
312
+ const source = asObject(raw);
313
+ const ids = (list)=>Array.isArray(list) && list.length <= SHARING_CHOICE_MAX_IDS && list.every((id)=>typeof id === 'string' && /^[^:/]+$/.test(id)) ? [
314
+ ...new Set(list)
315
+ ] : null;
316
+ if ((source == null ? void 0 : source['mode']) === 'all') return {
317
+ ok: true,
318
+ choice: {
319
+ mode: 'all'
320
+ }
321
+ };
322
+ if ((source == null ? void 0 : source['mode']) === 'selected') {
323
+ const hostIds = ids(source['hostIds']);
324
+ return hostIds ? {
325
+ ok: true,
326
+ choice: {
327
+ mode: 'selected',
328
+ hostIds
329
+ }
330
+ } : {
331
+ ok: false,
332
+ problem: SHARING_PROBLEM
333
+ };
334
+ }
335
+ if ((source == null ? void 0 : source['mode']) === 'allExcept') {
336
+ const exceptHostIds = ids(source['exceptHostIds']);
337
+ if (!exceptHostIds) return {
338
+ ok: false,
339
+ problem: SHARING_PROBLEM
340
+ };
341
+ if (!exceptHostIds.length) {
342
+ return {
343
+ ok: false,
344
+ problem: 'Choose at least one site to leave out, or run it on every site'
345
+ };
346
+ }
347
+ return {
348
+ ok: true,
349
+ choice: {
350
+ mode: 'allExcept',
351
+ exceptHostIds
352
+ }
353
+ };
354
+ }
355
+ return {
356
+ ok: false,
357
+ problem: SHARING_PROBLEM
358
+ };
359
+ }
301
360
  /**
302
361
  * Reads an org automation out of an untrusted request body: the fields it may
303
362
  * hold, in the shape they are stored, or the first reason it cannot be saved.
@@ -307,10 +366,11 @@ function readCombinator(raw) {
307
366
  * the two this vocabulary adds: the trigger must be an org trigger and every
308
367
  * step an org step. The placement must be a scope a save can store:
309
368
  * `normalizeVisibleTo` refuses an empty one and one over thirty sites rather
310
- * than guessing between sharing wider and taking access away.
369
+ * than guessing between sharing wider and taking access away. All sites
370
+ * except some (AGL-4047) must leave at least one site out.
311
371
  *
312
372
  * Whether each named site belongs to the organization is the route's to ask,
313
- * because it takes a read.
373
+ * because it takes a read, and so is which sites all-but-some reaches.
314
374
  */ export function readOrgAutomation(input) {
315
375
  var _asObject, _body_name, _asObject1, _trigger_event, _trigger_filter;
316
376
  const body = (_asObject = asObject(input)) != null ? _asObject : {};
@@ -362,7 +422,19 @@ function readCombinator(raw) {
362
422
  ok: false,
363
423
  problem
364
424
  };
365
- const visibleTo = normalizeVisibleTo(Array.isArray(body['visibleTo']) ? body['visibleTo'].filter((token)=>typeof token === 'string') : []);
425
+ const sharing = readSharingChoice(body['sharing']);
426
+ if (sharing.ok === false) return {
427
+ ok: false,
428
+ problem: sharing.problem
429
+ };
430
+ const choice = sharing.choice;
431
+ /*
432
+ * A choice decides the placement; without one, `visibleTo` does, as it did
433
+ * before there was a choice. All sites except some names no site here: the
434
+ * route works the sites out from the workspace's, in the write.
435
+ */ const visibleTo = (choice == null ? void 0 : choice.mode) === 'allExcept' ? [] : (choice == null ? void 0 : choice.mode) === 'all' ? [
436
+ ORG_SCOPE_TOKEN
437
+ ] : normalizeVisibleTo((choice == null ? void 0 : choice.mode) === 'selected' ? choice.hostIds.map(hostScopeToken) : Array.isArray(body['visibleTo']) ? body['visibleTo'].filter((token)=>typeof token === 'string') : []);
366
438
  if (!visibleTo) {
367
439
  return {
368
440
  ok: false,
@@ -371,7 +443,7 @@ function readCombinator(raw) {
371
443
  }
372
444
  return {
373
445
  ok: true,
374
- value: {
446
+ value: _extends({
375
447
  name,
376
448
  trigger: _extends({
377
449
  event
@@ -384,9 +456,22 @@ function readCombinator(raw) {
384
456
  steps: steps,
385
457
  enabled: body['enabled'] !== false,
386
458
  visibleTo
387
- }
459
+ }, choice ? {
460
+ sharing: choice
461
+ } : {})
388
462
  };
389
463
  }
464
+ /**
465
+ * The sharing choice a STORED automation was written with, for a reader that
466
+ * has to say it back (AGL-4047): all sites except some, read off the marker,
467
+ * or null for one whose `visibleTo` already says everything.
468
+ */ export function orgAutomationStoredSharing(automation) {
469
+ const sharing = scopeSharingOf(automation);
470
+ return sharing.mode === 'allExcept' ? {
471
+ mode: 'allExcept',
472
+ exceptHostIds: sharing.exceptHostIds
473
+ } : null;
474
+ }
390
475
  /** A stored document's pause list, read defensively. */ export function orgAutomationPausedHostIds(automation) {
391
476
  const paused = automation == null ? void 0 : automation.pausedHostIds;
392
477
  return Array.isArray(paused) ? paused.filter((id)=>typeof id === 'string') : [];
@@ -421,7 +506,9 @@ function readCombinator(raw) {
421
506
  /**
422
507
  * A pause list after the placement changed: a site the automation no longer
423
508
  * runs on has nothing left to pause, so its entry goes with it, and a site
424
- * placed on it again later starts unpaused.
509
+ * placed on it again later starts unpaused. A site left out of one that runs
510
+ * on all sites except some is not in `visibleTo`, so its pause goes too
511
+ * (AGL-4047).
425
512
  */ export function prunePausedHostIds(pausedHostIds, visibleTo) {
426
513
  return pausedHostIds.filter((hostId)=>visibleToHost(visibleTo, hostId));
427
514
  }