@aglyn/plugins-workflows 1.0.0-beta.143
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/LICENSE +201 -0
- package/README.md +52 -0
- package/package.json +53 -0
- package/src/index.d.ts +18 -0
- package/src/index.js +19 -0
- package/src/index.js.map +1 -0
- package/src/lib/components/automation-step-fields.component.d.ts +74 -0
- package/src/lib/components/automation-step-fields.component.js +1210 -0
- package/src/lib/components/automation-step-fields.component.js.map +1 -0
- package/src/lib/components/host-actions-card.component.d.ts +15 -0
- package/src/lib/components/host-actions-card.component.js +1229 -0
- package/src/lib/components/host-actions-card.component.js.map +1 -0
- package/src/lib/components/host-activity-card.component.d.ts +84 -0
- package/src/lib/components/host-activity-card.component.js +280 -0
- package/src/lib/components/host-activity-card.component.js.map +1 -0
- package/src/lib/components/host-run-history-card.component.d.ts +40 -0
- package/src/lib/components/host-run-history-card.component.js +284 -0
- package/src/lib/components/host-run-history-card.component.js.map +1 -0
- package/src/lib/components/host-webhooks-card.component.d.ts +15 -0
- package/src/lib/components/host-webhooks-card.component.js +421 -0
- package/src/lib/components/host-webhooks-card.component.js.map +1 -0
- package/src/lib/components/host-workflows-card.component.d.ts +18 -0
- package/src/lib/components/host-workflows-card.component.js +952 -0
- package/src/lib/components/host-workflows-card.component.js.map +1 -0
- package/src/lib/components/run-quota-line.component.d.ts +27 -0
- package/src/lib/components/run-quota-line.component.js +72 -0
- package/src/lib/components/run-quota-line.component.js.map +1 -0
- package/src/lib/components/use-automation-step-pickers.d.ts +27 -0
- package/src/lib/components/use-automation-step-pickers.js +205 -0
- package/src/lib/components/use-automation-step-pickers.js.map +1 -0
- package/src/lib/components/workflow-zones.d.ts +36 -0
- package/src/lib/components/workflow-zones.js +19 -0
- package/src/lib/components/workflow-zones.js.map +1 -0
- package/src/lib/components/workflows-console-page.d.ts +25 -0
- package/src/lib/components/workflows-console-page.js +112 -0
- package/src/lib/components/workflows-console-page.js.map +1 -0
- package/src/lib/components/workflows-console-sections.d.ts +34 -0
- package/src/lib/components/workflows-console-sections.js +50 -0
- package/src/lib/components/workflows-console-sections.js.map +1 -0
- package/src/lib/constants/bundle-common.d.ts +8 -0
- package/src/lib/constants/bundle-common.js +9 -0
- package/src/lib/constants/bundle-common.js.map +1 -0
- package/src/lib/declarations.server.d.ts +41 -0
- package/src/lib/declarations.server.js +54 -0
- package/src/lib/declarations.server.js.map +1 -0
- package/src/lib/engine/crm-action-steps.d.ts +129 -0
- package/src/lib/engine/crm-action-steps.js +432 -0
- package/src/lib/engine/crm-action-steps.js.map +1 -0
- package/src/lib/engine/flow-enrollments.d.ts +264 -0
- package/src/lib/engine/flow-enrollments.js +386 -0
- package/src/lib/engine/flow-enrollments.js.map +1 -0
- package/src/lib/engine/run-event-actions.d.ts +232 -0
- package/src/lib/engine/run-event-actions.js +1392 -0
- package/src/lib/engine/run-event-actions.js.map +1 -0
- package/src/lib/engine/run-event-automations.d.ts +28 -0
- package/src/lib/engine/run-event-automations.js +37 -0
- package/src/lib/engine/run-event-automations.js.map +1 -0
- package/src/lib/engine/run-event-workflows.d.ts +75 -0
- package/src/lib/engine/run-event-workflows.js +311 -0
- package/src/lib/engine/run-event-workflows.js.map +1 -0
- package/src/lib/engine/workflow-steps.d.ts +107 -0
- package/src/lib/engine/workflow-steps.js +124 -0
- package/src/lib/engine/workflow-steps.js.map +1 -0
- package/src/lib/plugin.d.ts +33 -0
- package/src/lib/plugin.js +94 -0
- package/src/lib/plugin.js.map +1 -0
- package/src/lib/server-automation-drafts.d.ts +90 -0
- package/src/lib/server-automation-drafts.js +429 -0
- package/src/lib/server-automation-drafts.js.map +1 -0
- package/src/lib/server-console.d.ts +27 -0
- package/src/lib/server-console.js +35 -0
- package/src/lib/server-console.js.map +1 -0
- package/src/lib/server.d.ts +29 -0
- package/src/lib/server.js +298 -0
- package/src/lib/server.js.map +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/server-automation-drafts.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n ACTIONS_MAX_PER_HOST,\n hostActionDocument,\n type HostAction,\n type HostActionStep,\n type HostActionStepType,\n type HostActionTriggerCondition,\n validateHostAction,\n} from '@aglyn/aglyn/app-utils/actions'\nimport { automationPlaceholders } from '@aglyn/aglyn/app-utils/automation-placeholders'\nimport { hostRoleCanWrite } from '@aglyn/aglyn/app-utils/organizations'\nimport { checkEntitlement } from '@aglyn/aglyn/app-utils/plan-entitlements'\nimport type { AglynOrgBilling } from '@aglyn/aglyn/foundation/definitions/org-billing.types'\nimport {\n registerPluginResourceDraftWriter,\n type PluginDraftCheck,\n type PluginDraftRecord,\n type PluginDraftRefusal,\n type PluginDraftWrite,\n type PluginResourceDraftWriter,\n} from '@aglyn/aglyn/plugin-manager/plugin-resource-drafts'\nimport { firebaseAdmin } from '@aglyn/tenant-data-admin'\nimport { BUNDLE_ID } from './constants/bundle-common'\n\n/**\n * AN AUTOMATION ANOTHER PLUGIN ASKS FOR (AGL-2919).\n *\n * The draft writer this plugin registers for the `automation` resource on the\n * core's resource-drafts seam. A plugin that produces an automation — a\n * generator working from a description, an importer bringing flows over from\n * another tool — asks for the writer by name and gets this plugin's rules,\n * never a copy of them:\n *\n * - THE DOCUMENT is `hosts/{hostId}/actions/{id}` in the stored shape the\n * Actions editor saves (`hostActionDocument`), with only the fields each\n * step type holds. It is listed on the Automation page's Actions, opens in\n * that editor, and runs through the same executor as one a person made.\n * - IT IS OFF. A draft is written `enabled: false` whatever the caller sent,\n * so nothing it describes runs until a person switches it on.\n * - THE SCHEMA is the editor's own validator, `validateHostAction`, which the\n * executor's writers share. A placeholder the draft could not fill — a\n * bracketed list name, a bracketed condition value — passes it, because it\n * is a value a person replaces, and the facts name every one.\n * - THE ROOM is the flat platform cap on live actions, counted inside the\n * transaction with the arithmetic `/api/hosts/resources` uses.\n * - THE ROLE is the resources route's: a member who may write the site's\n * content. THE PLAN is the Actions editor's: the `actions` entitlement.\n *\n * Nothing is enabled, sent or run, and the writer touches the one new document.\n */\n\ntype Firestore = FirebaseFirestore.Firestore\n\n/** The resource name this writer is registered under. */\nexport const AUTOMATION_DRAFT_RESOURCE = 'automation'\n\n/** The longest name the Actions editor stores. */\nexport const AUTOMATION_DRAFT_NAME_MAX_CHARS = 60\n\n/** A draft's name when the caller asks for none. */\nexport const AUTOMATION_DRAFT_DEFAULT_NAME = 'New automation'\n\n/** The resources route's refusal for a member who may not write the site. */\nexport const AUTOMATION_DRAFT_ROLE_REFUSAL = 'Editing requires the editor role'\n\n/** What a person is told when their plan has no actions builder. It names the page that sells one. */\nexport const AUTOMATION_DRAFT_PLAN_REFUSAL =\n 'Automations are not included on this workspace’s plan. Upgrade in Billing to build them.'\n\n/** The resources route's refusal at the cap. */\nexport const AUTOMATION_DRAFT_LIMIT_REFUSAL =\n `interactions and actions are capped at ${ACTIONS_MAX_PER_HOST} per site — ` +\n 'delete some to make room'\n\n/** A trigger bound to one element, which makes an action an interaction of its page. */\nconst LEAF_SELECTOR = /^\\[data-aglyn=\"leaf:.+\"\\]$/\n\n/**\n * The fields each step type holds, besides `type` and the step's own `when`.\n * Total over the step types, so a type the model gains is a compile error here\n * until its fields are named, rather than a draft that silently drops them.\n */\nexport const AUTOMATION_STEP_FIELDS: Readonly<Record<HostActionStepType, readonly string[]>> = {\n runWorkflow: ['workflowId', 'workflowName'],\n siteAlert: ['message', 'severity'],\n customEvent: ['eventName'],\n datasetAppend: ['datasetId', 'datasetName'],\n webhookPost: ['webhookId', 'webhookName'],\n showOverlay: ['overlayId', 'overlayName'],\n stickyNav: ['selector'],\n addClass: ['selector', 'className'],\n removeClass: ['selector', 'className'],\n toggleClass: ['selector', 'className'],\n showElement: ['selector', 'delayMs', 'dismissOn'],\n hideElement: ['selector', 'delayMs'],\n toggleElement: ['selector', 'delayMs', 'dismissOn'],\n setAttribute: ['selector', 'name', 'value'],\n removeAttribute: ['selector', 'name'],\n scrollTo: ['selector', 'behavior', 'offsetPx'],\n playVideo: ['selector'],\n openDrawer: ['drawerNodeId'],\n closeDrawer: ['drawerNodeId'],\n toggleDrawer: ['drawerNodeId'],\n openMenu: ['menuNodeId'],\n closeMenu: ['menuNodeId'],\n toggleMenu: ['menuNodeId'],\n showHtml: ['html'],\n runJs: ['code'],\n redirect: ['url', 'screenId'],\n trackGaEvent: ['eventName', 'params'],\n sendEmail: ['subject', 'body', 'toField', 'topicId'],\n notifyAdmins: ['title', 'body'],\n enrollList: ['listId', 'listName'],\n updateDataset: ['datasetId', 'datasetName'],\n assignCampaign: ['campaignId', 'campaignName'],\n wait: ['delayMinutes'],\n waitForEvent: ['eventName', 'timeoutMinutes'],\n exitFlow: [],\n setContactStage: ['lifecycleStage'],\n addContactTag: ['tag'],\n assignContactOwner: ['ownerUid', 'ownerEmail', 'roundRobin'],\n createCrmTask: ['title', 'kind', 'dueInDays', 'assigneeUid', 'assigneeEmail'],\n logCrmActivity: ['kind', 'body'],\n}\n\n/** The trigger keys an automation stores. */\nconst TRIGGER_FIELDS = [\n 'event',\n 'filter',\n 'conditions',\n 'combinator',\n 'selector',\n 'threshold',\n 'pathPattern',\n 'oncePerVisitor',\n 'oncePerSession',\n 'cooldownMinutes',\n 'everyTime',\n] as const\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\n/** The keys of `source` that `keys` names and that hold something. */\nfunction picked(source: Record<string, unknown>, keys: readonly string[]): Record<string, unknown> {\n const out: Record<string, unknown> = {}\n for (const key of keys) {\n if (source[key] !== undefined && source[key] !== null) out[key] = source[key]\n }\n return out\n}\n\nfunction conditionOf(value: unknown): HostActionTriggerCondition | null {\n if (!isRecord(value)) return null\n return picked(value, ['field', 'op', 'value']) as unknown as HostActionTriggerCondition\n}\n\nexport type AutomationDraftContentRead =\n | { ok: true; action: HostAction }\n | { ok: false; problems: string[] }\n\n/**\n * What a caller sends as `content` — `{ action }` — read into the action this\n * writer would store: the trigger's and each step's own fields and nothing\n * else, named, OFF, and held to the editor's validator.\n */\nexport function readAutomationDraftContent(\n content: Readonly<Record<string, unknown>>,\n): AutomationDraftContentRead {\n const raw = content['action']\n if (!isRecord(raw)) return { ok: false, problems: ['The draft holds no automation'] }\n const trigger = raw['trigger']\n const steps = raw['steps']\n if (!isRecord(trigger)) return { ok: false, problems: ['Pick a trigger event'] }\n if (!Array.isArray(steps)) return { ok: false, problems: ['Add at least one step'] }\n const problems: string[] = []\n const knownTypes = new Set(Object.keys(AUTOMATION_STEP_FIELDS))\n const cleanSteps: HostActionStep[] = []\n steps.forEach((step, index) => {\n const type = isRecord(step) ? step['type'] : undefined\n if (typeof type !== 'string' || !knownTypes.has(type)) {\n problems.push(`Step ${index + 1}: not a step the Actions editor offers`)\n return\n }\n const source = step as Record<string, unknown>\n const when = isRecord(source['when'])\n ? {\n conditions: (Array.isArray(source['when']['conditions']) ? source['when']['conditions'] : [])\n .map(conditionOf)\n .filter((clause): clause is HostActionTriggerCondition => clause !== null),\n ...(typeof source['when']['combinator'] === 'string'\n ? { combinator: source['when']['combinator'] }\n : {}),\n }\n : null\n cleanSteps.push({\n type,\n ...picked(source, AUTOMATION_STEP_FIELDS[type as HostActionStepType]),\n ...(when && when.conditions.length ? { when } : {}),\n } as HostActionStep)\n })\n const cleanTrigger = picked(trigger, TRIGGER_FIELDS)\n if (Array.isArray(cleanTrigger['conditions'])) {\n cleanTrigger['conditions'] = (cleanTrigger['conditions'] as unknown[])\n .map(conditionOf)\n .filter((clause): clause is HostActionTriggerCondition => clause !== null)\n }\n // An element's own interaction belongs to the page that holds the element,\n // and is authored there; the Actions list does not show one.\n if (typeof cleanTrigger['selector'] === 'string' && LEAF_SELECTOR.test(cleanTrigger['selector'])) {\n problems.push('An interaction on one element is set up on that element, not as an automation')\n }\n const name = String(raw['name'] ?? '')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, AUTOMATION_DRAFT_NAME_MAX_CHARS)\n const action: HostAction = {\n name: name || AUTOMATION_DRAFT_DEFAULT_NAME,\n trigger: cleanTrigger as unknown as HostAction['trigger'],\n steps: cleanSteps,\n enabled: false,\n }\n const invalid = validateHostAction(action)\n if (invalid) problems.push(invalid)\n return problems.length ? { ok: false, problems } : { ok: true, action }\n}\n\n/** What the writer reports about an automation beyond its identity. */\nfunction factsOf(action: Pick<HostAction, 'trigger' | 'steps' | 'enabled'>): Record<string, unknown> {\n return {\n event: action.trigger?.event ?? '',\n steps: (action.steps ?? []).length,\n enabled: action.enabled === true,\n placeholders: automationPlaceholders(action).length,\n }\n}\n\n/** Whether content is an automation this site could store: well-formed, off, and valid. */\nexport function checkAutomationDraftContent(\n content: Readonly<Record<string, unknown>>,\n): PluginDraftCheck {\n const read = readAutomationDraftContent(content)\n return read.ok === false ? read : { ok: true, facts: factsOf(read.action) }\n}\n\nfunction recordOf(snapshot: FirebaseFirestore.DocumentSnapshot): PluginDraftRecord {\n const data = (snapshot.data() ?? {}) as HostAction\n return {\n id: snapshot.id,\n name: String(data.name ?? ''),\n versionId: null,\n facts: factsOf(data),\n }\n}\n\nfunction roleRefusal(host: FirebaseFirestore.DocumentSnapshot, uid: string): PluginDraftRefusal | null {\n const role = (host.get('memberRoles') ?? {})[uid]\n return hostRoleCanWrite(role) ? null : { status: 403, error: AUTOMATION_DRAFT_ROLE_REFUSAL }\n}\n\nfunction planRefusal(org: Readonly<Record<string, unknown>> | null): PluginDraftRefusal | null {\n return checkEntitlement(org as Partial<AglynOrgBilling> | null, 'actions')\n ? null\n : { status: 403, error: AUTOMATION_DRAFT_PLAN_REFUSAL }\n}\n\n/** The live actions the site holds: a soft-deleted one frees its slot. */\nfunction liveCount(rows: FirebaseFirestore.QuerySnapshot): number {\n return rows.docs.filter((row) => row.get('deletedAt') == null).length\n}\n\nfunction roomRefusal(live: number): PluginDraftRefusal | null {\n return live >= ACTIONS_MAX_PER_HOST ? { status: 403, error: AUTOMATION_DRAFT_LIMIT_REFUSAL } : null\n}\n\nexport interface AutomationDraftWriterDeps {\n /** The Admin SDK handle; specs hand in a double. */\n firestore?: () => Firestore\n}\n\nexport function createAutomationDraftWriter(\n deps: AutomationDraftWriterDeps = {},\n): PluginResourceDraftWriter {\n const firestore = deps.firestore ?? (() => firebaseAdmin.app().firestore() as unknown as Firestore)\n return {\n refusal: async (context) => {\n const hostRef = firestore().collection('hosts').doc(context.hostId)\n const host = await hostRef.get()\n if (!host.exists) return { status: 404, error: 'Unknown site' }\n return (\n roleRefusal(host, context.uid) ??\n planRefusal(context.org) ??\n roomRefusal(liveCount(await hostRef.collection('actions').select('deletedAt').get()))\n )\n },\n\n check: (content) => checkAutomationDraftContent(content),\n\n read: async ({ hostId, id }) => {\n const snapshot = await firestore().collection('hosts').doc(hostId).collection('actions').doc(id).get()\n return snapshot.exists ? recordOf(snapshot) : null\n },\n\n write: async (request): Promise<PluginDraftWrite> => {\n const read = readAutomationDraftContent(request.content)\n if (read.ok === false) return { ok: false, status: 400, error: read.problems[0] }\n const db = firestore()\n const hostRef = db.collection('hosts').doc(request.hostId)\n const actionRef = hostRef.collection('actions').doc(request.id)\n const name =\n String(request.name ?? '')\n .replace(/\\s+/g, ' ')\n .trim()\n .slice(0, AUTOMATION_DRAFT_NAME_MAX_CHARS) || read.action.name\n const action: HostAction = { ...read.action, name, enabled: false, recipe: null }\n return db.runTransaction(async (tx): Promise<PluginDraftWrite> => {\n // Every read before any write, which Firestore requires.\n const [host, existing, rows] = await Promise.all([\n tx.get(hostRef),\n tx.get(actionRef),\n tx.get(hostRef.collection('actions').select('deletedAt')),\n ])\n if (!host.exists) return { ok: false, status: 404, error: 'Unknown site' }\n if (existing.exists) return { ok: true, replayed: true, ...recordOf(existing) }\n const refusal =\n roleRefusal(host, request.uid) ?? planRefusal(request.org) ?? roomRefusal(liveCount(rows))\n if (refusal) return { ok: false, ...refusal }\n tx.create(actionRef, {\n ...hostActionDocument(action),\n createdAt: request.now,\n updatedAt: request.now,\n createdBy: request.uid,\n })\n return { ok: true, replayed: false, id: request.id, name, versionId: null, facts: factsOf(action) }\n })\n },\n }\n}\n\nexport const automationDraftWriter = createAutomationDraftWriter()\n\n/**\n * Registers the writer; the console surface calls it, since only the console\n * runs AI jobs (AGL-3026). Idempotent: a second call replaces the first.\n */\nexport function registerAutomationDraftWriter(): void {\n registerPluginResourceDraftWriter(AUTOMATION_DRAFT_RESOURCE, automationDraftWriter, {\n pluginId: BUNDLE_ID,\n })\n}\n"],"names":["ACTIONS_MAX_PER_HOST","hostActionDocument","validateHostAction","automationPlaceholders","hostRoleCanWrite","checkEntitlement","registerPluginResourceDraftWriter","firebaseAdmin","BUNDLE_ID","AUTOMATION_DRAFT_RESOURCE","AUTOMATION_DRAFT_NAME_MAX_CHARS","AUTOMATION_DRAFT_DEFAULT_NAME","AUTOMATION_DRAFT_ROLE_REFUSAL","AUTOMATION_DRAFT_PLAN_REFUSAL","AUTOMATION_DRAFT_LIMIT_REFUSAL","LEAF_SELECTOR","AUTOMATION_STEP_FIELDS","runWorkflow","siteAlert","customEvent","datasetAppend","webhookPost","showOverlay","stickyNav","addClass","removeClass","toggleClass","showElement","hideElement","toggleElement","setAttribute","removeAttribute","scrollTo","playVideo","openDrawer","closeDrawer","toggleDrawer","openMenu","closeMenu","toggleMenu","showHtml","runJs","redirect","trackGaEvent","sendEmail","notifyAdmins","enrollList","updateDataset","assignCampaign","wait","waitForEvent","exitFlow","setContactStage","addContactTag","assignContactOwner","createCrmTask","logCrmActivity","TRIGGER_FIELDS","isRecord","value","Array","isArray","picked","source","keys","out","key","undefined","conditionOf","readAutomationDraftContent","content","raw","ok","problems","trigger","steps","knownTypes","Set","Object","cleanSteps","forEach","step","index","type","has","push","when","conditions","map","filter","clause","combinator","length","cleanTrigger","test","name","String","replace","trim","slice","action","enabled","invalid","factsOf","event","placeholders","checkAutomationDraftContent","read","facts","recordOf","snapshot","data","id","versionId","roleRefusal","host","uid","role","get","status","error","planRefusal","org","liveCount","rows","docs","row","roomRefusal","live","createAutomationDraftWriter","deps","firestore","app","refusal","context","hostRef","collection","doc","hostId","exists","select","check","write","request","db","actionRef","recipe","runTransaction","tx","existing","Promise","all","replayed","create","createdAt","now","updatedAt","createdBy","automationDraftWriter","registerAutomationDraftWriter","pluginId"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,oBAAoB,EACpBC,kBAAkB,EAKlBC,kBAAkB,QACb,iCAAgC;AACvC,SAASC,sBAAsB,QAAQ,iDAAgD;AACvF,SAASC,gBAAgB,QAAQ,uCAAsC;AACvE,SAASC,gBAAgB,QAAQ,2CAA0C;AAE3E,SACEC,iCAAiC,QAM5B,qDAAoD;AAC3D,SAASC,aAAa,QAAQ,2BAA0B;AACxD,SAASC,SAAS,QAAQ,+BAA2B;AA+BrD,uDAAuD,GACvD,OAAO,MAAMC,4BAA4B,aAAY;AAErD,gDAAgD,GAChD,OAAO,MAAMC,kCAAkC,GAAE;AAEjD,kDAAkD,GAClD,OAAO,MAAMC,gCAAgC,iBAAgB;AAE7D,2EAA2E,GAC3E,OAAO,MAAMC,gCAAgC,mCAAkC;AAE/E,oGAAoG,GACpG,OAAO,MAAMC,gCACX,2FAA0F;AAE5F,8CAA8C,GAC9C,OAAO,MAAMC,iCACX,CAAC,uCAAuC,EAAEd,qBAAqB,YAAY,CAAC,GAC5E,2BAA0B;AAE5B,sFAAsF,GACtF,MAAMe,gBAAgB;AAEtB;;;;CAIC,GACD,OAAO,MAAMC,yBAAkF;IAC7FC,aAAa;QAAC;QAAc;KAAe;IAC3CC,WAAW;QAAC;QAAW;KAAW;IAClCC,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Ce,GAAGK,MAAM,CAACR,WAAW,aAChBhJ,mBAAmBmG;oBACtBsD,WAAWX,QAAQY,GAAG;oBACtBC,WAAWb,QAAQY,GAAG;oBACtBE,WAAWd,QAAQ3B,GAAG;;gBAExB,OAAO;oBAAE5C,IAAI;oBAAMgF,UAAU;oBAAOxC,IAAI+B,QAAQ/B,EAAE;oBAAEjB;oBAAMkB,WAAW;oBAAML,OAAOL,QAAQH;gBAAQ;YACpG;QACF;IACF;AACF;AAEA,OAAO,MAAM0D,wBAAwB7B,8BAA6B;AAElE;;;CAGC,GACD,OAAO,SAAS8B;IACdzJ,kCAAkCG,2BAA2BqJ,uBAAuB;QAClFE,UAAUxJ;IACZ;AACF"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* The workflows plugin's console server surface (AGL-2919).
|
|
19
|
+
*
|
|
20
|
+
* The tenant surface (`registerWorkflowsApi`) serves the inbound webhook a
|
|
21
|
+
* visitor-facing integration calls. This one serves what only the console
|
|
22
|
+
* does: the automation draft writer another plugin reaches through the core's
|
|
23
|
+
* resource-drafts seam, which the AI jobs that write through it — inline at a
|
|
24
|
+
* door and on the beat — find registered in the console process alone
|
|
25
|
+
* (AGL-3026).
|
|
26
|
+
*/
|
|
27
|
+
export declare function registerWorkflowsConsoleApi(): void;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/ import { registerWorkflowsServerDeclarations } from "./declarations.server.js";
|
|
17
|
+
import { registerAutomationDraftWriter } from "./server-automation-drafts.js";
|
|
18
|
+
/**
|
|
19
|
+
* The workflows plugin's console server surface (AGL-2919).
|
|
20
|
+
*
|
|
21
|
+
* The tenant surface (`registerWorkflowsApi`) serves the inbound webhook a
|
|
22
|
+
* visitor-facing integration calls. This one serves what only the console
|
|
23
|
+
* does: the automation draft writer another plugin reaches through the core's
|
|
24
|
+
* resource-drafts seam, which the AI jobs that write through it — inline at a
|
|
25
|
+
* door and on the beat — find registered in the console process alone
|
|
26
|
+
* (AGL-3026).
|
|
27
|
+
*/ export function registerWorkflowsConsoleApi() {
|
|
28
|
+
// The console raises host events too — a CRM stage moved, a deal won, a
|
|
29
|
+
// task completed — so the engine's listener is registered here as well as
|
|
30
|
+
// at boot (see `declarations.server.ts`).
|
|
31
|
+
registerWorkflowsServerDeclarations();
|
|
32
|
+
registerAutomationDraftWriter();
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
//# sourceMappingURL=server-console.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/server-console.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { registerWorkflowsServerDeclarations } from './declarations.server'\nimport { registerAutomationDraftWriter } from './server-automation-drafts'\n\n/**\n * The workflows plugin's console server surface (AGL-2919).\n *\n * The tenant surface (`registerWorkflowsApi`) serves the inbound webhook a\n * visitor-facing integration calls. This one serves what only the console\n * does: the automation draft writer another plugin reaches through the core's\n * resource-drafts seam, which the AI jobs that write through it — inline at a\n * door and on the beat — find registered in the console process alone\n * (AGL-3026).\n */\nexport function registerWorkflowsConsoleApi(): void {\n // The console raises host events too — a CRM stage moved, a deal won, a\n // task completed — so the engine's listener is registered here as well as\n // at boot (see `declarations.server.ts`).\n registerWorkflowsServerDeclarations()\n registerAutomationDraftWriter()\n}\n"],"names":["registerWorkflowsServerDeclarations","registerAutomationDraftWriter","registerWorkflowsConsoleApi"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,SAASA,mCAAmC,QAAQ,2BAAuB;AAC3E,SAASC,6BAA6B,QAAQ,gCAA4B;AAE1E;;;;;;;;;CASC,GACD,OAAO,SAASC;IACd,wEAAwE;IACxE,0EAA0E;IAC1E,0CAA0C;IAC1CF;IACAC;AACF"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @license
|
|
3
|
+
* Copyright 2026 Aglyn LLC
|
|
4
|
+
*
|
|
5
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
6
|
+
* you may not use this file except in compliance with the License.
|
|
7
|
+
* You may obtain a copy of the License at
|
|
8
|
+
*
|
|
9
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
10
|
+
*
|
|
11
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
12
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
13
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
14
|
+
* See the License for the specific language governing permissions and
|
|
15
|
+
* limitations under the License.
|
|
16
|
+
*/
|
|
17
|
+
/**
|
|
18
|
+
* Registers the workflows plugin's public API routes (AGL-396), and the
|
|
19
|
+
* engine's host-event listener beside them for a process whose boot did not
|
|
20
|
+
* (see `declarations.server.ts`).
|
|
21
|
+
*/
|
|
22
|
+
export declare function registerWorkflowsApi(): void;
|
|
23
|
+
/**
|
|
24
|
+
* The console half (AGL-2919), re-exported so one entry point serves both
|
|
25
|
+
* surfaces: the manifest generator resolves every server surface through
|
|
26
|
+
* `@aglyn/plugins-workflows/server`, and a second entry point would be a second
|
|
27
|
+
* thing to keep in step with plugins.config.json.
|
|
28
|
+
*/
|
|
29
|
+
export { registerWorkflowsConsoleApi } from './server-console';
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { _ as _extends } from "@swc/helpers/_/_extends";
|
|
2
|
+
/**
|
|
3
|
+
* @license
|
|
4
|
+
* Copyright 2026 Aglyn LLC
|
|
5
|
+
*
|
|
6
|
+
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
7
|
+
* you may not use this file except in compliance with the License.
|
|
8
|
+
* You may obtain a copy of the License at
|
|
9
|
+
*
|
|
10
|
+
* http://www.apache.org/licenses/LICENSE-2.0
|
|
11
|
+
*
|
|
12
|
+
* Unless required by applicable law or agreed to in writing, software
|
|
13
|
+
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
14
|
+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
15
|
+
* See the License for the specific language governing permissions and
|
|
16
|
+
* limitations under the License.
|
|
17
|
+
*/ import { checkEntitlement, resolveOrgEntitlements, runWorkflow } from "@aglyn/aglyn/server";
|
|
18
|
+
import { registerPluginApiRoute, registerPluginJob } from "@aglyn/aglyn/server";
|
|
19
|
+
import { firebaseAdmin, getOrgForHost } from "@aglyn/tenant-data-admin";
|
|
20
|
+
import { timingSafeEqual } from "crypto";
|
|
21
|
+
import { FieldValue } from "firebase-admin/firestore";
|
|
22
|
+
import { BUNDLE_ID as WORKFLOWS_BUNDLE_ID } from "./constants/bundle-common.js";
|
|
23
|
+
import { registerWorkflowsServerDeclarations } from "./declarations.server.js";
|
|
24
|
+
import { automationRunEnv, executeWorkflow, runDueFlowEnrollments, workflowContextFromDocs } from "./engine/run-event-actions.js";
|
|
25
|
+
import { workflowHasActionSteps } from "./engine/workflow-steps.js";
|
|
26
|
+
/*==========================================
|
|
27
|
+
* THE BEAT THAT MAKES A WAIT STEP REAL.
|
|
28
|
+
*
|
|
29
|
+
* A `wait` step suspends a run into a `flowEnrollments` row and returns; this
|
|
30
|
+
* is the only thing that ever comes back for it. Without a registration here
|
|
31
|
+
* the wait step would be a delay that never ends — the exact failure
|
|
32
|
+
* `process-abandoned.ts` documents next door, where a Pro entitlement sat
|
|
33
|
+
* behind an HTTP door nothing ever POSTed to.
|
|
34
|
+
*
|
|
35
|
+
* Module scope, like the commerce and bookings registrations: the runner
|
|
36
|
+
* route reaches plugin jobs through `ensureAll(['tenantApi'])`, so a
|
|
37
|
+
* registration inside `registerWorkflowsApi()` would depend on which entry
|
|
38
|
+
* point happened to be loaded.
|
|
39
|
+
*
|
|
40
|
+
* ## Every minute, and why that is cheap
|
|
41
|
+
*
|
|
42
|
+
* `FLOW_WAIT_MIN_MINUTES` is one, so the beat has to be one — a fifteen-minute
|
|
43
|
+
* sweep would make the shortest wait anybody can author wrong by up to
|
|
44
|
+
* fourteen minutes. It costs one collection-group query per minute, which
|
|
45
|
+
* returns nothing at all on a platform with no flow due, because the query
|
|
46
|
+
* asks for `resumeAtMs <= now` rather than for the enrolled population.
|
|
47
|
+
*
|
|
48
|
+
* Bounded and idempotent, the two properties the runner requires: the scan
|
|
49
|
+
* budget bounds one pass, and a transactional claim means an overlapping or
|
|
50
|
+
* repeated beat cannot run the same person's step twice.
|
|
51
|
+
*=========================================*/ registerPluginJob({
|
|
52
|
+
pluginId: WORKFLOWS_BUNDLE_ID,
|
|
53
|
+
name: 'resume-flow-waits',
|
|
54
|
+
intervalMinutes: 1,
|
|
55
|
+
description: 'Continue automations whose wait step has ended, and time out those ' + 'waiting for an event that never arrived.',
|
|
56
|
+
lockdown: {
|
|
57
|
+
scope: 'per-host'
|
|
58
|
+
},
|
|
59
|
+
handler: async (gate)=>{
|
|
60
|
+
await runDueFlowEnrollments(gate);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
// Best-effort per-instance rate limit (mirrors forms/submit).
|
|
64
|
+
const recentByHook = new Map();
|
|
65
|
+
const RATE_WINDOW_MS = 60000;
|
|
66
|
+
const RATE_MAX = 30;
|
|
67
|
+
function rateLimited(key) {
|
|
68
|
+
var _recentByHook_get;
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
const hits = ((_recentByHook_get = recentByHook.get(key)) != null ? _recentByHook_get : []).filter((t)=>now - t < RATE_WINDOW_MS);
|
|
71
|
+
hits.push(now);
|
|
72
|
+
recentByHook.set(key, hits);
|
|
73
|
+
return hits.length > RATE_MAX;
|
|
74
|
+
}
|
|
75
|
+
function secretsMatch(expected, provided) {
|
|
76
|
+
if (!expected || expected.length !== provided.length) return false;
|
|
77
|
+
return timingSafeEqual(new Uint8Array(Buffer.from(expected)), new Uint8Array(Buffer.from(provided)));
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Inbound webhook endpoint (AGL-149): external systems POST JSON to
|
|
81
|
+
* `/api/hooks/{hostId}/{hookId}` with the hook's secret in
|
|
82
|
+
* `x-aglyn-secret`; a valid call enrolls the configured workflow with the
|
|
83
|
+
* payload's top-level primitives in scope. Business tier (`webhooks`
|
|
84
|
+
* flag); runs bill against the workflow-runs meter like any other run —
|
|
85
|
+
* `workflowRunsPerMonth` is checked before the run and
|
|
86
|
+
* `hosts/{id}/counters/workflowRuns` is incremented after it (AGL-2228).
|
|
87
|
+
* That sentence was here before either half of it was true.
|
|
88
|
+
*/ const inboundHookHandler = async (req, res)=>{
|
|
89
|
+
var _req_query_hostId, _req_query_hookId;
|
|
90
|
+
if (req.method !== 'POST') {
|
|
91
|
+
return res.status(405).json({
|
|
92
|
+
error: 'Method not allowed'
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
const hostId = String((_req_query_hostId = req.query['hostId']) != null ? _req_query_hostId : '');
|
|
96
|
+
const hookId = String((_req_query_hookId = req.query['hookId']) != null ? _req_query_hookId : '');
|
|
97
|
+
if (!hostId || !hookId) {
|
|
98
|
+
return res.status(400).json({
|
|
99
|
+
error: 'Invalid webhook address'
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
if (rateLimited(`${hostId}/${hookId}`)) {
|
|
103
|
+
return res.status(429).json({
|
|
104
|
+
error: 'Too many requests'
|
|
105
|
+
});
|
|
106
|
+
}
|
|
107
|
+
try {
|
|
108
|
+
var _req_headers_xaglynsecret, _hook_secret, _get, _req_body, _ref, _hook_name, _hook_name1;
|
|
109
|
+
var _hook_workflowName;
|
|
110
|
+
const firestore = firebaseAdmin.app().firestore();
|
|
111
|
+
const hostRef = firestore.collection('hosts').doc(hostId);
|
|
112
|
+
const hookSnapshot = await hostRef.collection('webhooks').doc(hookId).get();
|
|
113
|
+
const hook = hookSnapshot.data();
|
|
114
|
+
if (!hook || hookSnapshot.get('deletedAt') || hook.direction !== 'inbound' || hook.enabled === false) {
|
|
115
|
+
return res.status(404).json({
|
|
116
|
+
error: 'Unknown webhook'
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
const provided = String((_req_headers_xaglynsecret = req.headers['x-aglyn-secret']) != null ? _req_headers_xaglynsecret : '');
|
|
120
|
+
if (!secretsMatch((_hook_secret = hook.secret) != null ? _hook_secret : '', provided)) {
|
|
121
|
+
return res.status(401).json({
|
|
122
|
+
error: 'Bad secret'
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
// Plan/quota gates ride the owning org's doc (AGL-238).
|
|
126
|
+
const owner = await getOrgForHost(hostId);
|
|
127
|
+
const org = owner == null ? void 0 : owner.org;
|
|
128
|
+
if (!checkEntitlement(org, 'webhooks')) {
|
|
129
|
+
return res.status(403).json({
|
|
130
|
+
error: 'Webhooks are not enabled on this site'
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
/*
|
|
134
|
+
* The MONTHLY RUN CAP, which this handler's own docblock claimed for
|
|
135
|
+
* years — "runs bill against the workflow-runs meter like any other run"
|
|
136
|
+
* — and did not have. It read neither `workflowRunsPerMonth` nor
|
|
137
|
+
* `hosts/{id}/counters/workflowRuns`, and it wrote neither, so an inbound
|
|
138
|
+
* hook was a workflow execution that no cap could refuse and no meter
|
|
139
|
+
* could see: the customer's usage card, the usage-alerts cron and the
|
|
140
|
+
* COGS rollup all read a counter this path never moved.
|
|
141
|
+
*
|
|
142
|
+
* The refusal is a 402 rather than the silent `return` of
|
|
143
|
+
* `runEventWorkflows`: that path is fired from a visitor request whose
|
|
144
|
+
* success must not depend on the workflow, where this one is an
|
|
145
|
+
* integration calling us on purpose and a caller that gets a 200 for a
|
|
146
|
+
* run that did not happen will keep sending. `Retry-After` is deliberately
|
|
147
|
+
* absent — the month, not a delay, is what clears this.
|
|
148
|
+
*
|
|
149
|
+
* The plan-less/unreadable org resolves as FREE
|
|
150
|
+
* (`workflowRunsPerMonth: 0`), so an org doc we cannot read refuses rather
|
|
151
|
+
* than runs. `checkEntitlement(webhooks)` above already refuses free on
|
|
152
|
+
* today's price list; this is not a second gate on the same fact, because
|
|
153
|
+
* a staff `entitlementOverrides` can grant `webhooks` without granting
|
|
154
|
+
* runs, and because the cap is what bounds a BUSINESS org's spend.
|
|
155
|
+
*
|
|
156
|
+
* Read-then-write, like the event path, and bounded the same way: the
|
|
157
|
+
* per-hook limiter above is 30/60s, so the overshoot a race can buy is
|
|
158
|
+
* bounded by concurrency rather than unbounded by design. Making it
|
|
159
|
+
* atomic means a transaction around the whole run and is the same trade
|
|
160
|
+
* `runEventWorkflows` declined.
|
|
161
|
+
*/ const monthKey = new Date().toISOString().slice(0, 7);
|
|
162
|
+
const runCounterRef = hostRef.collection('counters').doc('workflowRuns');
|
|
163
|
+
const runLimit = resolveOrgEntitlements(org).workflowRunsPerMonth;
|
|
164
|
+
const runsUsed = Number((_get = (await runCounterRef.get()).get(monthKey)) != null ? _get : 0);
|
|
165
|
+
if (!(runsUsed + 1 <= runLimit)) {
|
|
166
|
+
return res.status(402).json({
|
|
167
|
+
error: `This site has used its ${runLimit} workflow runs for the month`
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
// Top-level primitives from the JSON body join the workflow scope.
|
|
171
|
+
const body = typeof req.body === 'string' ? JSON.parse(req.body || '{}') : (_req_body = req.body) != null ? _req_body : {};
|
|
172
|
+
const scope = {};
|
|
173
|
+
for (const [key, value] of Object.entries(body)){
|
|
174
|
+
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
|
|
175
|
+
scope[key.slice(0, 64)] = typeof value === 'string' ? value.slice(0, 2000) : value;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const [functionDocs, variableDocs, workflowDocs] = await Promise.all([
|
|
179
|
+
hostRef.collection('functions').limit(100).get(),
|
|
180
|
+
hostRef.collection('variables').limit(100).get(),
|
|
181
|
+
hostRef.collection('workflows').limit(100).get()
|
|
182
|
+
]);
|
|
183
|
+
const byName = (docs)=>{
|
|
184
|
+
const map = {};
|
|
185
|
+
for (const doc of docs){
|
|
186
|
+
const data = doc.data();
|
|
187
|
+
if ((data == null ? void 0 : data.name) && !data.deletedAt) map[data.name] = data;
|
|
188
|
+
}
|
|
189
|
+
return map;
|
|
190
|
+
};
|
|
191
|
+
const workflows = byName(workflowDocs.docs);
|
|
192
|
+
const workflow = workflows[(_ref = (_hook_workflowName = hook.workflowName) == null ? void 0 : _hook_workflowName.trim()) != null ? _ref : ''];
|
|
193
|
+
if (!workflow) {
|
|
194
|
+
return res.status(422).json({
|
|
195
|
+
error: 'No workflow bound to this hook'
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
const hookEvent = `hook:${(_hook_name = hook.name) != null ? _hook_name : hookId}`;
|
|
199
|
+
/*
|
|
200
|
+
* A workflow of function calls is evaluated, as it always has been. One
|
|
201
|
+
* with Actions steps is PERFORMED by the engine's executor — the posted
|
|
202
|
+
* JSON is its payload — under the Actions tier gates, step by step, and
|
|
203
|
+
* it is still one run on the meter below. Its working set is built from
|
|
204
|
+
* the documents read above rather than read again.
|
|
205
|
+
*/ const outcome = workflowHasActionSteps(workflow) ? await (async ()=>{
|
|
206
|
+
var _ref, _workflow_name;
|
|
207
|
+
const workflowDoc = workflowDocs.docs.find((doc)=>{
|
|
208
|
+
var _hook_workflowName;
|
|
209
|
+
return !doc.get('deletedAt') && doc.get('name') === ((_hook_workflowName = hook.workflowName) == null ? void 0 : _hook_workflowName.trim());
|
|
210
|
+
});
|
|
211
|
+
const execution = await executeWorkflow(automationRunEnv({
|
|
212
|
+
hostId,
|
|
213
|
+
hostRef,
|
|
214
|
+
owner,
|
|
215
|
+
depth: 0,
|
|
216
|
+
loadWorkflowContext: async ()=>workflowContextFromDocs(functionDocs.docs, variableDocs.docs, workflowDocs.docs)
|
|
217
|
+
}), {
|
|
218
|
+
kind: 'workflow',
|
|
219
|
+
id: (_ref = workflowDoc == null ? void 0 : workflowDoc.id) != null ? _ref : '',
|
|
220
|
+
name: (_workflow_name = workflow.name) != null ? _workflow_name : ''
|
|
221
|
+
}, workflow, hookEvent, scope);
|
|
222
|
+
return {
|
|
223
|
+
error: execution.errors.length ? execution.errors.join('; ') : null,
|
|
224
|
+
value: execution.value,
|
|
225
|
+
summary: execution.outcomes.length ? execution.outcomes.join(' · ') : `Ran ${hook.workflowName}`
|
|
226
|
+
};
|
|
227
|
+
})() : (()=>{
|
|
228
|
+
const run = runWorkflow(workflow, byName(functionDocs.docs), byName(variableDocs.docs), _extends({
|
|
229
|
+
event: hookEvent
|
|
230
|
+
}, scope), {
|
|
231
|
+
workflows
|
|
232
|
+
});
|
|
233
|
+
return run.ok === false ? {
|
|
234
|
+
error: run.error,
|
|
235
|
+
value: undefined,
|
|
236
|
+
summary: ''
|
|
237
|
+
} : {
|
|
238
|
+
error: null,
|
|
239
|
+
value: run.value,
|
|
240
|
+
summary: `Ran ${hook.workflowName}`
|
|
241
|
+
};
|
|
242
|
+
})();
|
|
243
|
+
const failed = outcome.error !== null;
|
|
244
|
+
await hostRef.collection('activity').add({
|
|
245
|
+
actorId: null,
|
|
246
|
+
actorEmail: null,
|
|
247
|
+
action: failed ? `Inbound webhook run failed: ${outcome.error}`.slice(0, 300) : `Inbound webhook ran "${hook.workflowName}"`,
|
|
248
|
+
// The run-history shape (AGL-2222) — without `result` this execution
|
|
249
|
+
// is invisible to the Runs table, which reads a verdict and not prose.
|
|
250
|
+
result: failed ? 'failed' : 'succeeded',
|
|
251
|
+
trigger: hookEvent,
|
|
252
|
+
summary: failed ? String(outcome.error).slice(0, 300) : outcome.summary.slice(0, 300),
|
|
253
|
+
target: {
|
|
254
|
+
type: 'workflow',
|
|
255
|
+
id: hookId,
|
|
256
|
+
name: (_hook_name1 = hook.name) != null ? _hook_name1 : ''
|
|
257
|
+
},
|
|
258
|
+
createdAt: FieldValue.serverTimestamp()
|
|
259
|
+
}).catch(()=>undefined);
|
|
260
|
+
// The run happened, so it counts — including a FAILED one, exactly as
|
|
261
|
+
// `runEventWorkflows` counts its failures. A run that executed and threw
|
|
262
|
+
// spent the same compute as one that returned a value; only a run that
|
|
263
|
+
// never started (the cap above, a missing workflow) must not count.
|
|
264
|
+
await runCounterRef.set({
|
|
265
|
+
[monthKey]: FieldValue.increment(1)
|
|
266
|
+
}, {
|
|
267
|
+
merge: true
|
|
268
|
+
}).catch(()=>undefined);
|
|
269
|
+
if (failed) return res.status(422).json({
|
|
270
|
+
error: outcome.error
|
|
271
|
+
});
|
|
272
|
+
return res.status(200).json({
|
|
273
|
+
ok: true,
|
|
274
|
+
value: outcome.value
|
|
275
|
+
});
|
|
276
|
+
} catch (error) {
|
|
277
|
+
console.error(error);
|
|
278
|
+
return res.status(500).json({
|
|
279
|
+
error: 'Webhook failed'
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
/**
|
|
284
|
+
* Registers the workflows plugin's public API routes (AGL-396), and the
|
|
285
|
+
* engine's host-event listener beside them for a process whose boot did not
|
|
286
|
+
* (see `declarations.server.ts`).
|
|
287
|
+
*/ export function registerWorkflowsApi() {
|
|
288
|
+
registerWorkflowsServerDeclarations();
|
|
289
|
+
registerPluginApiRoute('hooks/[hostId]/[hookId]', inboundHookHandler);
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* The console half (AGL-2919), re-exported so one entry point serves both
|
|
293
|
+
* surfaces: the manifest generator resolves every server surface through
|
|
294
|
+
* `@aglyn/plugins-workflows/server`, and a second entry point would be a second
|
|
295
|
+
* thing to keep in step with plugins.config.json.
|
|
296
|
+
*/ export { registerWorkflowsConsoleApi } from "./server-console.js";
|
|
297
|
+
|
|
298
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../../../libs/plugins/workflows/src/lib/server.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport {\n checkEntitlement,\n type HostFunction,\n type HostVariable,\n type HostWebhook,\n type HostWorkflow,\n resolveOrgEntitlements,\n runWorkflow,\n} from '@aglyn/aglyn/server'\nimport {\n registerPluginApiRoute,\n registerPluginJob,\n type PluginApiHandler,\n} from '@aglyn/aglyn/server'\nimport { firebaseAdmin, getOrgForHost } from '@aglyn/tenant-data-admin'\nimport { timingSafeEqual } from 'crypto'\nimport { FieldValue } from 'firebase-admin/firestore'\nimport { BUNDLE_ID as WORKFLOWS_BUNDLE_ID } from './constants/bundle-common'\nimport { registerWorkflowsServerDeclarations } from './declarations.server'\nimport {\n automationRunEnv,\n executeWorkflow,\n runDueFlowEnrollments,\n workflowContextFromDocs,\n} from './engine/run-event-actions'\nimport {\n type AutomationWorkflow,\n workflowHasActionSteps,\n} from './engine/workflow-steps'\n\n/*==========================================\n * THE BEAT THAT MAKES A WAIT STEP REAL.\n *\n * A `wait` step suspends a run into a `flowEnrollments` row and returns; this\n * is the only thing that ever comes back for it. Without a registration here\n * the wait step would be a delay that never ends — the exact failure\n * `process-abandoned.ts` documents next door, where a Pro entitlement sat\n * behind an HTTP door nothing ever POSTed to.\n *\n * Module scope, like the commerce and bookings registrations: the runner\n * route reaches plugin jobs through `ensureAll(['tenantApi'])`, so a\n * registration inside `registerWorkflowsApi()` would depend on which entry\n * point happened to be loaded.\n *\n * ## Every minute, and why that is cheap\n *\n * `FLOW_WAIT_MIN_MINUTES` is one, so the beat has to be one — a fifteen-minute\n * sweep would make the shortest wait anybody can author wrong by up to\n * fourteen minutes. It costs one collection-group query per minute, which\n * returns nothing at all on a platform with no flow due, because the query\n * asks for `resumeAtMs <= now` rather than for the enrolled population.\n *\n * Bounded and idempotent, the two properties the runner requires: the scan\n * budget bounds one pass, and a transactional claim means an overlapping or\n * repeated beat cannot run the same person's step twice.\n *=========================================*/\nregisterPluginJob({\n pluginId: WORKFLOWS_BUNDLE_ID,\n name: 'resume-flow-waits',\n intervalMinutes: 1,\n description:\n 'Continue automations whose wait step has ended, and time out those ' +\n 'waiting for an event that never arrived.',\n lockdown: { scope: 'per-host' },\n handler: async (gate) => {\n await runDueFlowEnrollments(gate)\n },\n})\n\n// Best-effort per-instance rate limit (mirrors forms/submit).\nconst recentByHook = new Map<string, number[]>()\nconst RATE_WINDOW_MS = 60_000\nconst RATE_MAX = 30\n\nfunction rateLimited(key: string): boolean {\n const now = Date.now()\n const hits = (recentByHook.get(key) ?? []).filter(\n (t) => now - t < RATE_WINDOW_MS,\n )\n hits.push(now)\n recentByHook.set(key, hits)\n return hits.length > RATE_MAX\n}\n\nfunction secretsMatch(expected: string, provided: string): boolean {\n if (!expected || expected.length !== provided.length) return false\n return timingSafeEqual(\n new Uint8Array(Buffer.from(expected)),\n new Uint8Array(Buffer.from(provided)),\n )\n}\n\n/**\n * Inbound webhook endpoint (AGL-149): external systems POST JSON to\n * `/api/hooks/{hostId}/{hookId}` with the hook's secret in\n * `x-aglyn-secret`; a valid call enrolls the configured workflow with the\n * payload's top-level primitives in scope. Business tier (`webhooks`\n * flag); runs bill against the workflow-runs meter like any other run —\n * `workflowRunsPerMonth` is checked before the run and\n * `hosts/{id}/counters/workflowRuns` is incremented after it (AGL-2228).\n * That sentence was here before either half of it was true.\n */\nconst inboundHookHandler: PluginApiHandler = async (req, res) => {\n if (req.method !== 'POST') {\n return res.status(405).json({ error: 'Method not allowed' })\n }\n const hostId = String(req.query['hostId'] ?? '')\n const hookId = String(req.query['hookId'] ?? '')\n if (!hostId || !hookId) {\n return res.status(400).json({ error: 'Invalid webhook address' })\n }\n if (rateLimited(`${hostId}/${hookId}`)) {\n return res.status(429).json({ error: 'Too many requests' })\n }\n\n try {\n const firestore = firebaseAdmin.app().firestore()\n const hostRef = firestore.collection('hosts').doc(hostId)\n const hookSnapshot = await hostRef.collection('webhooks').doc(hookId).get()\n const hook = hookSnapshot.data() as HostWebhook | undefined\n if (\n !hook ||\n hookSnapshot.get('deletedAt') ||\n hook.direction !== 'inbound' ||\n hook.enabled === false\n ) {\n return res.status(404).json({ error: 'Unknown webhook' })\n }\n const provided = String(req.headers['x-aglyn-secret'] ?? '')\n if (!secretsMatch(hook.secret ?? '', provided)) {\n return res.status(401).json({ error: 'Bad secret' })\n }\n\n // Plan/quota gates ride the owning org's doc (AGL-238).\n const owner = await getOrgForHost(hostId)\n const org = owner?.org\n if (!checkEntitlement(org as any, 'webhooks')) {\n return res\n .status(403)\n .json({ error: 'Webhooks are not enabled on this site' })\n }\n /*\n * The MONTHLY RUN CAP, which this handler's own docblock claimed for\n * years — \"runs bill against the workflow-runs meter like any other run\"\n * — and did not have. It read neither `workflowRunsPerMonth` nor\n * `hosts/{id}/counters/workflowRuns`, and it wrote neither, so an inbound\n * hook was a workflow execution that no cap could refuse and no meter\n * could see: the customer's usage card, the usage-alerts cron and the\n * COGS rollup all read a counter this path never moved.\n *\n * The refusal is a 402 rather than the silent `return` of\n * `runEventWorkflows`: that path is fired from a visitor request whose\n * success must not depend on the workflow, where this one is an\n * integration calling us on purpose and a caller that gets a 200 for a\n * run that did not happen will keep sending. `Retry-After` is deliberately\n * absent — the month, not a delay, is what clears this.\n *\n * The plan-less/unreadable org resolves as FREE\n * (`workflowRunsPerMonth: 0`), so an org doc we cannot read refuses rather\n * than runs. `checkEntitlement(webhooks)` above already refuses free on\n * today's price list; this is not a second gate on the same fact, because\n * a staff `entitlementOverrides` can grant `webhooks` without granting\n * runs, and because the cap is what bounds a BUSINESS org's spend.\n *\n * Read-then-write, like the event path, and bounded the same way: the\n * per-hook limiter above is 30/60s, so the overshoot a race can buy is\n * bounded by concurrency rather than unbounded by design. Making it\n * atomic means a transaction around the whole run and is the same trade\n * `runEventWorkflows` declined.\n */\n const monthKey = new Date().toISOString().slice(0, 7)\n const runCounterRef = hostRef.collection('counters').doc('workflowRuns')\n const runLimit = resolveOrgEntitlements(org as any).workflowRunsPerMonth\n const runsUsed = Number((await runCounterRef.get()).get(monthKey) ?? 0)\n if (!(runsUsed + 1 <= runLimit)) {\n return res.status(402).json({\n error: `This site has used its ${runLimit} workflow runs for the month`,\n })\n }\n\n // Top-level primitives from the JSON body join the workflow scope.\n const body =\n typeof req.body === 'string'\n ? JSON.parse(req.body || '{}')\n : (req.body ?? {})\n const scope: Record<string, string | number | boolean> = {}\n for (const [key, value] of Object.entries(body)) {\n if (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n ) {\n scope[key.slice(0, 64)] =\n typeof value === 'string' ? value.slice(0, 2000) : value\n }\n }\n\n const [functionDocs, variableDocs, workflowDocs] = await Promise.all([\n hostRef.collection('functions').limit(100).get(),\n hostRef.collection('variables').limit(100).get(),\n hostRef.collection('workflows').limit(100).get(),\n ])\n const byName = <T extends { name?: string; deletedAt?: unknown }>(\n docs: FirebaseFirestore.QueryDocumentSnapshot[],\n ) => {\n const map: Record<string, T> = {}\n for (const doc of docs) {\n const data = doc.data() as T\n if (data?.name && !data.deletedAt) map[data.name] = data\n }\n return map\n }\n const workflows = byName<HostWorkflow>(workflowDocs.docs)\n const workflow = workflows[hook.workflowName?.trim() ?? '']\n if (!workflow) {\n return res.status(422).json({ error: 'No workflow bound to this hook' })\n }\n\n const hookEvent = `hook:${hook.name ?? hookId}`\n /*\n * A workflow of function calls is evaluated, as it always has been. One\n * with Actions steps is PERFORMED by the engine's executor — the posted\n * JSON is its payload — under the Actions tier gates, step by step, and\n * it is still one run on the meter below. Its working set is built from\n * the documents read above rather than read again.\n */\n const outcome: { error: string | null; value: unknown; summary: string } =\n workflowHasActionSteps(workflow)\n ? await (async () => {\n const workflowDoc = workflowDocs.docs.find(\n (doc) =>\n !doc.get('deletedAt') &&\n doc.get('name') === hook.workflowName?.trim(),\n )\n const execution = await executeWorkflow(\n automationRunEnv({\n hostId,\n hostRef,\n owner,\n depth: 0,\n loadWorkflowContext: async () =>\n workflowContextFromDocs(\n functionDocs.docs,\n variableDocs.docs,\n workflowDocs.docs,\n ),\n }),\n {\n kind: 'workflow',\n id: workflowDoc?.id ?? '',\n name: workflow.name ?? '',\n },\n workflow as AutomationWorkflow,\n hookEvent,\n scope,\n )\n return {\n error: execution.errors.length\n ? execution.errors.join('; ')\n : null,\n value: execution.value,\n summary: execution.outcomes.length\n ? execution.outcomes.join(' · ')\n : `Ran ${hook.workflowName}`,\n }\n })()\n : (() => {\n const run = runWorkflow(\n workflow,\n byName<HostFunction>(functionDocs.docs),\n byName<HostVariable>(variableDocs.docs),\n { event: hookEvent, ...scope },\n { workflows },\n )\n return run.ok === false\n ? { error: run.error, value: undefined, summary: '' }\n : {\n error: null,\n value: run.value,\n summary: `Ran ${hook.workflowName}`,\n }\n })()\n const failed = outcome.error !== null\n await hostRef\n .collection('activity')\n .add({\n actorId: null,\n actorEmail: null,\n action: failed\n ? `Inbound webhook run failed: ${outcome.error}`.slice(0, 300)\n : `Inbound webhook ran \"${hook.workflowName}\"`,\n // The run-history shape (AGL-2222) — without `result` this execution\n // is invisible to the Runs table, which reads a verdict and not prose.\n result: failed ? 'failed' : 'succeeded',\n trigger: hookEvent,\n summary: failed\n ? String(outcome.error).slice(0, 300)\n : outcome.summary.slice(0, 300),\n target: { type: 'workflow', id: hookId, name: hook.name ?? '' },\n createdAt: FieldValue.serverTimestamp(),\n })\n .catch(() => undefined)\n\n // The run happened, so it counts — including a FAILED one, exactly as\n // `runEventWorkflows` counts its failures. A run that executed and threw\n // spent the same compute as one that returned a value; only a run that\n // never started (the cap above, a missing workflow) must not count.\n await runCounterRef\n .set({ [monthKey]: FieldValue.increment(1) }, { merge: true })\n .catch(() => undefined)\n\n if (failed) return res.status(422).json({ error: outcome.error })\n return res.status(200).json({ ok: true, value: outcome.value })\n } catch (error) {\n console.error(error)\n return res.status(500).json({ error: 'Webhook failed' })\n }\n}\n\n/**\n * Registers the workflows plugin's public API routes (AGL-396), and the\n * engine's host-event listener beside them for a process whose boot did not\n * (see `declarations.server.ts`).\n */\nexport function registerWorkflowsApi(): void {\n registerWorkflowsServerDeclarations()\n registerPluginApiRoute('hooks/[hostId]/[hookId]', inboundHookHandler)\n}\n\n/**\n * The console half (AGL-2919), re-exported so one entry point serves both\n * surfaces: the manifest generator resolves every server surface through\n * `@aglyn/plugins-workflows/server`, and a second entry point would be a second\n * thing to keep in step with plugins.config.json.\n */\nexport { registerWorkflowsConsoleApi } from './server-console'\n"],"names":["checkEntitlement","resolveOrgEntitlements","runWorkflow","registerPluginApiRoute","registerPluginJob","firebaseAdmin","getOrgForHost","timingSafeEqual","FieldValue","BUNDLE_ID","WORKFLOWS_BUNDLE_ID","registerWorkflowsServerDeclarations","automationRunEnv","executeWorkflow","runDueFlowEnrollments","workflowContextFromDocs","workflowHasActionSteps","pluginId","name","intervalMinutes","description","lockdown","scope","handler","gate","recentByHook","Map","RATE_WINDOW_MS","RATE_MAX","rateLimited","key","now","Date","hits","get","filter","t","push","set","length","secretsMatch","expected","provided","Uint8Array","Buffer","from","inboundHookHandler","req","res","method","status","json","error","hostId","String","query","hookId","hook","firestore","app","hostRef","collection","doc","hookSnapshot","data","direction","enabled","headers","secret","owner","org","monthKey","toISOString","slice","runCounterRef","runLimit","workflowRunsPerMonth","runsUsed","Number","body","JSON","parse","value","Object","entries","functionDocs","variableDocs","workflowDocs","Promise","all","limit","byName","docs","map","deletedAt","workflows","workflow","workflowName","trim","hookEvent","outcome","workflowDoc","find","execution","depth","loadWorkflowContext","kind","id","errors","join","summary","outcomes","run","event","ok","undefined","failed","add","actorId","actorEmail","action","result","trigger","target","type","createdAt","serverTimestamp","catch","increment","merge","console","registerWorkflowsApi","registerWorkflowsConsoleApi"],"mappings":";AAAA;;;;;;;;;;;;;;;CAeC,GAED,SACEA,gBAAgB,EAKhBC,sBAAsB,EACtBC,WAAW,QACN,sBAAqB;AAC5B,SACEC,sBAAsB,EACtBC,iBAAiB,QAEZ,sBAAqB;AAC5B,SAASC,aAAa,EAAEC,aAAa,QAAQ,2BAA0B;AACvE,SAASC,eAAe,QAAQ,SAAQ;AACxC,SAASC,UAAU,QAAQ,2BAA0B;AACrD,SAASC,aAAaC,mBAAmB,QAAQ,+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