@aglyn/plugins-workflows 1.0.0-beta.219 → 1.0.0-beta.221
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/README.md +7 -2
- package/package.json +13 -13
- package/src/lib/components/host-actions-card.component.js +3 -2
- package/src/lib/components/host-actions-card.component.js.map +1 -1
- package/src/lib/components/host-run-history-card.component.d.ts +2 -2
- package/src/lib/components/host-run-history-card.component.js +2 -1
- package/src/lib/components/host-run-history-card.component.js.map +1 -1
- package/src/lib/components/host-webhooks-card.component.js +2 -1
- package/src/lib/components/host-webhooks-card.component.js.map +1 -1
- package/src/lib/components/host-workflows-card.component.js +2 -2
- package/src/lib/components/host-workflows-card.component.js.map +1 -1
- package/src/lib/components/use-automation-step-pickers.js +50 -42
- package/src/lib/components/use-automation-step-pickers.js.map +1 -1
- package/src/lib/components/use-org-automation-step-pickers.js +23 -11
- package/src/lib/components/use-org-automation-step-pickers.js.map +1 -1
- package/src/lib/components/workflow-zones.d.ts +49 -0
- package/src/lib/components/workflow-zones.js +3 -0
- package/src/lib/components/workflow-zones.js.map +1 -1
- package/src/lib/engine/crm-action-steps.d.ts +14 -1
- package/src/lib/engine/crm-action-steps.js +15 -0
- package/src/lib/engine/crm-action-steps.js.map +1 -1
- package/src/lib/engine/run-event-actions.js +65 -24
- package/src/lib/engine/run-event-actions.js.map +1 -1
- package/src/lib/engine/run-event-workflows.js +2 -2
- package/src/lib/engine/run-event-workflows.js.map +1 -1
- package/src/lib/model/automation-record.d.ts +47 -0
- package/src/lib/model/automation-record.js +79 -0
- package/src/lib/model/automation-record.js.map +1 -0
- package/src/lib/model/step-outcomes.d.ts +42 -0
- package/src/lib/model/step-outcomes.js +70 -0
- package/src/lib/model/step-outcomes.js.map +1 -0
- package/src/lib/model/webhooks.d.ts +36 -0
- package/src/lib/model/webhooks.js +24 -0
- package/src/lib/model/webhooks.js.map +1 -0
- package/src/lib/model/workflows-record-lists.d.ts +18 -0
- package/src/lib/model/workflows-record-lists.js +45 -0
- package/src/lib/model/workflows-record-lists.js.map +1 -0
- package/src/lib/model/workflows.d.ts +16 -4
- package/src/lib/model/workflows.js +10 -9
- package/src/lib/model/workflows.js.map +1 -1
- package/src/lib/plugin.js +33 -2
- package/src/lib/plugin.js.map +1 -1
- package/src/lib/server/automation-record-index.js +16 -47
- package/src/lib/server/automation-record-index.js.map +1 -1
- package/src/lib/server.js.map +1 -1
- package/src/lib/testing/stand-in-dataset-list.d.ts +28 -0
- package/src/lib/testing/stand-in-dataset-list.js +55 -0
- package/src/lib/testing/stand-in-dataset-list.js.map +1 -0
- package/src/lib/testing/stand-in-overlay-list.d.ts +26 -0
- package/src/lib/testing/stand-in-overlay-list.js +53 -0
- package/src/lib/testing/stand-in-overlay-list.js.map +1 -0
- package/src/lib/usage-axes.d.ts +1 -1
- package/src/lib/usage-axes.js +13 -2
- package/src/lib/usage-axes.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/host-workflows-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 checkQuota,\n HOST_EVENT_TYPES,\n hostEventLabel,\n hostEventPayloadHint,\n type HostActionStep,\n type HostActionStepType,\n type HostFunction,\n type HostVariable,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — every spec that\n * renders this card mocks `@aglyn/tenant-feature-instance` wholesale to stage\n * its Firestore hooks, and a query builder imported through that barrel\n * disappears under the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { useConsoleWidgetSlot } from '@aglyn/aglyn/app-utils/console-widget-slot-context'\nimport type { ConsoleAutomationTarget } from '@aglyn/aglyn/plugin-manager/feature-plugins'\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 QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getCountFromServer,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n AutomationStepFields,\n type AutomationStepKind,\n defaultStep,\n} from './automation-step-fields.component'\nimport {\n type AutomationWorkflow,\n isWorkflowActionStep,\n validateWorkflowSteps,\n WORKFLOW_ACTION_STEP_TYPES,\n workflowFunctionCalls,\n type WorkflowStep,\n workflowStepTypeLabel,\n} from '../engine/workflow-steps'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport {\n EDITOR_OPTION_CEILING,\n useAutomationStepPickers,\n} from './use-automation-step-pickers'\nimport { listConsoleWidgets } from '@aglyn/aglyn'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\nimport { WORKFLOW_USAGE_ZONE } from './workflow-zones'\nimport {\n type HostWorkflowStep,\n runWorkflow,\n WORKFLOW_MAX_STEPS,\n} from '../model/workflows'\n\n/**\n * How many workflows the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst WORKFLOW_CEILING = 100\n\n/** The \"Do\" entry for the step kind a workflow has always had: a call. */\nconst FUNCTION_CALL_KIND = 'functionCall'\n\n/**\n * What a step may be (AGL-3105).\n *\n * The function call comes first because it is what a workflow was before the\n * two engines became one, and is still what a new step is. After it comes\n * every Actions step a SERVER event can run — the client-only interactions\n * are absent, because a workflow runs where there is no page to run them on.\n */\nconst STEP_KINDS: AutomationStepKind[] = [\n { value: FUNCTION_CALL_KIND, label: 'Call a function' },\n ...WORKFLOW_ACTION_STEP_TYPES.map((value) => ({\n value,\n label: workflowStepTypeLabel(value),\n })),\n]\n\nexport interface HostWorkflowsCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n}\n\ninterface WorkflowDraft extends AutomationWorkflow {\n id: string | null\n}\n\n/**\n * Workflow builder v1 (AGL-101): pipelines of host-function calls — each\n * step's argument expressions see host variables and previous step results\n * (`step1`, or a custom result name). Runs through the pure `runWorkflow`\n * evaluator; test-run panel included. Plan-gated (`workflows` flag +\n * `workflowsPerHost` cap, AGL-99); site-event triggers are v2.\n */\nexport function HostWorkflowsCard(props: HostWorkflowsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): the copy keeps every step and arrives disarmed —\n // its trigger is cleared — so nothing runs twice until somebody arms it.\n const duplicate = useDuplicateResource({\n hostId,\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(\n `Duplicated as “${copy.name}” — arm its trigger to run it`,\n {\n variant: 'success',\n },\n ),\n })\n const { confirm } = useConfirmationContext()\n const { org } = props\n /**\n * The shell's zone renderer, for what other plugins add to a saved workflow's\n * editor (AGL-2919); `null` outside the console shell.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n\n const {\n data: workflowDocs,\n status: workflowsStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing destructures a whole stored workflow into `draft`\n * and writes `{...definition}` back, so `merge: true` protects nothing.\n * `trigger` is the field that makes this more than a lost edit: it is\n * `{event, filter}` or `null` for manual-only, and nothing else on this\n * card writes it, so a cached seed can re-arm an automation the author\n * disarmed — or disarm one running on a live site — and revert every\n * step of the pipeline with it.\n */\n fromCache: workflowsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the logic plugin's two cards, for the same reasons.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below arranges\n * alphabetically, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every workflow written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.workflows` copies one only if the export carried it.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows: computed variables look their workflow up BY NAME\n * (AGL-185/AGL-261), so a duplicate silently rebinds a live binding, and a\n * uniqueness check over a ten-row page would let one through.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'workflows'),\n WORKFLOW_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readWorkflows, truncated: workflowsTruncated } =\n ceilingedWindow<any>(workflowDocs, WORKFLOW_CEILING)\n const [draft, setDraft] = useState<WorkflowDraft | null>(null)\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the two reads below key their\n * listeners on it. Tracking the dialog would tear those subscriptions down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten actions would buy the same two windows ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * THE EDITOR'S WORKING SET, read when the editor opens.\n *\n * Nothing outside the dialog reads either of these: the table renders a\n * workflow's stored step names, and `runWorkflow` is only reachable from the\n * test-run button inside the dialog. Mounting them unconditionally charges\n * every visitor to this page two windows to fill a select and seed a\n * scratchpad most of them never open.\n *\n * Ceilinged and ordered for the reason the workflows query above gives: a\n * bare `limit` is answered in document-id order, so the `localeCompare` on\n * the options below would arrange a pseudo-random hundred into a convincing\n * alphabet, and a function past the window could not be picked with nothing\n * saying why.\n */\n const { data: functionRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'functions'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n // Memoised so the window keeps one identity while the rows do — the option\n // list and the two lookup maps below are all built from it.\n const { rows: functionDocs, truncated: functionsTruncated } = useMemo(\n () => ceilingedWindow<any>(functionRead, EDITOR_OPTION_CEILING),\n [functionRead],\n )\n const { data: variableRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'variables'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: variableDocs, truncated: variablesTruncated } = useMemo(\n () => ceilingedWindow<any>(variableRead, EDITOR_OPTION_CEILING),\n [variableRead],\n )\n /*\n * What an ACTIONS step can be pointed at, on the same latch (AGL-3105).\n *\n * The hook the Actions builder uses, because a workflow step may be any\n * server-side Actions step and the two editors therefore offer one set of\n * records. Read on the editor's first open, like the two windows above, so\n * a reader who never edits a workflow still pays nothing for them.\n */\n const { pickers: stepPickers, truncated: truncatedPickers } =\n useAutomationStepPickers(hostId, editorOpened)\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const workflows = useMemo(\n () =>\n readWorkflows\n .filter((workflow: any) => !workflow.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readWorkflows],\n )\n // The page is a SLICE: the rows are already in hand and `nameTaken` needs\n // all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleWorkflows = useMemo(\n () => workflows.slice(page * pageSize, page * pageSize + pageSize),\n [workflows, page, pageSize],\n )\n /**\n * The workflow HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape).\n *\n * The listener is `limit(100)` and `workflows.length` fed\n * `checkQuota(org, 'workflowsPerHost', …)`, whose bands are 0 / 3 / 25 /\n * 100 / 250 / 500. The window TIES Business's 100 and hides Scale's 250\n * and Advanced's 500, so on those plans the gate compared 100 against\n * hundreds and could never refuse — while `api/hosts/resources` counted\n * the collection and did. The card offered headroom that did not exist and\n * then failed the create.\n *\n * UNFILTERED, matching that route's plain `collection('workflows').count()`\n * — its `softDeletes` branch governs only the flat per-host webhook cap, so\n * soft-deleted workflows have always counted server-side while this card\n * excluded them. Only a create moves the number, so that is where it is\n * re-read.\n */\n const [workflowCountEpoch, setWorkflowCountEpoch] = useState(0)\n const [serverWorkflowCount, setServerWorkflowCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getCountFromServer(collection(firestore, 'hosts', hostId, 'workflows'))\n .then((snapshot) => {\n if (active) setServerWorkflowCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the loaded rows — a LOWER bound and the prior\n // behaviour, never 0, which `checkQuota` would answer as \"no usage\"\n // on a site that is over its band.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, workflowCountEpoch])\n const workflowCount = serverWorkflowCount ?? workflows.length\n // Double-keyed by doc id and name (AGL-261): id references are\n // rename-safe; legacy name references keep resolving.\n const functions = useMemo(() => {\n const map: Record<string, HostFunction> = {}\n for (const definition of functionDocs ?? []) {\n if (definition.deletedAt) continue\n if (definition.$id) map[definition.$id] = definition\n if (definition.name) map[definition.name] = definition\n }\n return map\n }, [functionDocs])\n const functionOptions = useMemo(\n () =>\n (functionDocs ?? [])\n .filter((definition: any) => !definition.deletedAt && definition.name)\n .map((definition: any) => ({\n id: definition.$id as string,\n name: definition.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n [functionDocs],\n )\n const variables = useMemo(() => {\n const map: Record<string, HostVariable> = {}\n for (const variable of variableDocs ?? []) {\n if (!variable.deletedAt && variable.name) map[variable.name] = variable\n }\n return map\n }, [variableDocs])\n\n // Where-used dialog (AGL-193).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n\n const [testResult, setTestResult] = useState<string | null>(null)\n const [runsFor, setRunsFor] = useState<any | null>(null)\n\n // Case-insensitive uniqueness (AGL-185): workflow names must stay\n // unambiguous for computed-variable lookups keyed by name.\n const nameTaken = Boolean(\n draft &&\n workflows.some(\n (definition: any) =>\n String(definition.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && definition.$id !== draft.id,\n ),\n )\n\n const patch = useCallback(\n (updater: (previous: WorkflowDraft) => WorkflowDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /** The saved workflow the editor has open, as the `automationEditor` zone names it. */\n const draftId = draft?.id ?? null\n const draftName = draft?.name ?? ''\n const editorTarget = useMemo<ConsoleAutomationTarget | null>(\n () => (draftId ? { type: 'workflow', id: draftId, name: draftName } : null),\n // The name the editor opened with: the zone reads the workflow as it is\n // stored, so a rename being typed does not make it a different one.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [draftId],\n )\n\n const handleAdd = useCallback(() => {\n // Feature + cap gate (AGL-99); dark-launch for plan-less workspaces.\n if (!checkEntitlement(org, 'workflows')) {\n return void enqueueSnackbar(\n 'Workflows require a Starter plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }\n // The site's workflows, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'workflowsPerHost', workflowCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Workflow limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setTestResult(null)\n setDraft({\n id: null,\n name: '',\n steps: [{ functionName: '', args: [], resultName: '' }],\n returnValue: '',\n trigger: null,\n })\n }, [org, workflowCount, enqueueSnackbar])\n\n /**\n * Every list the ceiling cut, named — the editor's two and the step\n * pickers' six, in one notice for the reason the Actions builder gives:\n * they are one read, and an author told the function list is short learns\n * nothing from being told again about datasets.\n */\n const shortLists = useMemo(\n () =>\n [\n functionsTruncated ? 'functions' : null,\n variablesTruncated ? 'variables' : null,\n ...truncatedPickers,\n ].filter((name): name is string => name !== null),\n [functionsTruncated, variablesTruncated, truncatedPickers],\n )\n\n /**\n * The first thing wrong with the steps, said the way the editors say it.\n *\n * The same check the engine makes of what it is handed: an Actions step is\n * held to the Actions validator, a call has to name a function, and a step\n * only a visitor's browser can run is refused. Said while the author is\n * still in the dialog rather than after a save that stores a step nothing\n * can run.\n */\n const stepProblem = useMemo(\n () => (draft ? validateWorkflowSteps(draft.steps) : null),\n [draft],\n )\n\n const handleTestRun = useCallback(() => {\n if (!draft) return\n /*\n * The FUNCTION CALLS, evaluated. A test run is the pure evaluator, and\n * an Actions step is not something to evaluate — it sends, writes and\n * charges. Running one here would perform it against the live site from\n * a button labelled \"Test run\", so the calls are evaluated, each keeping\n * the result name it holds among all the steps, and the rest is left to\n * the run itself.\n */\n const run = runWorkflow(workflowFunctionCalls(draft), functions, variables)\n setTestResult(\n run.ok === false\n ? `Error: ${run.error}`\n : `Result: ${String(run.value)} (${Object.entries(run.results)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ')})`,\n )\n }, [draft, functions, variables])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim() || nameTaken) return\n // The steps are checked at the door, not after the write: a stored step\n // nothing can run is a run that fails on the site rather than here.\n if (stepProblem) {\n return void enqueueSnackbar(stepProblem, {\n variant: 'warning',\n persist: false,\n })\n }\n const { id: draftId, ...definition } = draft\n const fields = { ...definition, name: draft.name.trim().slice(0, 60) }\n try {\n if (draftId) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * the whole definition spread out of the listener row, `trigger` and\n * `steps` included, so `merge: true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'workflow',\n unreadable: workflowsStatus === 'error',\n fromCache: workflowsFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'workflows', draftId),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // every step that was built and its test run still on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New workflow rides the quota-enforcing resources API (AGL-473) —\n // it also re-checks the `workflows` entitlement server-side.\n await createHostResource({ hostId, resource: 'workflow', data: fields })\n // A create moves the count; the one-shot aggregate below does not\n // refresh itself the way the listener refreshes the rows.\n setWorkflowCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n enqueueSnackbar('Workflow saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n nameTaken,\n stepProblem,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n workflowsStatus,\n workflowsFromCache,\n ])\n\n const handleShowUsage = useCallback(\n (workflow: any) => async () => {\n setUsageLoading(workflow.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n setUsageLoading(null)\n // The rows and their deep links are drawn in a zone; with nothing\n // registered there the answer is still given, in words.\n if (listConsoleWidgets(WORKFLOW_USAGE_ZONE.id).length === 0) {\n enqueueSnackbar(\n result.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(result)}`\n : `\"${workflow.name}\" is not referenced by anything published`,\n { variant: 'info', persist: false },\n )\n return\n }\n setUsage({ name: workflow.name, result })\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleDelete = useCallback(\n (workflow: any) => async () => {\n // Dependents warning (AGL-187): computed variables backed by this\n // workflow keep their stored fallback value once it is gone.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n const confirmed = await confirm({\n title: 'Delete this workflow?',\n description: scan.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(scan)} — ` +\n 'those variables will fall back to their stored values.'\n : `\"${workflow.name}\" will no longer be runnable.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'workflows', workflow.$id),\n { deletedAt: Timestamp.now() },\n )\n enqueueSnackbar('Workflow deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n return (\n <CardDisplay\n header={'Workflows'}\n help={pluginDocsHelp('buildAWorkflow', {\n anchor: '#1-open-the-workflows-page',\n })}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={1}>\n {workflows.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Chain your functions into multi-step pipelines — each step ' +\n 'feeds the next. Site-event triggers are coming next.'}\n </Typography>\n ) : (\n visibleWorkflows.map((workflow: any) => (\n <Stack\n key={workflow.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {workflow.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${(workflow.steps ?? []).length} step${\n (workflow.steps ?? []).length === 1 ? '' : 's'\n }${\n workflow.trigger?.event\n ? ` · on ${hostEventLabel(workflow.trigger.event)}`\n : ''\n } · ${(workflow.steps ?? [])\n .map((step: any) => step.functionName)\n .join(' → ')}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === workflow.$id}\n onClick={handleShowUsage(workflow)}\n >\n {usageLoading === workflow.$id ? 'Scanning…' : 'Usage'}\n </Button>\n {/* Run history (wave v6): the event runner logs status +\n duration per run. */}\n <Button size=\"small\" onClick={() => setRunsFor(workflow)}>\n {'Runs'}\n </Button>\n <Button\n size=\"small\"\n onClick={() => {\n setTestResult(null)\n setDraft({\n id: workflow.$id,\n name: workflow.name ?? '',\n steps: workflow.steps ?? [],\n returnValue: workflow.returnValue ?? '',\n trigger: workflow.trigger ?? null,\n })\n }}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n onClick={() =>\n duplicate.request('workflow', {\n id: workflow.$id,\n name: workflow.name ?? '',\n })\n }\n >\n {'Duplicate…'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(workflow)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {workflows.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleWorkflows.length}\n // The workflows the card HOLDS. Not `workflowCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={workflows.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {workflowsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${WORKFLOW_CEILING} workflows, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add workflow'}\n </Button>\n {/* The cap, standing rather than only on refusal (AGL-2113).\n `workflowCount` is the server aggregate the gate uses, not\n `workflows.length` — the listener is `limit(100)` and its length\n saturates (AGL-1716). */}\n <QuotaReadoutComponent\n ready={org != null}\n used={workflowCount}\n limit={checkQuota(org, 'workflowsPerHost', workflowCount).limit}\n noun=\"workflow\"\n />\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Workflow' : 'Add Workflow'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && editorTarget ? (\n <ExtensionZone\n slot=\"automationEditor\"\n hostId={hostId}\n orgId={org?.$id}\n target={editorTarget}\n />\n ) : null}\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A workflow with this name already exists'\n : 'Used to identify the workflow'\n }\n error={nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Steps'}\n </Typography>\n {/*\n The pickers and the test run speak only for what was read. A step\n calling a function past the ceiling still RUNS on the site — this\n editor simply cannot name it, and a test run resolves its\n expression against an incomplete variable set.\n */}\n {shortLists.length > 0 ? (\n <Alert severity=\"info\">\n {`Offering the first ${EDITOR_OPTION_CEILING} ` +\n `${shortLists.join(', ')} on this site, ordered by id. ` +\n 'There are more, so the pickers below are short and a test ' +\n 'run may not resolve every expression.'}\n </Alert>\n ) : null}\n {(draft?.steps ?? []).map((step, index) => {\n const call = isWorkflowActionStep(step)\n ? null\n : (step as HostWorkflowStep)\n const definition = call\n ? (functions[(call as any).functionId ?? ''] ??\n functions[call.functionName])\n : null\n return (\n <AutomationStepFields\n key={index}\n /*\n * The editor speaks the Actions vocabulary. A function call\n * has no Actions type, so it takes none of those fields and\n * renders its own through `fields` instead — which is what\n * keeps this one editor rather than two.\n */\n step={step as HostActionStep}\n index={index}\n kind={call ? FUNCTION_CALL_KIND : (step as HostActionStep).type}\n kinds={STEP_KINDS}\n stepForKind={(value) =>\n (value === FUNCTION_CALL_KIND\n ? { functionName: '', args: [], resultName: '' }\n : defaultStep(\n value as HostActionStepType,\n )) as HostActionStep\n }\n pickers={stepPickers}\n onSteps={(update) =>\n patch((previous) => ({\n ...previous,\n steps: update(\n previous.steps as HostActionStep[],\n ) as WorkflowStep[],\n }))\n }\n fields={\n call ? (\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', flex: 1, flexWrap: 'wrap' }}\n >\n <TextField\n label=\"Function\"\n // Stored by id (AGL-261); legacy steps carry only the\n // name and resolve through the double-keyed map.\n value={\n (call as any).functionId ??\n (functions[call.functionName] as any)?.$id ??\n ''\n }\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n functionId: event.target.value,\n functionName:\n functionOptions.find(\n (option) =>\n option.id === event.target.value,\n )?.name ??\n (s as HostWorkflowStep).functionName,\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 160, flex: 1 }}\n >\n {functionOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Result name\"\n placeholder={`step${index + 1}`}\n value={call.resultName ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n resultName: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 140 }}\n />\n {(definition?.parameters ?? []).map(\n (parameter, parameterIndex) => (\n <TextField\n key={parameter.name}\n label={`${parameter.name} expression`}\n placeholder={\n parameterIndex === 0 && index > 0\n ? `step${index}`\n : 'a variable, number, or expression'\n }\n value={call.args?.[parameterIndex] ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) => {\n if (index2 !== index) return s\n const args = [\n ...((s as HostWorkflowStep).args ?? []),\n ]\n args[parameterIndex] = event.target.value\n return { ...s, args }\n }),\n }))\n }\n size=\"small\"\n sx={{ minWidth: 180, flex: 1 }}\n />\n ),\n )}\n </Stack>\n ) : undefined\n }\n />\n )\n })}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={(draft?.steps.length ?? 0) >= WORKFLOW_MAX_STEPS}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n steps: [\n ...previous.steps,\n { functionName: '', args: [], resultName: '' },\n ],\n }))\n }\n >\n {'Add step'}\n </Button>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Trigger'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Run on event\"\n value={draft?.trigger?.event ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: event.target.value\n ? {\n event: event.target.value as any,\n filter: previous.trigger?.filter ?? '',\n }\n : null,\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 180 }}\n >\n <MenuItem value=\"\">{'Manual only'}</MenuItem>\n {HOST_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {hostEventLabel(eventType)}\n </MenuItem>\n ))}\n </TextField>\n {draft?.trigger ? (\n <TextField\n label=\"Filter (optional)\"\n placeholder={'path == \"/pricing\"'}\n helperText={[\n 'Runs only when this expression is truthy.',\n hostEventPayloadHint(draft?.trigger?.event),\n ]\n .filter(Boolean)\n .join(' ')}\n value={draft?.trigger?.filter ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: previous.trigger\n ? { ...previous.trigger, filter: event.target.value }\n : previous.trigger,\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n ) : null}\n </Stack>\n <TextField\n label=\"Return value\"\n helperText=\"A step result name; defaults to the last step\"\n value={draft?.returnValue ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n returnValue: event.target.value,\n }))\n }\n size=\"small\"\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button size=\"small\" color=\"primary\" onClick={handleTestRun}>\n {'Test run'}\n </Button>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Uses current variable values'}\n </Typography>\n </Stack>\n {testResult ? (\n <Alert\n severity={testResult.startsWith('Error') ? 'warning' : 'success'}\n >\n {testResult}\n </Alert>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || nameTaken}\n onClick={handleSave}\n >\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n {ExtensionZone ? (\n <ExtensionZone\n slot={WORKFLOW_USAGE_ZONE.id}\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n ) : null}\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n // md: the history's four columns fit without the table scrolling.\n maxWidth=\"md\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n orgId={org?.$id}\n targetId={runsFor.$id}\n targetType=\"workflow\"\n targetName={runsFor.name ?? ''}\n header=\"Recent runs\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nHostWorkflowsCard.displayName = 'HostWorkflowsCard'\n\nexport default HostWorkflowsCard\n"],"names":["checkEntitlement","checkQuota","HOST_EVENT_TYPES","hostEventLabel","hostEventPayloadHint","pluginDocsHelp","ceilingedWindow","collectionCeiling","useConsoleWidgetSlot","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","QuotaReadoutComponent","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","doc","getCountFromServer","setDoc","updateDoc","useCallback","useEffect","useMemo","useState","useDuplicateResource","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","AutomationStepFields","defaultStep","isWorkflowActionStep","validateWorkflowSteps","WORKFLOW_ACTION_STEP_TYPES","workflowFunctionCalls","workflowStepTypeLabel","HostRunHistoryCard","EDITOR_OPTION_CEILING","useAutomationStepPickers","listConsoleWidgets","fetchWhereUsed","summarizeDependents","WORKFLOW_USAGE_ZONE","runWorkflow","WORKFLOW_MAX_STEPS","WORKFLOW_CEILING","FUNCTION_CALL_KIND","STEP_KINDS","value","label","map","HostWorkflowsCard","props","runsFor","draft","hostId","firestore","data","user","createHostResource","enqueueSnackbar","duplicate","onDuplicated","_kind","copy","name","variant","confirm","org","ExtensionZone","workflowDocs","status","workflowsStatus","fromCache","workflowsFromCache","idField","rows","readWorkflows","truncated","workflowsTruncated","setDraft","editorOpened","setEditorOpened","functionRead","functionDocs","functionsTruncated","variableRead","variableDocs","variablesTruncated","pickers","stepPickers","truncatedPickers","workflows","filter","workflow","deletedAt","sort","a","b","String","localeCompare","page","setPage","pageSize","setPageSize","visibleWorkflows","slice","workflowCountEpoch","setWorkflowCountEpoch","serverWorkflowCount","setServerWorkflowCount","active","then","snapshot","count","catch","workflowCount","length","functions","definition","$id","functionOptions","id","variables","variable","usage","setUsage","usageLoading","setUsageLoading","testResult","setTestResult","setRunsFor","nameTaken","Boolean","some","toLowerCase","trim","patch","updater","previous","draftId","draftName","editorTarget","type","handleAdd","persist","quota","allowed","limit","steps","functionName","args","resultName","returnValue","trigger","shortLists","stepProblem","handleTestRun","run","ok","error","Object","entries","results","key","join","handleSave","fields","verdict","subject","unreadable","updatedAt","now","merge","message","resource","epoch","console","allowDuplicate","handleShowUsage","result","kind","total","handleDelete","scan","confirmed","title","description","confirmationText","confirmationButtonProps","color","header","help","anchor","contentGutterX","contentGutterY","dialog","spacing","direction","sx","alignItems","flex","minWidth","noWrap","event","step","size","disabled","onClick","request","rowCount","onPageChange","onPageSizeChange","severity","alignSelf","ready","used","noun","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","slot","orgId","target","helperText","onChange","autoFocus","mt","index","call","functionId","kinds","stepForKind","onSteps","update","flexWrap","s","index2","find","option","select","placeholder","replace","width","parameters","parameter","parameterIndex","undefined","eventType","startsWith","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,gBAAgB,EAChBC,UAAU,EACVC,gBAAgB,EAChBC,cAAc,EACdC,oBAAoB,EAKpBC,cAAc,QACT,eAAc;AACrB;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,oBAAoB,QAAQ,qDAAoD;AAEzF,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACrF,OAAOC,2BAA2B,0DAAyD;AAC3F,SAASC,WAAW,QAAQ,8BAA6B;AACzD,SAASC,SAAS,QAAQ,+BAA8B;AACxD,SACEC,KAAK,EACLC,MAAM,EACNC,MAAM,EACNC,aAAa,EACbC,aAAa,EACbC,WAAW,EACXC,QAAQ,EACRC,KAAK,EACLC,SAAS,EACTC,UAAU,QACL,gBAAe;AACtB,SACEC,UAAU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CACC6D,SAAQ;gCACR4H,OAAM;gCACNiB,UAAU,EAACzJ,yBAAAA,MAAOW,IAAI,CAACuE,IAAI,OAAMJ;gCACjC4E,SAAS1C;0CAER;;;;;;YAINjG,8BACC,KAACA;gBACC6J,MAAMxL,oBAAoBgF,EAAE;gBAC5BnE,QAAQA;gBACRsE,OAAOA;gBACP8F,SAAS,IAAM7F,SAAS;iBAExB;0BACJ,MAACxH;gBACCoN,MAAMrF,QAAQhF;gBACdsK,SAAS,IAAMxF,WAAW;gBAC1B,kEAAkE;gBAClEyF,UAAS;gBACTC,SAAS;;kCAET,KAACpN;kCAAa,CAAC,OAAO,WAAE4C,2BAAAA,QAASY,IAAI,oBAAI,IAAI;;kCAC7C,KAACzD;kCACE6C,wBACC,KAACjB;4BACCmB,QAAQA;4BACR4K,KAAK,EAAE/J,uBAAAA,IAAKoD,GAAG;4BACfuI,UAAU1M,QAAQmE,GAAG;4BACrBwI,YAAW;4BACXC,UAAU,GAAE5M,gBAAAA,QAAQY,IAAI,YAAZZ,gBAAgB;4BAC5B0I,QAAO;6BAEP;;kCAEN,KAACxL;kCACC,cAAA,KAACF;4BAAOyL,OAAM;4BAAUkB,SAAS,IAAM7E,WAAW;sCAC/C;;;;;;;AAMb;AACAhF,kBAAkB+M,WAAW,GAAG;AAEhC,eAAe/M,kBAAiB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/host-workflows-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 checkQuota,\n HOST_EVENT_TYPES,\n hostEventLabel,\n hostEventPayloadHint,\n type HostActionStep,\n type HostActionStepType,\n type HostFunction,\n type HostVariable,\n pluginDocsHelp,\n} from '@aglyn/aglyn'\n/*\n * The MODULE, not the barrel, for the two PURE helpers — every spec that\n * renders this card mocks `@aglyn/tenant-feature-instance` wholesale to stage\n * its Firestore hooks, and a query builder imported through that barrel\n * disappears under the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\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 QuotaReadoutComponent from '@aglyn/shared-ui-jsx/components/quota-readout.component'\nimport { useSnackbar } from '@aglyn/shared-ui-snackstack'\nimport { Timestamp } from '@aglyn/shared-util-timestamp'\nimport {\n Alert,\n Button,\n Dialog,\n DialogActions,\n DialogContent,\n DialogTitle,\n MenuItem,\n Stack,\n TextField,\n Typography,\n} from '@mui/material'\nimport {\n collection,\n doc,\n getCountFromServer,\n setDoc,\n updateDoc,\n} from 'firebase/firestore'\nimport { useCallback, useEffect, useMemo, useState } from 'react'\nimport {\n useDuplicateResource,\n useFirestore,\n useFirestoreCollection,\n useHostResourceApi,\n useUser,\n writeGuardedBySeed,\n} from '@aglyn/tenant-feature-instance'\nimport {\n AutomationStepFields,\n type AutomationStepKind,\n defaultStep,\n} from './automation-step-fields.component'\nimport {\n type AutomationWorkflow,\n isWorkflowActionStep,\n validateWorkflowSteps,\n WORKFLOW_ACTION_STEP_TYPES,\n workflowFunctionCalls,\n type WorkflowStep,\n workflowStepTypeLabel,\n} from '../engine/workflow-steps'\nimport HostRunHistoryCard from './host-run-history-card.component'\nimport {\n EDITOR_OPTION_CEILING,\n useAutomationStepPickers,\n} from './use-automation-step-pickers'\nimport { listConsoleWidgets } from '@aglyn/aglyn'\nimport {\n fetchWhereUsed,\n summarizeDependents,\n type WhereUsedResult,\n} from '@aglyn/aglyn/app-utils/where-used'\nimport {\n AUTOMATION_EDITOR_ZONE,\n WORKFLOW_USAGE_ZONE,\n type AutomationTarget,\n} from './workflow-zones'\nimport {\n type HostWorkflowStep,\n runWorkflow,\n WORKFLOW_MAX_STEPS,\n} from '../model/workflows'\n\n/**\n * How many workflows the card reads.\n *\n * A CEILING, not a page size — see the query, which explains why this list\n * cannot be paged by the server without making the duplicate-name check lie.\n */\nconst WORKFLOW_CEILING = 100\n\n/** The \"Do\" entry for the step kind a workflow has always had: a call. */\nconst FUNCTION_CALL_KIND = 'functionCall'\n\n/**\n * What a step may be (AGL-3105).\n *\n * The function call comes first because it is what a workflow was before the\n * two engines became one, and is still what a new step is. After it comes\n * every Actions step a SERVER event can run — the client-only interactions\n * are absent, because a workflow runs where there is no page to run them on.\n */\nconst STEP_KINDS: AutomationStepKind[] = [\n { value: FUNCTION_CALL_KIND, label: 'Call a function' },\n ...WORKFLOW_ACTION_STEP_TYPES.map((value) => ({\n value,\n label: workflowStepTypeLabel(value),\n })),\n]\n\nexport interface HostWorkflowsCardProps {\n hostId: string\n /** Resolved entitlement source for quota checks (AGL-395). */\n org?: Partial<AglynOrgBilling>\n}\n\ninterface WorkflowDraft extends AutomationWorkflow {\n id: string | null\n}\n\n/**\n * Workflow builder v1 (AGL-101): pipelines of host-function calls — each\n * step's argument expressions see host variables and previous step results\n * (`step1`, or a custom result name). Runs through the pure `runWorkflow`\n * evaluator; test-run panel included. Plan-gated (`workflows` flag +\n * `workflowsPerHost` cap, AGL-99); site-event triggers are v2.\n */\nexport function HostWorkflowsCard(props: HostWorkflowsCardProps) {\n const { hostId } = props\n const firestore = useFirestore()\n const { data: user } = useUser()\n const createHostResource = useHostResourceApi()\n const { enqueueSnackbar } = useSnackbar()\n // Duplicate (AGL-2936): the copy keeps every step and arrives disarmed —\n // its trigger is cleared — so nothing runs twice until somebody arms it.\n const duplicate = useDuplicateResource({\n hostId,\n onDuplicated: (_kind, copy) =>\n enqueueSnackbar(\n `Duplicated as “${copy.name}” — arm its trigger to run it`,\n {\n variant: 'success',\n },\n ),\n })\n const { confirm } = useConfirmationContext()\n const { org } = props\n /**\n * The shell's zone renderer, for what other plugins add to a saved workflow's\n * editor (AGL-2919); `null` outside the console shell.\n */\n const ExtensionZone = useConsoleWidgetSlot()\n\n const {\n data: workflowDocs,\n status: workflowsStatus,\n /**\n * The rows this editor is seeded from are unconfirmed by the server\n * (AGL-1358). Editing destructures a whole stored workflow into `draft`\n * and writes `{...definition}` back, so `merge: true` protects nothing.\n * `trigger` is the field that makes this more than a lost edit: it is\n * `{event, filter}` or `null` for manual-only, and nothing else on this\n * card writes it, so a cached seed can re-arm an automation the author\n * disarmed — or disarm one running on a live site — and revert every\n * step of the pipeline with it.\n */\n fromCache: workflowsFromCache,\n } = useFirestoreCollection<any>(\n /*\n * ORDERED AND CEILINGED, deliberately not paged by the query (AGL-2501) —\n * the same decision as the logic plugin's two cards, for the same reasons.\n *\n * `limit(100)` alone is answered in DOCUMENT-ID order, so the window is a\n * pseudo-random hundred that the `localeCompare` below arranges\n * alphabetically, and nothing said the list was bounded.\n *\n * `collectionCeiling` does not change WHICH hundred — document-id order is\n * what the bare cap already returned. What it changes is that the order is\n * NAMED, so the obvious next edit is caught: ordering on `name` would HIDE\n * every workflow written without one rather than mis-sorting the list, and\n * `/api/hosts/resources` validates no field for presence while\n * `IMPORTABLE_FIELDS.workflows` copies one only if the export carried it.\n *\n * The QUERY is not paged because `nameTaken` below tests the draft against\n * these rows: computed variables look their workflow up BY NAME\n * (AGL-185/AGL-261), so a duplicate silently rebinds a live binding, and a\n * uniqueness check over a ten-row page would let one through.\n */\n () =>\n collectionCeiling(\n collection(firestore, 'hosts', hostId, 'workflows'),\n WORKFLOW_CEILING,\n ),\n [firestore, hostId],\n { idField: '$id' },\n )\n const { rows: readWorkflows, truncated: workflowsTruncated } =\n ceilingedWindow<any>(workflowDocs, WORKFLOW_CEILING)\n const [draft, setDraft] = useState<WorkflowDraft | null>(null)\n /**\n * The editor has been opened at least once in this session.\n *\n * A LATCH rather than `draft` itself, because the two reads below key their\n * listeners on it. Tracking the dialog would tear those subscriptions down\n * on Cancel and pay for them again on the next Edit, so a merchant working\n * through ten actions would buy the same two windows ten times — worse than\n * the mount-time read this replaces. Latched, a reader who never edits pays\n * nothing and a reader who edits pays once.\n */\n const [editorOpened, setEditorOpened] = useState(false)\n if (draft && !editorOpened) setEditorOpened(true)\n /*\n * THE EDITOR'S WORKING SET, read when the editor opens.\n *\n * Nothing outside the dialog reads either of these: the table renders a\n * workflow's stored step names, and `runWorkflow` is only reachable from the\n * test-run button inside the dialog. Mounting them unconditionally charges\n * every visitor to this page two windows to fill a select and seed a\n * scratchpad most of them never open.\n *\n * Ceilinged and ordered for the reason the workflows query above gives: a\n * bare `limit` is answered in document-id order, so the `localeCompare` on\n * the options below would arrange a pseudo-random hundred into a convincing\n * alphabet, and a function past the window could not be picked with nothing\n * saying why.\n */\n const { data: functionRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'functions'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n // Memoised so the window keeps one identity while the rows do — the option\n // list and the two lookup maps below are all built from it.\n const { rows: functionDocs, truncated: functionsTruncated } = useMemo(\n () => ceilingedWindow<any>(functionRead, EDITOR_OPTION_CEILING),\n [functionRead],\n )\n const { data: variableRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'variables'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: variableDocs, truncated: variablesTruncated } = useMemo(\n () => ceilingedWindow<any>(variableRead, EDITOR_OPTION_CEILING),\n [variableRead],\n )\n /*\n * What an ACTIONS step can be pointed at, on the same latch (AGL-3105).\n *\n * The hook the Actions builder uses, because a workflow step may be any\n * server-side Actions step and the two editors therefore offer one set of\n * records. Read on the editor's first open, like the two windows above, so\n * a reader who never edits a workflow still pays nothing for them.\n */\n const { pickers: stepPickers, truncated: truncatedPickers } =\n useAutomationStepPickers(hostId, editorOpened)\n // Sorting is safe here in a way it is not on a paged list: these rows are\n // the whole collection below the ceiling, not a slice of one.\n const workflows = useMemo(\n () =>\n readWorkflows\n .filter((workflow: any) => !workflow.deletedAt)\n .sort((a: any, b: any) =>\n String(a.name ?? '').localeCompare(String(b.name ?? '')),\n ),\n [readWorkflows],\n )\n // The page is a SLICE: the rows are already in hand and `nameTaken` needs\n // all of them.\n const [page, setPage] = useState(0)\n const [pageSize, setPageSize] = useState(TABLE_PAGE_SIZE_DEFAULT)\n const visibleWorkflows = useMemo(\n () => workflows.slice(page * pageSize, page * pageSize + pageSize),\n [workflows, page, pageSize],\n )\n /**\n * The workflow HEAD-COUNT is a server aggregate, not the length of the\n * capped listener (AGL-1716, the AGL-1706 shape).\n *\n * The listener is `limit(100)` and `workflows.length` fed\n * `checkQuota(org, 'workflowsPerHost', …)`, whose bands are 0 / 3 / 25 /\n * 100 / 250 / 500. The window TIES Business's 100 and hides Scale's 250\n * and Advanced's 500, so on those plans the gate compared 100 against\n * hundreds and could never refuse — while `api/hosts/resources` counted\n * the collection and did. The card offered headroom that did not exist and\n * then failed the create.\n *\n * UNFILTERED, matching that route's plain `collection('workflows').count()`\n * — its `softDeletes` branch governs only the flat per-host webhook cap, so\n * soft-deleted workflows have always counted server-side while this card\n * excluded them. Only a create moves the number, so that is where it is\n * re-read.\n */\n const [workflowCountEpoch, setWorkflowCountEpoch] = useState(0)\n const [serverWorkflowCount, setServerWorkflowCount] = useState<number | null>(\n null,\n )\n useEffect(() => {\n let active = true\n void getCountFromServer(collection(firestore, 'hosts', hostId, 'workflows'))\n .then((snapshot) => {\n if (active) setServerWorkflowCount(snapshot.data().count)\n })\n .catch(() => {\n // Falls back to the loaded rows — a LOWER bound and the prior\n // behaviour, never 0, which `checkQuota` would answer as \"no usage\"\n // on a site that is over its band.\n })\n return () => {\n active = false\n }\n }, [firestore, hostId, workflowCountEpoch])\n const workflowCount = serverWorkflowCount ?? workflows.length\n // Double-keyed by doc id and name (AGL-261): id references are\n // rename-safe; legacy name references keep resolving.\n const functions = useMemo(() => {\n const map: Record<string, HostFunction> = {}\n for (const definition of functionDocs ?? []) {\n if (definition.deletedAt) continue\n if (definition.$id) map[definition.$id] = definition\n if (definition.name) map[definition.name] = definition\n }\n return map\n }, [functionDocs])\n const functionOptions = useMemo(\n () =>\n (functionDocs ?? [])\n .filter((definition: any) => !definition.deletedAt && definition.name)\n .map((definition: any) => ({\n id: definition.$id as string,\n name: definition.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name)),\n [functionDocs],\n )\n const variables = useMemo(() => {\n const map: Record<string, HostVariable> = {}\n for (const variable of variableDocs ?? []) {\n if (!variable.deletedAt && variable.name) map[variable.name] = variable\n }\n return map\n }, [variableDocs])\n\n // Where-used dialog (AGL-193).\n const [usage, setUsage] = useState<{\n name: string\n result: WhereUsedResult\n } | null>(null)\n const [usageLoading, setUsageLoading] = useState<string | null>(null)\n\n const [testResult, setTestResult] = useState<string | null>(null)\n const [runsFor, setRunsFor] = useState<any | null>(null)\n\n // Case-insensitive uniqueness (AGL-185): workflow names must stay\n // unambiguous for computed-variable lookups keyed by name.\n const nameTaken = Boolean(\n draft &&\n workflows.some(\n (definition: any) =>\n String(definition.name ?? '').toLowerCase() ===\n draft.name.trim().toLowerCase() && definition.$id !== draft.id,\n ),\n )\n\n const patch = useCallback(\n (updater: (previous: WorkflowDraft) => WorkflowDraft) =>\n setDraft((previous) => (previous ? updater(previous) : previous)),\n [],\n )\n\n /** The saved workflow the editor has open, as the `automationEditor` zone names it. */\n const draftId = draft?.id ?? null\n const draftName = draft?.name ?? ''\n const editorTarget = useMemo<AutomationTarget | null>(\n () => (draftId ? { type: 'workflow', id: draftId, name: draftName } : null),\n // The name the editor opened with: the zone reads the workflow as it is\n // stored, so a rename being typed does not make it a different one.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [draftId],\n )\n\n const handleAdd = useCallback(() => {\n // Feature + cap gate (AGL-99); dark-launch for plan-less workspaces.\n if (!checkEntitlement(org, 'workflows')) {\n return void enqueueSnackbar(\n 'Workflows require a Starter plan — see Billing to upgrade',\n { variant: 'warning', persist: false },\n )\n }\n // The site's workflows, not this page of them (AGL-1716).\n const quota = checkQuota(org, 'workflowsPerHost', workflowCount)\n if (!quota.allowed) {\n return void enqueueSnackbar(\n `Workflow limit reached (${quota.limit}) — upgrade in Billing`,\n { variant: 'warning', persist: false },\n )\n }\n setTestResult(null)\n setDraft({\n id: null,\n name: '',\n steps: [{ functionName: '', args: [], resultName: '' }],\n returnValue: '',\n trigger: null,\n })\n }, [org, workflowCount, enqueueSnackbar])\n\n /**\n * Every list the ceiling cut, named — the editor's two and the step\n * pickers' six, in one notice for the reason the Actions builder gives:\n * they are one read, and an author told the function list is short learns\n * nothing from being told again about datasets.\n */\n const shortLists = useMemo(\n () =>\n [\n functionsTruncated ? 'functions' : null,\n variablesTruncated ? 'variables' : null,\n ...truncatedPickers,\n ].filter((name): name is string => name !== null),\n [functionsTruncated, variablesTruncated, truncatedPickers],\n )\n\n /**\n * The first thing wrong with the steps, said the way the editors say it.\n *\n * The same check the engine makes of what it is handed: an Actions step is\n * held to the Actions validator, a call has to name a function, and a step\n * only a visitor's browser can run is refused. Said while the author is\n * still in the dialog rather than after a save that stores a step nothing\n * can run.\n */\n const stepProblem = useMemo(\n () => (draft ? validateWorkflowSteps(draft.steps) : null),\n [draft],\n )\n\n const handleTestRun = useCallback(() => {\n if (!draft) return\n /*\n * The FUNCTION CALLS, evaluated. A test run is the pure evaluator, and\n * an Actions step is not something to evaluate — it sends, writes and\n * charges. Running one here would perform it against the live site from\n * a button labelled \"Test run\", so the calls are evaluated, each keeping\n * the result name it holds among all the steps, and the rest is left to\n * the run itself.\n */\n const run = runWorkflow(workflowFunctionCalls(draft), functions, variables)\n setTestResult(\n run.ok === false\n ? `Error: ${run.error}`\n : `Result: ${String(run.value)} (${Object.entries(run.results)\n .map(([key, value]) => `${key}=${value}`)\n .join(', ')})`,\n )\n }, [draft, functions, variables])\n\n const handleSave = useCallback(async () => {\n if (!draft || !draft.name.trim() || nameTaken) return\n // The steps are checked at the door, not after the write: a stored step\n // nothing can run is a run that fails on the site rather than here.\n if (stepProblem) {\n return void enqueueSnackbar(stepProblem, {\n variant: 'warning',\n persist: false,\n })\n }\n const { id: draftId, ...definition } = draft\n const fields = { ...definition, name: draft.name.trim().slice(0, 60) }\n try {\n if (draftId) {\n /**\n * Edit stays client-direct (no quota consumed) — and is refused when\n * its seed was never confirmed by the server (AGL-1358). `fields` is\n * the whole definition spread out of the listener row, `trigger` and\n * `steps` included, so `merge: true` has nothing left to protect.\n *\n * The guard WRAPS the write. An early return is a shape you can keep\n * while losing the protection; here the write is only reachable\n * through the verdict.\n */\n const verdict = await writeGuardedBySeed(\n {\n subject: 'workflow',\n unreadable: workflowsStatus === 'error',\n fromCache: workflowsFromCache,\n },\n async () => {\n await setDoc(\n doc(firestore, 'hosts', hostId, 'workflows', draftId),\n { ...fields, updatedAt: Timestamp.now() },\n { merge: true },\n )\n },\n )\n // Before `setDraft(null)`, so a refusal keeps the dialog open with\n // every step that was built and its test run still on screen.\n if (!verdict.ok) {\n return void enqueueSnackbar(verdict.message, {\n variant: 'warning',\n persist: false,\n })\n }\n } else {\n // New workflow rides the quota-enforcing resources API (AGL-473) —\n // it also re-checks the `workflows` entitlement server-side.\n await createHostResource({ hostId, resource: 'workflow', data: fields })\n // A create moves the count; the one-shot aggregate below does not\n // refresh itself the way the listener refreshes the rows.\n setWorkflowCountEpoch((epoch) => epoch + 1)\n }\n setDraft(null)\n enqueueSnackbar('Workflow saved', { variant: 'success', persist: false })\n } catch (error: any) {\n console.error(error)\n enqueueSnackbar(error?.message ?? 'An error has occurred', {\n variant: 'error',\n allowDuplicate: true,\n })\n }\n }, [\n draft,\n nameTaken,\n stepProblem,\n firestore,\n hostId,\n createHostResource,\n enqueueSnackbar,\n workflowsStatus,\n workflowsFromCache,\n ])\n\n const handleShowUsage = useCallback(\n (workflow: any) => async () => {\n setUsageLoading(workflow.$id)\n const result = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n setUsageLoading(null)\n // The rows and their deep links are drawn in a zone; with nothing\n // registered there the answer is still given, in words.\n if (listConsoleWidgets(WORKFLOW_USAGE_ZONE.id).length === 0) {\n enqueueSnackbar(\n result.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(result)}`\n : `\"${workflow.name}\" is not referenced by anything published`,\n { variant: 'info', persist: false },\n )\n return\n }\n setUsage({ name: workflow.name, result })\n },\n [user, hostId, enqueueSnackbar],\n )\n\n const handleDelete = useCallback(\n (workflow: any) => async () => {\n // Dependents warning (AGL-187): computed variables backed by this\n // workflow keep their stored fallback value once it is gone.\n const scan = await fetchWhereUsed(user as any, {\n hostId,\n kind: 'workflow',\n id: workflow.$id,\n name: workflow.name,\n })\n const confirmed = await confirm({\n title: 'Delete this workflow?',\n description: scan.total\n ? `\"${workflow.name}\" computes ${summarizeDependents(scan)} — ` +\n 'those variables will fall back to their stored values.'\n : `\"${workflow.name}\" will no longer be runnable.`,\n confirmationText: 'Delete',\n confirmationButtonProps: { color: 'error' },\n })\n .then(() => true)\n .catch(() => false)\n if (!confirmed) return\n await updateDoc(\n doc(firestore, 'hosts', hostId, 'workflows', workflow.$id),\n { deletedAt: Timestamp.now() },\n )\n enqueueSnackbar('Workflow deleted', {\n variant: 'success',\n persist: false,\n })\n },\n [user, confirm, firestore, hostId, enqueueSnackbar],\n )\n\n return (\n <CardDisplay\n header={'Workflows'}\n help={pluginDocsHelp('buildAWorkflow', {\n anchor: '#1-open-the-workflows-page',\n })}\n contentGutterX\n contentGutterY\n >\n {duplicate.dialog}\n <Stack spacing={1}>\n {workflows.length === 0 ? (\n <Typography variant=\"body2\" color=\"text.secondary\">\n {'Chain your functions into multi-step pipelines — each step ' +\n 'feeds the next. Site-event triggers are coming next.'}\n </Typography>\n ) : (\n visibleWorkflows.map((workflow: any) => (\n <Stack\n key={workflow.$id}\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center' }}\n >\n <Stack sx={{ flex: 1, minWidth: 0 }}>\n <Typography variant=\"body2\" noWrap>\n {workflow.name}\n </Typography>\n <Typography variant=\"caption\" color=\"text.secondary\" noWrap>\n {`${(workflow.steps ?? []).length} step${\n (workflow.steps ?? []).length === 1 ? '' : 's'\n }${\n workflow.trigger?.event\n ? ` · on ${hostEventLabel(workflow.trigger.event)}`\n : ''\n } · ${(workflow.steps ?? [])\n .map((step: any) => step.functionName)\n .join(' → ')}`}\n </Typography>\n </Stack>\n <Button\n size=\"small\"\n disabled={usageLoading === workflow.$id}\n onClick={handleShowUsage(workflow)}\n >\n {usageLoading === workflow.$id ? 'Scanning…' : 'Usage'}\n </Button>\n {/* Run history (wave v6): the event runner logs status +\n duration per run. */}\n <Button size=\"small\" onClick={() => setRunsFor(workflow)}>\n {'Runs'}\n </Button>\n <Button\n size=\"small\"\n onClick={() => {\n setTestResult(null)\n setDraft({\n id: workflow.$id,\n name: workflow.name ?? '',\n steps: workflow.steps ?? [],\n returnValue: workflow.returnValue ?? '',\n trigger: workflow.trigger ?? null,\n })\n }}\n >\n {'Edit'}\n </Button>\n <Button\n size=\"small\"\n onClick={() =>\n duplicate.request('workflow', {\n id: workflow.$id,\n name: workflow.name ?? '',\n })\n }\n >\n {'Duplicate…'}\n </Button>\n <Button\n size=\"small\"\n color=\"error\"\n onClick={handleDelete(workflow)}\n >\n {'Delete'}\n </Button>\n </Stack>\n ))\n )}\n {workflows.length === 0 ? null : (\n <ListPagination\n page={page}\n pageSize={pageSize}\n rowCount={visibleWorkflows.length}\n // The workflows the card HOLDS. Not `workflowCount`, which is the\n // site's total including soft-deleted rows and answers the quota's\n // question rather than the reader's.\n count={workflows.length}\n onPageChange={setPage}\n onPageSizeChange={setPageSize}\n />\n )}\n {workflowsTruncated ? (\n <Alert severity=\"info\">\n {`Showing ${WORKFLOW_CEILING} workflows, ordered by id. This site ` +\n 'has more — the duplicate-name check below only covers the ' +\n 'ones listed here, so a name may already be taken by one that ' +\n 'is not.'}\n </Alert>\n ) : null}\n <Button\n size=\"small\"\n color=\"primary\"\n sx={{ alignSelf: 'flex-start' }}\n onClick={handleAdd}\n >\n {'Add workflow'}\n </Button>\n {/* The cap, standing rather than only on refusal (AGL-2113).\n `workflowCount` is the server aggregate the gate uses, not\n `workflows.length` — the listener is `limit(100)` and its length\n saturates (AGL-1716). */}\n <QuotaReadoutComponent\n ready={org != null}\n used={workflowCount}\n limit={checkQuota(org, 'workflowsPerHost', workflowCount).limit}\n noun=\"workflow\"\n />\n </Stack>\n\n <Dialog\n open={Boolean(draft)}\n onClose={() => setDraft(null)}\n maxWidth=\"sm\"\n fullWidth\n >\n <DialogTitle>\n {draft?.id ? 'Edit Workflow' : 'Add Workflow'}\n </DialogTitle>\n <DialogContent\n sx={{ display: 'flex', flexDirection: 'column', gap: 1.5, pt: 1 }}\n >\n {ExtensionZone && editorTarget ? (\n <ExtensionZone\n slot={AUTOMATION_EDITOR_ZONE.id}\n hostId={hostId}\n orgId={org?.$id}\n target={editorTarget}\n />\n ) : null}\n <TextField\n label=\"Name\"\n helperText={\n nameTaken\n ? 'A workflow with this name already exists'\n : 'Used to identify the workflow'\n }\n error={nameTaken}\n value={draft?.name ?? ''}\n onChange={(event) =>\n patch((previous) => ({ ...previous, name: event.target.value }))\n }\n size=\"small\"\n autoFocus\n sx={{ mt: 1 }}\n />\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Steps'}\n </Typography>\n {/*\n The pickers and the test run speak only for what was read. A step\n calling a function past the ceiling still RUNS on the site — this\n editor simply cannot name it, and a test run resolves its\n expression against an incomplete variable set.\n */}\n {shortLists.length > 0 ? (\n <Alert severity=\"info\">\n {`Offering the first ${EDITOR_OPTION_CEILING} ` +\n `${shortLists.join(', ')} on this site, ordered by id. ` +\n 'There are more, so the pickers below are short and a test ' +\n 'run may not resolve every expression.'}\n </Alert>\n ) : null}\n {(draft?.steps ?? []).map((step, index) => {\n const call = isWorkflowActionStep(step)\n ? null\n : (step as HostWorkflowStep)\n const definition = call\n ? (functions[(call as any).functionId ?? ''] ??\n functions[call.functionName])\n : null\n return (\n <AutomationStepFields\n key={index}\n /*\n * The editor speaks the Actions vocabulary. A function call\n * has no Actions type, so it takes none of those fields and\n * renders its own through `fields` instead — which is what\n * keeps this one editor rather than two.\n */\n step={step as HostActionStep}\n index={index}\n kind={call ? FUNCTION_CALL_KIND : (step as HostActionStep).type}\n kinds={STEP_KINDS}\n stepForKind={(value) =>\n (value === FUNCTION_CALL_KIND\n ? { functionName: '', args: [], resultName: '' }\n : defaultStep(\n value as HostActionStepType,\n )) as HostActionStep\n }\n pickers={stepPickers}\n onSteps={(update) =>\n patch((previous) => ({\n ...previous,\n steps: update(\n previous.steps as HostActionStep[],\n ) as WorkflowStep[],\n }))\n }\n fields={\n call ? (\n <Stack\n direction=\"row\"\n spacing={1}\n sx={{ alignItems: 'center', flex: 1, flexWrap: 'wrap' }}\n >\n <TextField\n label=\"Function\"\n // Stored by id (AGL-261); legacy steps carry only the\n // name and resolve through the double-keyed map.\n value={\n (call as any).functionId ??\n (functions[call.functionName] as any)?.$id ??\n ''\n }\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n functionId: event.target.value,\n functionName:\n functionOptions.find(\n (option) =>\n option.id === event.target.value,\n )?.name ??\n (s as HostWorkflowStep).functionName,\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 160, flex: 1 }}\n >\n {functionOptions.map((option) => (\n <MenuItem key={option.id} value={option.id}>\n {option.name}\n </MenuItem>\n ))}\n </TextField>\n <TextField\n label=\"Result name\"\n placeholder={`step${index + 1}`}\n value={call.resultName ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) =>\n index2 === index\n ? {\n ...s,\n resultName: event.target.value.replace(\n /[^a-zA-Z0-9_]/g,\n '',\n ),\n }\n : s,\n ),\n }))\n }\n size=\"small\"\n sx={{ width: 140 }}\n />\n {(definition?.parameters ?? []).map(\n (parameter, parameterIndex) => (\n <TextField\n key={parameter.name}\n label={`${parameter.name} expression`}\n placeholder={\n parameterIndex === 0 && index > 0\n ? `step${index}`\n : 'a variable, number, or expression'\n }\n value={call.args?.[parameterIndex] ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n steps: previous.steps.map((s, index2) => {\n if (index2 !== index) return s\n const args = [\n ...((s as HostWorkflowStep).args ?? []),\n ]\n args[parameterIndex] = event.target.value\n return { ...s, args }\n }),\n }))\n }\n size=\"small\"\n sx={{ minWidth: 180, flex: 1 }}\n />\n ),\n )}\n </Stack>\n ) : undefined\n }\n />\n )\n })}\n <Button\n size=\"small\"\n sx={{ alignSelf: 'flex-start' }}\n disabled={(draft?.steps.length ?? 0) >= WORKFLOW_MAX_STEPS}\n onClick={() =>\n patch((previous) => ({\n ...previous,\n steps: [\n ...previous.steps,\n { functionName: '', args: [], resultName: '' },\n ],\n }))\n }\n >\n {'Add step'}\n </Button>\n <Typography variant=\"overline\" color=\"text.secondary\">\n {'Trigger'}\n </Typography>\n <Stack direction=\"row\" spacing={1}>\n <TextField\n label=\"Run on event\"\n value={draft?.trigger?.event ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: event.target.value\n ? {\n event: event.target.value as any,\n filter: previous.trigger?.filter ?? '',\n }\n : null,\n }))\n }\n size=\"small\"\n select\n sx={{ minWidth: 180 }}\n >\n <MenuItem value=\"\">{'Manual only'}</MenuItem>\n {HOST_EVENT_TYPES.map((eventType) => (\n <MenuItem key={eventType} value={eventType}>\n {hostEventLabel(eventType)}\n </MenuItem>\n ))}\n </TextField>\n {draft?.trigger ? (\n <TextField\n label=\"Filter (optional)\"\n placeholder={'path == \"/pricing\"'}\n helperText={[\n 'Runs only when this expression is truthy.',\n hostEventPayloadHint(draft?.trigger?.event),\n ]\n .filter(Boolean)\n .join(' ')}\n value={draft?.trigger?.filter ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n trigger: previous.trigger\n ? { ...previous.trigger, filter: event.target.value }\n : previous.trigger,\n }))\n }\n size=\"small\"\n sx={{ flex: 1 }}\n />\n ) : null}\n </Stack>\n <TextField\n label=\"Return value\"\n helperText=\"A step result name; defaults to the last step\"\n value={draft?.returnValue ?? ''}\n onChange={(event) =>\n patch((previous) => ({\n ...previous,\n returnValue: event.target.value,\n }))\n }\n size=\"small\"\n />\n <Stack direction=\"row\" spacing={1} sx={{ alignItems: 'center' }}>\n <Button size=\"small\" color=\"primary\" onClick={handleTestRun}>\n {'Test run'}\n </Button>\n <Typography variant=\"caption\" color=\"text.secondary\">\n {'Uses current variable values'}\n </Typography>\n </Stack>\n {testResult ? (\n <Alert\n severity={testResult.startsWith('Error') ? 'warning' : 'success'}\n >\n {testResult}\n </Alert>\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button onClick={() => setDraft(null)}>{'Cancel'}</Button>\n <Button\n variant=\"contained\"\n color=\"primary\"\n disabled={!draft?.name.trim() || nameTaken}\n onClick={handleSave}\n >\n {'Done'}\n </Button>\n </DialogActions>\n </Dialog>\n {ExtensionZone ? (\n <ExtensionZone\n slot={WORKFLOW_USAGE_ZONE.id}\n hostId={hostId}\n usage={usage}\n onClose={() => setUsage(null)}\n />\n ) : null}\n <Dialog\n open={Boolean(runsFor)}\n onClose={() => setRunsFor(null)}\n // md: the history's four columns fit without the table scrolling.\n maxWidth=\"md\"\n fullWidth\n >\n <DialogTitle>{`Runs — ${runsFor?.name ?? ''}`}</DialogTitle>\n <DialogContent>\n {runsFor ? (\n <HostRunHistoryCard\n hostId={hostId}\n orgId={org?.$id}\n targetId={runsFor.$id}\n targetType=\"workflow\"\n targetName={runsFor.name ?? ''}\n header=\"Recent runs\"\n />\n ) : null}\n </DialogContent>\n <DialogActions>\n <Button color=\"inherit\" onClick={() => setRunsFor(null)}>\n {'Close'}\n </Button>\n </DialogActions>\n </Dialog>\n </CardDisplay>\n )\n}\nHostWorkflowsCard.displayName = 'HostWorkflowsCard'\n\nexport default HostWorkflowsCard\n"],"names":["checkEntitlement","checkQuota","HOST_EVENT_TYPES","hostEventLabel","hostEventPayloadHint","pluginDocsHelp","ceilingedWindow","collectionCeiling","useConsoleWidgetSlot","CardDisplay","useConfirmationContext","ListPagination","TABLE_PAGE_SIZE_DEFAULT","QuotaReadoutComponent","useSnackbar","Timestamp","Alert","Button","Dialog","DialogActions","DialogContent","DialogTitle","MenuItem","Stack","TextField","Typography","collection","doc","getCountFromServer","setDoc","updateDoc","useCallback","useEffect","useMemo","useState","useDuplicateResource","useFirestore","useFirestoreCollection","useHostResourceApi","useUser","writeGuardedBySeed","AutomationStepFields","defaultStep","isWorkflowActionStep","validateWorkflowSteps","WORKFLOW_ACTION_STEP_TYPES","workflowFunctionCalls","workflowStepTypeLabel","HostRunHistoryCard","EDITOR_OPTION_CEILING","useAutomationStepPickers","listConsoleWidgets","fetchWhereUsed","summarizeDependents","AUTOMATION_EDITOR_ZONE","WORKFLOW_USAGE_ZONE","runWorkflow","WORKFLOW_MAX_STEPS","WORKFLOW_CEILING","FUNCTION_CALL_KIND","STEP_KINDS","value","label","map","HostWorkflowsCard","props","runsFor","draft","hostId","firestore","data","user","createHostResource","enqueueSnackbar","duplicate","onDuplicated","_kind","copy","name","variant","confirm","org","ExtensionZone","workflowDocs","status","workflowsStatus","fromCache","workflowsFromCache","idField","rows","readWorkflows","truncated","workflowsTruncated","setDraft","editorOpened","setEditorOpened","functionRead","functionDocs","functionsTruncated","variableRead","variableDocs","variablesTruncated","pickers","stepPickers","truncatedPickers","workflows","filter","workflow","deletedAt","sort","a","b","String","localeCompare","page","setPage","pageSize","setPageSize","visibleWorkflows","slice","workflowCountEpoch","setWorkflowCountEpoch","serverWorkflowCount","setServerWorkflowCount","active","then","snapshot","count","catch","workflowCount","length","functions","definition","$id","functionOptions","id","variables","variable","usage","setUsage","usageLoading","setUsageLoading","testResult","setTestResult","setRunsFor","nameTaken","Boolean","some","toLowerCase","trim","patch","updater","previous","draftId","draftName","editorTarget","type","handleAdd","persist","quota","allowed","limit","steps","functionName","args","resultName","returnValue","trigger","shortLists","stepProblem","handleTestRun","run","ok","error","Object","entries","results","key","join","handleSave","fields","verdict","subject","unreadable","updatedAt","now","merge","message","resource","epoch","console","allowDuplicate","handleShowUsage","result","kind","total","handleDelete","scan","confirmed","title","description","confirmationText","confirmationButtonProps","color","header","help","anchor","contentGutterX","contentGutterY","dialog","spacing","direction","sx","alignItems","flex","minWidth","noWrap","event","step","size","disabled","onClick","request","rowCount","onPageChange","onPageSizeChange","severity","alignSelf","ready","used","noun","open","onClose","maxWidth","fullWidth","display","flexDirection","gap","pt","slot","orgId","target","helperText","onChange","autoFocus","mt","index","call","functionId","kinds","stepForKind","onSteps","update","flexWrap","s","index2","find","option","select","placeholder","replace","width","parameters","parameter","parameterIndex","undefined","eventType","startsWith","targetId","targetType","targetName","displayName"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;;;;AAEA,SAEEA,gBAAgB,EAChBC,UAAU,EACVC,gBAAgB,EAChBC,cAAc,EACdC,oBAAoB,EAKpBC,cAAc,QACT,eAAc;AACrB;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,oBAAoB,QAAQ,qDAAoD;AACzF,SAASC,WAAW,EAAEC,sBAAsB,QAAQ,uBAAsB;AAC1E,SAASC,cAAc,QAAQ,4DAA2D;AAC1F,SAASC,uBAAuB,QAAQ,8CAA6C;AACr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AACpM;wCAAO0M,MAAK;wCAAQhB,OAAM;wCAAUkB,SAASnD;kDAC3C;;kDAEH,KAACjJ;wCAAWsD,SAAQ;wCAAU4H,OAAM;kDACjC;;;;4BAGJ7D,2BACC,KAAC9H;gCACCkN,UAAUpF,WAAW6H,UAAU,CAAC,WAAW,YAAY;0CAEtD7H;iCAED;;;kCAEN,MAAC3H;;0CACC,KAACF;gCAAO4M,SAAS,IAAMhI,SAAS;0CAAQ;;0CACxC,KAAC5E;gCACC8D,SAAQ;gCACR4H,OAAM;gCACNiB,UAAU,EAACzJ,yBAAAA,MAAOW,IAAI,CAACuE,IAAI,OAAMJ;gCACjC4E,SAAS1C;0CAER;;;;;;YAINjG,8BACC,KAACA;gBACC6J,MAAMxL,oBAAoBgF,EAAE;gBAC5BnE,QAAQA;gBACRsE,OAAOA;gBACP8F,SAAS,IAAM7F,SAAS;iBAExB;0BACJ,MAACzH;gBACCqN,MAAMrF,QAAQhF;gBACdsK,SAAS,IAAMxF,WAAW;gBAC1B,kEAAkE;gBAClEyF,UAAS;gBACTC,SAAS;;kCAET,KAACrN;kCAAa,CAAC,OAAO,WAAE6C,2BAAAA,QAASY,IAAI,oBAAI,IAAI;;kCAC7C,KAAC1D;kCACE8C,wBACC,KAAClB;4BACCoB,QAAQA;4BACR4K,KAAK,EAAE/J,uBAAAA,IAAKoD,GAAG;4BACfuI,UAAU1M,QAAQmE,GAAG;4BACrBwI,YAAW;4BACXC,UAAU,GAAE5M,gBAAAA,QAAQY,IAAI,YAAZZ,gBAAgB;4BAC5B0I,QAAO;6BAEP;;kCAEN,KAACzL;kCACC,cAAA,KAACF;4BAAO0L,OAAM;4BAAUkB,SAAS,IAAM7E,WAAW;sCAC/C;;;;;;;AAMb;AACAhF,kBAAkB+M,WAAW,GAAG;AAEhC,eAAe/M,kBAAiB"}
|
|
@@ -22,7 +22,8 @@
|
|
|
22
22
|
* collections, at the same ceiling, on the same latch. Two copies would be two
|
|
23
23
|
* read costs to keep in agreement, and the console's read-cost spec measures
|
|
24
24
|
* both surfaces against this one set.
|
|
25
|
-
*/ import {
|
|
25
|
+
*/ import { scopeTokensForHost } from "@aglyn/aglyn";
|
|
26
|
+
import { pluginContainerKind } from "@aglyn/aglyn/plugin-manager/plugin-containers";
|
|
26
27
|
import { useFirestore, useFirestoreCollection, useOrgDataScope } from "@aglyn/tenant-feature-instance";
|
|
27
28
|
/*
|
|
28
29
|
* The MODULE, not the barrel, for the two PURE helpers — the cards' specs
|
|
@@ -30,7 +31,8 @@ import { useFirestore, useFirestoreCollection, useOrgDataScope } from "@aglyn/te
|
|
|
30
31
|
* hooks, and a query builder imported through that barrel disappears under
|
|
31
32
|
* the mock. Neither of these is a hook.
|
|
32
33
|
*/ import { ceilingedWindow, collectionCeiling } from "@aglyn/tenant-feature-instance/hooks/host-collection-queries";
|
|
33
|
-
import { collection,
|
|
34
|
+
import { collection, query, where } from "firebase/firestore";
|
|
35
|
+
import { pluginRecordListQuery, pluginRecordsFromRows } from "@aglyn/aglyn/plugin-manager/plugin-record-lists";
|
|
34
36
|
import { useMemo } from "react";
|
|
35
37
|
/**
|
|
36
38
|
* How many rows each of the step editor's six pickers offers.
|
|
@@ -50,6 +52,8 @@ import { useMemo } from "react";
|
|
|
50
52
|
* again on the next Edit, so an author working through ten automations would
|
|
51
53
|
* pay for the same six windows ten times.
|
|
52
54
|
*/ export function useAutomationStepPickers(hostId, editorOpened) {
|
|
55
|
+
var _ref;
|
|
56
|
+
var _pluginContainerKind;
|
|
53
57
|
const firestore = useFirestore();
|
|
54
58
|
const { scope: dataScope } = useOrgDataScope({
|
|
55
59
|
hostId
|
|
@@ -76,45 +80,46 @@ import { useMemo } from "react";
|
|
|
76
80
|
idField: '$id'
|
|
77
81
|
});
|
|
78
82
|
const { rows: workflowDocs, truncated: workflowsTruncated } = ceilingedWindow(workflowRead, EDITOR_OPTION_CEILING);
|
|
79
|
-
// Scoped (AGL-1044):
|
|
80
|
-
//
|
|
81
|
-
//
|
|
82
|
-
//
|
|
83
|
-
//
|
|
84
|
-
//
|
|
85
|
-
// AGL-1041 rules, since they are a subset of any viewer's who can reach
|
|
86
|
-
// this host at all.
|
|
83
|
+
// Scoped to the HOST, not the viewer (AGL-1044): an action runs ON this
|
|
84
|
+
// host, so it may only reach org records THIS host can use — an org-wide
|
|
85
|
+
// admin would otherwise be offered ones that resolve to nothing at render
|
|
86
|
+
// time. Filtering by the host's tokens also satisfies the AGL-1041 rules,
|
|
87
|
+
// which reject a scoped member's UNFILTERED list outright, since they are a
|
|
88
|
+
// subset of any viewer's who can reach this host at all.
|
|
87
89
|
// Memoised: this is a listener DEPENDENCY, and a fresh array each
|
|
88
90
|
// render tears the subscription down and clears its data every time.
|
|
89
91
|
const scopeTokens = useMemo(()=>scopeTokensForHost(hostId), [
|
|
90
92
|
hostId
|
|
91
93
|
]);
|
|
92
|
-
//
|
|
93
|
-
//
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
* anything else here would need a composite index that does not exist.
|
|
101
|
-
*/ const { data: datasetRead } = useFirestoreCollection(()=>editorOpened && dataScope ? query(collection(firestore, dataScope[0], dataScope[1], 'datasets'), where('visibleTo', 'array-contains-any', scopeTokens), orderBy(documentId()), limit(EDITOR_OPTION_CEILING + 1)) : null, [
|
|
94
|
+
// The datasets are the data plugin's, listed through the source it
|
|
95
|
+
// publishes (AGL-3080), which applies the same host scoping.
|
|
96
|
+
const datasetOrgId = (_ref = dataScope == null ? void 0 : dataScope[1]) != null ? _ref : null;
|
|
97
|
+
const { data: datasetRead } = useFirestoreCollection(()=>editorOpened && datasetOrgId ? pluginRecordListQuery('dataset', firestore, {
|
|
98
|
+
orgId: datasetOrgId,
|
|
99
|
+
hostId,
|
|
100
|
+
limit: EDITOR_OPTION_CEILING + 1
|
|
101
|
+
}) : null, [
|
|
102
102
|
firestore,
|
|
103
|
-
|
|
104
|
-
|
|
103
|
+
datasetOrgId,
|
|
104
|
+
hostId,
|
|
105
105
|
editorOpened
|
|
106
106
|
], {
|
|
107
107
|
idField: '$id'
|
|
108
108
|
});
|
|
109
|
-
const { rows:
|
|
110
|
-
|
|
109
|
+
const { rows: datasetRows, truncated: datasetsTruncated } = ceilingedWindow(datasetRead, EDITOR_OPTION_CEILING);
|
|
110
|
+
// The site's overlays are the marketing plugin's, listed through the
|
|
111
|
+
// source it publishes (AGL-3080); none where no plugin keeps them here.
|
|
112
|
+
const { data: overlayRead } = useFirestoreCollection(()=>editorOpened ? pluginRecordListQuery('overlay', firestore, {
|
|
113
|
+
hostId,
|
|
114
|
+
limit: EDITOR_OPTION_CEILING + 1
|
|
115
|
+
}) : null, [
|
|
111
116
|
firestore,
|
|
112
117
|
hostId,
|
|
113
118
|
editorOpened
|
|
114
119
|
], {
|
|
115
120
|
idField: '$id'
|
|
116
121
|
});
|
|
117
|
-
const { rows:
|
|
122
|
+
const { rows: overlayRows, truncated: overlaysTruncated } = ceilingedWindow(overlayRead, EDITOR_OPTION_CEILING);
|
|
118
123
|
// Lists live on the org (AGL-254), and so do campaigns.
|
|
119
124
|
const { data: listRead } = useFirestoreCollection(()=>editorOpened && dataScope ? collectionCeiling(collection(firestore, dataScope[0], dataScope[1], 'lists'), EDITOR_OPTION_CEILING) : null, [
|
|
120
125
|
firestore,
|
|
@@ -125,21 +130,24 @@ import { useMemo } from "react";
|
|
|
125
130
|
});
|
|
126
131
|
const { rows: listDocs, truncated: listsTruncated } = ceilingedWindow(listRead, EDITOR_OPTION_CEILING);
|
|
127
132
|
/*
|
|
128
|
-
* The campaign CONTAINERS
|
|
129
|
-
*
|
|
130
|
-
*
|
|
131
|
-
*
|
|
132
|
-
* run with "unknown campaign".
|
|
133
|
+
* The campaign CONTAINERS — the `campaign` container kind, read where its
|
|
134
|
+
* declaration says they are stored — which the executor resolves an
|
|
135
|
+
* "Assign to a campaign" step's `campaignId` against when it runs
|
|
136
|
+
* (AGL-3052). A send's id names no container, so a step pointed at one
|
|
137
|
+
* fails every run with "unknown campaign". Nothing is read where no plugin
|
|
138
|
+
* keeps the kind.
|
|
133
139
|
*
|
|
134
140
|
* The org's, narrowed to the ones placed on THIS site by the same host
|
|
135
141
|
* tokens the datasets use — an automation runs on this site, so it may
|
|
136
142
|
* only file under a campaign the site offers, and the clause is what
|
|
137
143
|
* makes the list provable for a collaborator scoped to the site.
|
|
138
|
-
*/ const
|
|
144
|
+
*/ const campaignCollection = (_pluginContainerKind = pluginContainerKind('campaign')) == null ? void 0 : _pluginContainerKind.orgCollection;
|
|
145
|
+
const { data: campaignRead } = useFirestoreCollection(()=>editorOpened && dataScope && campaignCollection ? collectionCeiling(query(collection(firestore, dataScope[0], dataScope[1], campaignCollection), where('visibleTo', 'array-contains-any', scopeTokens)), EDITOR_OPTION_CEILING) : null, [
|
|
139
146
|
firestore,
|
|
140
147
|
dataScope,
|
|
141
148
|
scopeTokens,
|
|
142
|
-
editorOpened
|
|
149
|
+
editorOpened,
|
|
150
|
+
campaignCollection
|
|
143
151
|
], {
|
|
144
152
|
idField: '$id'
|
|
145
153
|
});
|
|
@@ -172,16 +180,16 @@ import { useMemo } from "react";
|
|
|
172
180
|
id: workflow.$id,
|
|
173
181
|
name: workflow.name
|
|
174
182
|
})).sort((a, b)=>a.name.localeCompare(b.name));
|
|
175
|
-
//
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
183
|
+
// Named as the Data page names them, by their owner.
|
|
184
|
+
const datasetOptions = pluginRecordsFromRows('dataset', datasetRows).map((dataset)=>({
|
|
185
|
+
id: dataset.id,
|
|
186
|
+
name: dataset.name
|
|
187
|
+
})).sort((a, b)=>a.name.localeCompare(b.name));
|
|
188
|
+
// Named as the Marketing page names them, by their owner.
|
|
189
|
+
const overlayOptions = pluginRecordsFromRows('overlay', overlayRows).map((overlay)=>({
|
|
190
|
+
id: overlay.id,
|
|
191
|
+
name: overlay.name
|
|
192
|
+
})).sort((a, b)=>a.name.localeCompare(b.name));
|
|
185
193
|
const listOptions = (listDocs != null ? listDocs : []).filter((list)=>!list.deletedAt && list.name).map((list)=>({
|
|
186
194
|
id: list.$id,
|
|
187
195
|
name: list.name
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/use-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\n/**\n * WHAT A STEP CAN BE POINTED AT, read once per editor (AGL-3105).\n *\n * The step fields are shared by the Actions builder and the Workflows builder,\n * so what fills their pickers is read in one place too — the same six\n * collections, at the same ceiling, on the same latch. Two copies would be two\n * read costs to keep in agreement, and the console's read-cost spec measures\n * both surfaces against this one set.\n */\n\nimport { datasetPickerOptions, scopeTokensForHost } from '@aglyn/aglyn'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\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 to stage their Firestore\n * hooks, and a query builder imported through that barrel disappears under\n * the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport {\n collection,\n documentId,\n limit,\n orderBy,\n query,\n where,\n} from 'firebase/firestore'\nimport { useMemo } from 'react'\nimport type { AutomationStepPickers } from './automation-step-fields.component'\n\n/**\n * How many rows each of the step editor's six pickers offers.\n *\n * One number for all six because they are read together, by the same click,\n * and a reader comparing two of them should not have to know which one was cut\n * at fifty. Paid for only while the editor is open, which is what makes a\n * ceiling this size affordable: one author mid-edit rather than every visitor\n * to the page.\n */\nexport const EDITOR_OPTION_CEILING = 100\n\n/** The pickers a step editor offers, and which of them the ceiling bit. */\nexport interface AutomationStepPickerData {\n pickers: AutomationStepPickers\n /** The lists that ran short, named as the editor's notice names them. */\n truncated: string[]\n}\n\n/**\n * The records a step can be pointed at on this site, read when the editor\n * that offers them is first opened.\n *\n * `editorOpened` is a LATCH the card holds, never the open dialog: keyed on\n * the dialog these subscriptions would be torn down on Cancel and bought\n * again on the next Edit, so an author working through ten automations would\n * pay for the same six windows ten times.\n */\nexport function useAutomationStepPickers(\n hostId: string,\n editorOpened: boolean,\n): AutomationStepPickerData {\n const firestore = useFirestore()\n const { scope: dataScope } = useOrgDataScope({ hostId })\n /*\n * THE STEP EDITOR'S OPTION LISTS, read when the editor opens.\n *\n * Six collections, and nothing outside the dialog below reads any of them:\n * the table renders a step's stored name, never one looked up here. Mounting\n * them unconditionally charges every visitor to this page six windows to\n * populate selects most of them never open — the largest read on the\n * automation surface, paid whether or not anybody edits anything.\n *\n * Each is ceilinged and ordered for the reason the actions query above\n * gives: a bare `limit` is answered in document-id order, so the\n * `localeCompare` on every option list would arrange a pseudo-random sample\n * into a convincing alphabet, and a workflow or dataset past the window\n * could not be picked with nothing saying why.\n */\n const { data: workflowRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'workflows'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: workflowDocs, truncated: workflowsTruncated } =\n ceilingedWindow<any>(workflowRead, EDITOR_OPTION_CEILING)\n // Scoped (AGL-1044): the AGL-1041 rules reject a scoped member's\n // UNFILTERED list outright, so without this the picker errors rather than\n // offering fewer datasets.\n // Scoped to the HOST, not the viewer (AGL-1044): an action runs ON this host, so it may only reach datasets THIS host can use — an org-wide\n // admin would otherwise be offered datasets that resolve to nothing at\n // render time. Filtering by the host's tokens also satisfies the\n // AGL-1041 rules, since they are a subset of any viewer's who can reach\n // this host at all.\n // Memoised: this is a listener DEPENDENCY, and a fresh array each\n // render tears the subscription down and clears its data every time.\n const scopeTokens = useMemo(() => scopeTokensForHost(hostId), [hostId])\n // Unconditional now: the only scope this hook yields is an org one, and\n // every org dataset carries `visibleTo` (AGL-1041). The filter used to be\n // conditional for the host fallback's sake, whose rows had no scope.\n /*\n * `documentId()` rather than a field, for the reason the audience sweep in\n * `campaign-send.ts` gives: Firestore's automatic single-field index for an\n * array member is keyed on the value and the document name, so\n * `array-contains-any` plus `orderBy(__name__)` is served by it. Ordering on\n * anything else here would need a composite index that does not exist.\n */\n const { data: datasetRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && dataScope\n ? query(\n collection(firestore, dataScope[0], dataScope[1], 'datasets'),\n where('visibleTo', 'array-contains-any', scopeTokens),\n orderBy(documentId()),\n limit(EDITOR_OPTION_CEILING + 1),\n )\n : null,\n [firestore, dataScope, scopeTokens, editorOpened],\n { idField: '$id' },\n )\n const { rows: datasetDocs, truncated: datasetsTruncated } =\n ceilingedWindow<any>(datasetRead, EDITOR_OPTION_CEILING)\n const { data: overlayRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'overlays'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: overlayDocs, truncated: overlaysTruncated } =\n ceilingedWindow<any>(overlayRead, EDITOR_OPTION_CEILING)\n // Lists live on the org (AGL-254), and so do campaigns.\n const { data: listRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && dataScope\n ? collectionCeiling(\n collection(firestore, dataScope[0], dataScope[1], 'lists'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, dataScope, editorOpened],\n { idField: '$id' },\n )\n const { rows: listDocs, truncated: listsTruncated } = ceilingedWindow<any>(\n listRead,\n EDITOR_OPTION_CEILING,\n )\n /*\n * The campaign CONTAINERS, `emailCampaigns`: the collection the executor\n * resolves an \"Assign to a campaign\" step's `campaignId` against when it\n * runs (AGL-3052). `campaigns` beside it holds the individual email sends,\n * and a send's id names no container, so a step pointed at one fails every\n * run with \"unknown campaign\".\n *\n * The org's, narrowed to the ones placed on THIS site by the same host\n * tokens the datasets use — an automation runs on this site, so it may\n * only file under a campaign the site offers, and the clause is what\n * makes the list provable for a collaborator scoped to the site.\n */\n const { data: campaignRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && dataScope\n ? collectionCeiling(\n query(\n collection(firestore, dataScope[0], dataScope[1], 'emailCampaigns'),\n where('visibleTo', 'array-contains-any', scopeTokens),\n ),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, dataScope, scopeTokens, editorOpened],\n { idField: '$id' },\n )\n const { rows: campaignDocs, truncated: campaignsTruncated } =\n ceilingedWindow<any>(campaignRead, EDITOR_OPTION_CEILING)\n const { data: webhookRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'webhooks'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: webhookDocs, truncated: webhooksTruncated } =\n ceilingedWindow<any>(webhookRead, EDITOR_OPTION_CEILING)\n /**\n * Which of the six pickers the ceiling actually bit, named.\n *\n * One notice rather than six, because they are one read and an author who\n * has just been told the workflow list is short does not learn anything from\n * being told again about datasets.\n */\n const truncatedPickers = [\n workflowsTruncated ? 'workflows' : null,\n webhooksTruncated ? 'webhooks' : null,\n datasetsTruncated ? 'datasets' : null,\n overlaysTruncated ? 'overlays' : null,\n listsTruncated ? 'audiences' : null,\n campaignsTruncated ? 'campaigns' : null,\n ].filter((name): name is string => name !== null)\n // Options carry ids (AGL-261): selects store the doc id, keep the name\n // as the display hint, and legacy name-only steps map back to their id.\n const workflowOptions = (workflowDocs ?? [])\n .filter((workflow: any) => !workflow.deletedAt && workflow.name)\n .map((workflow: any) => ({\n id: workflow.$id as string,\n name: workflow.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n // Labeled by `displayName`, which every create path writes; the legacy\n // `name` only covers pre-migration documents.\n const datasetOptions = datasetPickerOptions(datasetDocs)\n const overlayOptions = (overlayDocs ?? [])\n .filter((overlay: any) => !overlay.deletedAt)\n .map((overlay: any) => ({\n id: overlay.$id as string,\n name: (overlay.name ||\n overlay.bar?.text ||\n overlay.popup?.headline ||\n overlay.$id) as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n const listOptions = (listDocs ?? [])\n .filter((list: any) => !list.deletedAt && list.name)\n .map((list: any) => ({\n id: list.$id as string,\n name: list.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n const campaignOptions = (campaignDocs ?? [])\n .filter((campaign: any) => !campaign.deletedAt && campaign.name)\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 const webhookOptions = (webhookDocs ?? [])\n .filter(\n (hook: any) =>\n !hook.deletedAt && hook.name && hook.direction === 'outbound',\n )\n .map((hook: any) => ({\n id: hook.$id as string,\n name: hook.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n\n /** The records this site offers every step picker in the editor. */\n const stepPickers: AutomationStepPickers = {\n workflowOptions,\n datasetOptions,\n overlayOptions,\n listOptions,\n campaignOptions,\n webhookOptions,\n }\n return { pickers: stepPickers, truncated: truncatedPickers }\n}\n"],"names":["datasetPickerOptions","scopeTokensForHost","useFirestore","useFirestoreCollection","useOrgDataScope","ceilingedWindow","collectionCeiling","collection","documentId","limit","orderBy","query","where","useMemo","EDITOR_OPTION_CEILING","useAutomationStepPickers","hostId","editorOpened","firestore","scope","dataScope","data","workflowRead","idField","rows","workflowDocs","truncated","workflowsTruncated","scopeTokens","datasetRead","datasetDocs","datasetsTruncated","overlayRead","overlayDocs","overlaysTruncated","listRead","listDocs","listsTruncated","campaignRead","campaignDocs","campaignsTruncated","webhookRead","webhookDocs","webhooksTruncated","truncatedPickers","filter","name","workflowOptions","workflow","deletedAt","map","id","$id","sort","a","b","localeCompare","datasetOptions","overlayOptions","overlay","bar","text","popup","headline","listOptions","list","campaignOptions","campaign","webhookOptions","hook","direction","stepPickers","pickers"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA;;;;;;;;CAQC,GAED,SAASA,oBAAoB,EAAEC,kBAAkB,QAAQ,eAAc;AACvE,SACEC,YAAY,EACZC,sBAAsB,EACtBC,eAAe,QACV,iCAAgC;AACvC;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SACEC,UAAU,EACVC,UAAU,EACVC,KAAK,EACLC,OAAO,EACPC,KAAK,EACLC,KAAK,QACA,qBAAoB;AAC3B,SAASC,OAAO,QAAQ,QAAO;AAG/B;;;;;;;;CAQC,GACD,OAAO,MAAMC,wBAAwB,IAAG;AASxC;;;;;;;;CAQC,GACD,OAAO,SAASC,yBACdC,MAAc,EACdC,YAAqB;IAErB,MAAMC,YAAYhB;IAClB,MAAM,EAAEiB,OAAOC,SAAS,EAAE,GAAGhB,gBAAgB;QAAEY;IAAO;IACtD;;;;;;;;;;;;;;GAcC,GACD,MAAM,EAAEK,MAAMC,YAAY,EAAE,GAAGnB,uBAC7B,IACEc,eACIX,kBACEC,WAAWW,WAAW,SAASF,QAAQ,cACvCF,yBAEF,MACN;QAACI;QAAWF;QAAQC;KAAa,EACjC;QAAEM,SAAS;IAAM;IAEnB,MAAM,EAAEC,MAAMC,YAAY,EAAEC,WAAWC,kBAAkB,EAAE,GACzDtB,gBAAqBiB,cAAcR;IACrC,iEAAiE;IACjE,0EAA0E;IAC1E,2BAA2B;IAC3B,4IAA4I;IAC5I,uEAAuE;IACvE,iEAAiE;IACjE,wEAAwE;IACxE,oB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CAAA,GACCO,IAAI,CAAC,CAACC,GAAGC,IAAMD,EAAER,IAAI,CAACU,aAAa,CAACD,EAAET,IAAI;IAE7C,kEAAkE,GAClE,MAAMyB,cAAqC;QACzCxB;QACAU;QACAC;QACAM;QACAE;QACAE;IACF;IACA,OAAO;QAAEI,SAASD;QAAa7C,WAAWkB;IAAiB;AAC7D"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../../libs/plugins/workflows/src/lib/components/use-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\n/**\n * WHAT A STEP CAN BE POINTED AT, read once per editor (AGL-3105).\n *\n * The step fields are shared by the Actions builder and the Workflows builder,\n * so what fills their pickers is read in one place too — the same six\n * collections, at the same ceiling, on the same latch. Two copies would be two\n * read costs to keep in agreement, and the console's read-cost spec measures\n * both surfaces against this one set.\n */\n\nimport { scopeTokensForHost } from '@aglyn/aglyn'\nimport { pluginContainerKind } from '@aglyn/aglyn/plugin-manager/plugin-containers'\nimport {\n useFirestore,\n useFirestoreCollection,\n useOrgDataScope,\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 to stage their Firestore\n * hooks, and a query builder imported through that barrel disappears under\n * the mock. Neither of these is a hook.\n */\nimport {\n ceilingedWindow,\n collectionCeiling,\n} from '@aglyn/tenant-feature-instance/hooks/host-collection-queries'\nimport { collection, query, where } from 'firebase/firestore'\nimport {\n pluginRecordListQuery,\n pluginRecordsFromRows,\n} from '@aglyn/aglyn/plugin-manager/plugin-record-lists'\nimport { useMemo } from 'react'\nimport type { AutomationStepPickers } from './automation-step-fields.component'\n\n/**\n * How many rows each of the step editor's six pickers offers.\n *\n * One number for all six because they are read together, by the same click,\n * and a reader comparing two of them should not have to know which one was cut\n * at fifty. Paid for only while the editor is open, which is what makes a\n * ceiling this size affordable: one author mid-edit rather than every visitor\n * to the page.\n */\nexport const EDITOR_OPTION_CEILING = 100\n\n/** The pickers a step editor offers, and which of them the ceiling bit. */\nexport interface AutomationStepPickerData {\n pickers: AutomationStepPickers\n /** The lists that ran short, named as the editor's notice names them. */\n truncated: string[]\n}\n\n/**\n * The records a step can be pointed at on this site, read when the editor\n * that offers them is first opened.\n *\n * `editorOpened` is a LATCH the card holds, never the open dialog: keyed on\n * the dialog these subscriptions would be torn down on Cancel and bought\n * again on the next Edit, so an author working through ten automations would\n * pay for the same six windows ten times.\n */\nexport function useAutomationStepPickers(\n hostId: string,\n editorOpened: boolean,\n): AutomationStepPickerData {\n const firestore = useFirestore()\n const { scope: dataScope } = useOrgDataScope({ hostId })\n /*\n * THE STEP EDITOR'S OPTION LISTS, read when the editor opens.\n *\n * Six collections, and nothing outside the dialog below reads any of them:\n * the table renders a step's stored name, never one looked up here. Mounting\n * them unconditionally charges every visitor to this page six windows to\n * populate selects most of them never open — the largest read on the\n * automation surface, paid whether or not anybody edits anything.\n *\n * Each is ceilinged and ordered for the reason the actions query above\n * gives: a bare `limit` is answered in document-id order, so the\n * `localeCompare` on every option list would arrange a pseudo-random sample\n * into a convincing alphabet, and a workflow or dataset past the window\n * could not be picked with nothing saying why.\n */\n const { data: workflowRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'workflows'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: workflowDocs, truncated: workflowsTruncated } =\n ceilingedWindow<any>(workflowRead, EDITOR_OPTION_CEILING)\n // Scoped to the HOST, not the viewer (AGL-1044): an action runs ON this\n // host, so it may only reach org records THIS host can use — an org-wide\n // admin would otherwise be offered ones that resolve to nothing at render\n // time. Filtering by the host's tokens also satisfies the AGL-1041 rules,\n // which reject a scoped member's UNFILTERED list outright, since they are a\n // subset of any viewer's who can reach this host at all.\n // Memoised: this is a listener DEPENDENCY, and a fresh array each\n // render tears the subscription down and clears its data every time.\n const scopeTokens = useMemo(() => scopeTokensForHost(hostId), [hostId])\n // The datasets are the data plugin's, listed through the source it\n // publishes (AGL-3080), which applies the same host scoping.\n const datasetOrgId = dataScope?.[1] ?? null\n const { data: datasetRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && datasetOrgId\n ? pluginRecordListQuery('dataset', firestore, {\n orgId: datasetOrgId,\n hostId,\n limit: EDITOR_OPTION_CEILING + 1,\n })\n : null,\n [firestore, datasetOrgId, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: datasetRows, truncated: datasetsTruncated } =\n ceilingedWindow<any>(datasetRead, EDITOR_OPTION_CEILING)\n // The site's overlays are the marketing plugin's, listed through the\n // source it publishes (AGL-3080); none where no plugin keeps them here.\n const { data: overlayRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? pluginRecordListQuery('overlay', firestore, {\n hostId,\n limit: EDITOR_OPTION_CEILING + 1,\n })\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: overlayRows, truncated: overlaysTruncated } =\n ceilingedWindow<any>(overlayRead, EDITOR_OPTION_CEILING)\n // Lists live on the org (AGL-254), and so do campaigns.\n const { data: listRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && dataScope\n ? collectionCeiling(\n collection(firestore, dataScope[0], dataScope[1], 'lists'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, dataScope, editorOpened],\n { idField: '$id' },\n )\n const { rows: listDocs, truncated: listsTruncated } = ceilingedWindow<any>(\n listRead,\n EDITOR_OPTION_CEILING,\n )\n /*\n * The campaign CONTAINERS — the `campaign` container kind, read where its\n * declaration says they are stored — which the executor resolves an\n * \"Assign to a campaign\" step's `campaignId` against when it runs\n * (AGL-3052). A send's id names no container, so a step pointed at one\n * fails every run with \"unknown campaign\". Nothing is read where no plugin\n * keeps the kind.\n *\n * The org's, narrowed to the ones placed on THIS site by the same host\n * tokens the datasets use — an automation runs on this site, so it may\n * only file under a campaign the site offers, and the clause is what\n * makes the list provable for a collaborator scoped to the site.\n */\n const campaignCollection = pluginContainerKind('campaign')?.orgCollection\n const { data: campaignRead } = useFirestoreCollection<any>(\n () =>\n editorOpened && dataScope && campaignCollection\n ? collectionCeiling(\n query(\n collection(firestore, dataScope[0], dataScope[1], campaignCollection),\n where('visibleTo', 'array-contains-any', scopeTokens),\n ),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, dataScope, scopeTokens, editorOpened, campaignCollection],\n { idField: '$id' },\n )\n const { rows: campaignDocs, truncated: campaignsTruncated } =\n ceilingedWindow<any>(campaignRead, EDITOR_OPTION_CEILING)\n const { data: webhookRead } = useFirestoreCollection<any>(\n () =>\n editorOpened\n ? collectionCeiling(\n collection(firestore, 'hosts', hostId, 'webhooks'),\n EDITOR_OPTION_CEILING,\n )\n : null,\n [firestore, hostId, editorOpened],\n { idField: '$id' },\n )\n const { rows: webhookDocs, truncated: webhooksTruncated } =\n ceilingedWindow<any>(webhookRead, EDITOR_OPTION_CEILING)\n /**\n * Which of the six pickers the ceiling actually bit, named.\n *\n * One notice rather than six, because they are one read and an author who\n * has just been told the workflow list is short does not learn anything from\n * being told again about datasets.\n */\n const truncatedPickers = [\n workflowsTruncated ? 'workflows' : null,\n webhooksTruncated ? 'webhooks' : null,\n datasetsTruncated ? 'datasets' : null,\n overlaysTruncated ? 'overlays' : null,\n listsTruncated ? 'audiences' : null,\n campaignsTruncated ? 'campaigns' : null,\n ].filter((name): name is string => name !== null)\n // Options carry ids (AGL-261): selects store the doc id, keep the name\n // as the display hint, and legacy name-only steps map back to their id.\n const workflowOptions = (workflowDocs ?? [])\n .filter((workflow: any) => !workflow.deletedAt && workflow.name)\n .map((workflow: any) => ({\n id: workflow.$id as string,\n name: workflow.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n // Named as the Data page names them, by their owner.\n const datasetOptions = pluginRecordsFromRows('dataset', datasetRows)\n .map((dataset) => ({ id: dataset.id, name: dataset.name }))\n .sort((a, b) => a.name.localeCompare(b.name))\n // Named as the Marketing page names them, by their owner.\n const overlayOptions = pluginRecordsFromRows('overlay', overlayRows)\n .map((overlay) => ({ id: overlay.id, name: overlay.name }))\n .sort((a, b) => a.name.localeCompare(b.name))\n const listOptions = (listDocs ?? [])\n .filter((list: any) => !list.deletedAt && list.name)\n .map((list: any) => ({\n id: list.$id as string,\n name: list.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n const campaignOptions = (campaignDocs ?? [])\n .filter((campaign: any) => !campaign.deletedAt && campaign.name)\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 const webhookOptions = (webhookDocs ?? [])\n .filter(\n (hook: any) =>\n !hook.deletedAt && hook.name && hook.direction === 'outbound',\n )\n .map((hook: any) => ({\n id: hook.$id as string,\n name: hook.name as string,\n }))\n .sort((a, b) => a.name.localeCompare(b.name))\n\n /** The records this site offers every step picker in the editor. */\n const stepPickers: AutomationStepPickers = {\n workflowOptions,\n datasetOptions,\n overlayOptions,\n listOptions,\n campaignOptions,\n webhookOptions,\n }\n return { pickers: stepPickers, truncated: truncatedPickers }\n}\n"],"names":["scopeTokensForHost","pluginContainerKind","useFirestore","useFirestoreCollection","useOrgDataScope","ceilingedWindow","collectionCeiling","collection","query","where","pluginRecordListQuery","pluginRecordsFromRows","useMemo","EDITOR_OPTION_CEILING","useAutomationStepPickers","hostId","editorOpened","firestore","scope","dataScope","data","workflowRead","idField","rows","workflowDocs","truncated","workflowsTruncated","scopeTokens","datasetOrgId","datasetRead","orgId","limit","datasetRows","datasetsTruncated","overlayRead","overlayRows","overlaysTruncated","listRead","listDocs","listsTruncated","campaignCollection","orgCollection","campaignRead","campaignDocs","campaignsTruncated","webhookRead","webhookDocs","webhooksTruncated","truncatedPickers","filter","name","workflowOptions","workflow","deletedAt","map","id","$id","sort","a","b","localeCompare","datasetOptions","dataset","overlayOptions","overlay","listOptions","list","campaignOptions","campaign","webhookOptions","hook","direction","stepPickers","pickers"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GACD;AAEA;;;;;;;;CAQC,GAED,SAASA,kBAAkB,QAAQ,eAAc;AACjD,SAASC,mBAAmB,QAAQ,gDAA+C;AACnF,SACEC,YAAY,EACZC,sBAAsB,EACtBC,eAAe,QACV,iCAAgC;AACvC;;;;;CAKC,GACD,SACEC,eAAe,EACfC,iBAAiB,QACZ,+DAA8D;AACrE,SAASC,UAAU,EAAEC,KAAK,EAAEC,KAAK,QAAQ,qBAAoB;AAC7D,SACEC,qBAAqB,EACrBC,qBAAqB,QAChB,kDAAiD;AACxD,SAASC,OAAO,QAAQ,QAAO;AAG/B;;;;;;;;CAQC,GACD,OAAO,MAAMC,wBAAwB,IAAG;AASxC;;;;;;;;CAQC,GACD,OAAO,SAASC,yBACdC,MAAc,EACdC,YAAqB;;QAsGMf;IApG3B,MAAMgB,YAAYf;IAClB,MAAM,EAAEgB,OAAOC,SAAS,EAAE,GAAGf,gBAAgB;QAAEW;IAAO;IACtD;;;;;;;;;;;;;;GAcC,GACD,MAAM,EAAEK,MAAMC,YAAY,EAAE,GAAGlB,uBAC7B,IACEa,eACIV,kBACEC,WAAWU,WAAW,SAASF,QAAQ,cACvCF,yBAEF,MACN;QAACI;QAAWF;QAAQC;KAAa,EACjC;QAAEM,SAAS;IAAM;IAEnB,MAAM,EAAEC,MAAMC,YAAY,EAAEC,WAAWC,kBAAkB,EAAE,GACzDrB,gBAAqBgB,cAAcR;IACrC,wEAAwE;IACxE,yEAAyE;IACzE,0EAA0E;IAC1E,0EAA0E;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