@shware/workflow 3.2.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +100 -29
- package/dist/apns.cjs +113 -26
- package/dist/apns.cjs.map +1 -1
- package/dist/apns.d.cts +52 -6
- package/dist/apns.d.cts.map +1 -1
- package/dist/apns.d.mts +52 -6
- package/dist/apns.d.mts.map +1 -1
- package/dist/apns.mjs +111 -27
- package/dist/apns.mjs.map +1 -1
- package/dist/aws/engine-step.cjs +5 -5
- package/dist/aws/engine-step.cjs.map +1 -1
- package/dist/aws/engine-step.d.cts +8 -2
- package/dist/aws/engine-step.d.cts.map +1 -1
- package/dist/aws/engine-step.d.mts +8 -2
- package/dist/aws/engine-step.d.mts.map +1 -1
- package/dist/aws/engine-step.mjs +5 -5
- package/dist/aws/engine-step.mjs.map +1 -1
- package/dist/aws/index.cjs +47 -6
- package/dist/aws/index.cjs.map +1 -1
- package/dist/aws/index.d.cts +2 -2
- package/dist/aws/index.d.cts.map +1 -1
- package/dist/aws/index.d.mts +2 -2
- package/dist/aws/index.d.mts.map +1 -1
- package/dist/aws/index.mjs +47 -6
- package/dist/aws/index.mjs.map +1 -1
- package/dist/aws/instances.cjs +29 -6
- package/dist/aws/instances.cjs.map +1 -1
- package/dist/aws/instances.d.cts +11 -1
- package/dist/aws/instances.d.cts.map +1 -1
- package/dist/aws/instances.d.mts +11 -1
- package/dist/aws/instances.d.mts.map +1 -1
- package/dist/aws/instances.mjs +27 -4
- package/dist/aws/instances.mjs.map +1 -1
- package/dist/client.cjs +4 -1
- package/dist/client.cjs.map +1 -1
- package/dist/client.d.cts +2 -2
- package/dist/client.d.cts.map +1 -1
- package/dist/client.d.mts +2 -2
- package/dist/client.d.mts.map +1 -1
- package/dist/client.mjs +4 -1
- package/dist/client.mjs.map +1 -1
- package/dist/cloudflare/bindings.cjs +28 -25
- package/dist/cloudflare/bindings.cjs.map +1 -1
- package/dist/cloudflare/bindings.d.cts +17 -129
- package/dist/cloudflare/bindings.d.cts.map +1 -1
- package/dist/cloudflare/bindings.d.mts +17 -129
- package/dist/cloudflare/bindings.d.mts.map +1 -1
- package/dist/cloudflare/bindings.mjs +28 -23
- package/dist/cloudflare/bindings.mjs.map +1 -1
- package/dist/cloudflare/d1-env.cjs +6 -6
- package/dist/cloudflare/d1-env.cjs.map +1 -1
- package/dist/cloudflare/d1-env.d.cts +5 -5
- package/dist/cloudflare/d1-env.d.mts +5 -5
- package/dist/cloudflare/d1-env.mjs +6 -6
- package/dist/cloudflare/d1-env.mjs.map +1 -1
- package/dist/cloudflare/index.cjs +28 -18
- package/dist/cloudflare/index.d.cts +8 -4
- package/dist/cloudflare/index.d.mts +8 -4
- package/dist/cloudflare/index.mjs +9 -5
- package/dist/cloudflare/runner.cjs +29 -14
- package/dist/cloudflare/runner.cjs.map +1 -1
- package/dist/cloudflare/runner.d.cts +9 -2
- package/dist/cloudflare/runner.d.cts.map +1 -1
- package/dist/cloudflare/runner.d.mts +9 -2
- package/dist/cloudflare/runner.d.mts.map +1 -1
- package/dist/cloudflare/runner.mjs +28 -13
- package/dist/cloudflare/runner.mjs.map +1 -1
- package/dist/cloudflare/schema.sql +27 -6
- package/dist/cloudflare/worker.cjs +19 -9
- package/dist/cloudflare/worker.cjs.map +1 -1
- package/dist/cloudflare/worker.d.cts +2 -2
- package/dist/cloudflare/worker.d.cts.map +1 -1
- package/dist/cloudflare/worker.d.mts +2 -2
- package/dist/cloudflare/worker.d.mts.map +1 -1
- package/dist/cloudflare/worker.mjs +19 -9
- package/dist/cloudflare/worker.mjs.map +1 -1
- package/dist/config.cjs +21 -5
- package/dist/config.cjs.map +1 -1
- package/dist/config.mjs +21 -5
- package/dist/config.mjs.map +1 -1
- package/dist/dsl/action.cjs +3 -6
- package/dist/dsl/action.cjs.map +1 -1
- package/dist/dsl/action.d.cts +12 -11
- package/dist/dsl/action.d.cts.map +1 -1
- package/dist/dsl/action.d.mts +12 -11
- package/dist/dsl/action.d.mts.map +1 -1
- package/dist/dsl/action.mjs +3 -6
- package/dist/dsl/action.mjs.map +1 -1
- package/dist/dsl/bundle.cjs +35 -31
- package/dist/dsl/bundle.cjs.map +1 -1
- package/dist/dsl/bundle.d.cts.map +1 -1
- package/dist/dsl/bundle.d.mts.map +1 -1
- package/dist/dsl/bundle.mjs +35 -31
- package/dist/dsl/bundle.mjs.map +1 -1
- package/dist/dsl/condition.cjs +13 -1
- package/dist/dsl/condition.cjs.map +1 -1
- package/dist/dsl/condition.d.cts +9 -1
- package/dist/dsl/condition.d.cts.map +1 -1
- package/dist/dsl/condition.d.mts +9 -1
- package/dist/dsl/condition.d.mts.map +1 -1
- package/dist/dsl/condition.mjs +13 -2
- package/dist/dsl/condition.mjs.map +1 -1
- package/dist/dsl/flow.cjs +33 -11
- package/dist/dsl/flow.cjs.map +1 -1
- package/dist/dsl/flow.d.cts +9 -1
- package/dist/dsl/flow.d.cts.map +1 -1
- package/dist/dsl/flow.d.mts +9 -1
- package/dist/dsl/flow.d.mts.map +1 -1
- package/dist/dsl/flow.mjs +34 -13
- package/dist/dsl/flow.mjs.map +1 -1
- package/dist/dsl/workflow.cjs +2 -3
- package/dist/dsl/workflow.cjs.map +1 -1
- package/dist/dsl/workflow.d.cts.map +1 -1
- package/dist/dsl/workflow.d.mts.map +1 -1
- package/dist/dsl/workflow.mjs +3 -4
- package/dist/dsl/workflow.mjs.map +1 -1
- package/dist/email-sender.cjs +24 -0
- package/dist/email-sender.cjs.map +1 -1
- package/dist/email-sender.d.cts +18 -0
- package/dist/email-sender.d.cts.map +1 -1
- package/dist/email-sender.d.mts +18 -0
- package/dist/email-sender.d.mts.map +1 -1
- package/dist/email-sender.mjs +24 -1
- package/dist/email-sender.mjs.map +1 -1
- package/dist/engine/actions.cjs +1 -8
- package/dist/engine/actions.cjs.map +1 -1
- package/dist/engine/actions.d.cts +1 -12
- package/dist/engine/actions.d.cts.map +1 -1
- package/dist/engine/actions.d.mts +1 -12
- package/dist/engine/actions.d.mts.map +1 -1
- package/dist/engine/actions.mjs +1 -8
- package/dist/engine/actions.mjs.map +1 -1
- package/dist/engine/condition.cjs +25 -5
- package/dist/engine/condition.cjs.map +1 -1
- package/dist/engine/condition.d.cts +12 -3
- package/dist/engine/condition.d.cts.map +1 -1
- package/dist/engine/condition.d.mts +12 -3
- package/dist/engine/condition.d.mts.map +1 -1
- package/dist/engine/condition.mjs +25 -6
- package/dist/engine/condition.mjs.map +1 -1
- package/dist/engine/index.cjs +3 -0
- package/dist/engine/index.d.cts +5 -5
- package/dist/engine/index.d.mts +5 -5
- package/dist/engine/index.mjs +4 -4
- package/dist/engine/interpreter.cjs +27 -20
- package/dist/engine/interpreter.cjs.map +1 -1
- package/dist/engine/interpreter.d.cts.map +1 -1
- package/dist/engine/interpreter.d.mts.map +1 -1
- package/dist/engine/interpreter.mjs +27 -20
- package/dist/engine/interpreter.mjs.map +1 -1
- package/dist/engine/ports.d.cts +21 -6
- package/dist/engine/ports.d.cts.map +1 -1
- package/dist/engine/ports.d.mts +21 -6
- package/dist/engine/ports.d.mts.map +1 -1
- package/dist/engine/retry.cjs +13 -0
- package/dist/engine/retry.cjs.map +1 -1
- package/dist/engine/retry.d.cts +12 -0
- package/dist/engine/retry.d.cts.map +1 -1
- package/dist/engine/retry.d.mts +12 -0
- package/dist/engine/retry.d.mts.map +1 -1
- package/dist/engine/retry.mjs +13 -1
- package/dist/engine/retry.mjs.map +1 -1
- package/dist/engine/time-scale.cjs +90 -15
- package/dist/engine/time-scale.cjs.map +1 -1
- package/dist/engine/time-scale.d.cts +9 -6
- package/dist/engine/time-scale.d.cts.map +1 -1
- package/dist/engine/time-scale.d.mts +9 -6
- package/dist/engine/time-scale.d.mts.map +1 -1
- package/dist/engine/time-scale.mjs +90 -16
- package/dist/engine/time-scale.mjs.map +1 -1
- package/dist/fcm.cjs +111 -38
- package/dist/fcm.cjs.map +1 -1
- package/dist/fcm.d.cts +45 -5
- package/dist/fcm.d.cts.map +1 -1
- package/dist/fcm.d.mts +45 -5
- package/dist/fcm.d.mts.map +1 -1
- package/dist/fcm.mjs +110 -39
- package/dist/fcm.mjs.map +1 -1
- package/dist/hash.cjs +6 -6
- package/dist/hash.cjs.map +1 -1
- package/dist/hash.mjs +6 -6
- package/dist/hash.mjs.map +1 -1
- package/dist/host/auth.cjs +49 -0
- package/dist/host/auth.cjs.map +1 -0
- package/dist/host/auth.d.cts +21 -0
- package/dist/host/auth.d.cts.map +1 -0
- package/dist/host/auth.d.mts +21 -0
- package/dist/host/auth.d.mts.map +1 -0
- package/dist/host/auth.mjs +47 -0
- package/dist/host/auth.mjs.map +1 -0
- package/dist/host/channels.cjs +118 -40
- package/dist/host/channels.cjs.map +1 -1
- package/dist/host/channels.d.cts +27 -1
- package/dist/host/channels.d.cts.map +1 -1
- package/dist/host/channels.d.mts +27 -1
- package/dist/host/channels.d.mts.map +1 -1
- package/dist/host/channels.mjs +121 -44
- package/dist/host/channels.mjs.map +1 -1
- package/dist/host/execute.cjs +14 -2
- package/dist/host/execute.cjs.map +1 -1
- package/dist/host/execute.d.cts +4 -4
- package/dist/host/execute.d.cts.map +1 -1
- package/dist/host/execute.d.mts +4 -4
- package/dist/host/execute.d.mts.map +1 -1
- package/dist/host/execute.mjs +13 -1
- package/dist/host/execute.mjs.map +1 -1
- package/dist/host/fresh-read.cjs +30 -0
- package/dist/host/fresh-read.cjs.map +1 -0
- package/dist/host/fresh-read.d.cts +18 -0
- package/dist/host/fresh-read.d.cts.map +1 -0
- package/dist/host/fresh-read.d.mts +18 -0
- package/dist/host/fresh-read.d.mts.map +1 -0
- package/dist/host/fresh-read.mjs +29 -0
- package/dist/host/fresh-read.mjs.map +1 -0
- package/dist/host/http.cjs +321 -0
- package/dist/host/http.cjs.map +1 -0
- package/dist/host/http.d.cts +54 -0
- package/dist/host/http.d.cts.map +1 -0
- package/dist/host/http.d.mts +54 -0
- package/dist/host/http.d.mts.map +1 -0
- package/dist/host/http.mjs +317 -0
- package/dist/host/http.mjs.map +1 -0
- package/dist/host/{router.cjs → ingest.cjs} +147 -175
- package/dist/host/ingest.cjs.map +1 -0
- package/dist/host/{router.d.cts → ingest.d.cts} +48 -30
- package/dist/host/ingest.d.cts.map +1 -0
- package/dist/host/{router.d.mts → ingest.d.mts} +48 -30
- package/dist/host/ingest.d.mts.map +1 -0
- package/dist/host/{router.mjs → ingest.mjs} +144 -173
- package/dist/host/ingest.mjs.map +1 -0
- package/dist/host/journey-host.cjs +65 -93
- package/dist/host/journey-host.cjs.map +1 -1
- package/dist/host/journey-host.d.cts +19 -26
- package/dist/host/journey-host.d.cts.map +1 -1
- package/dist/host/journey-host.d.mts +19 -26
- package/dist/host/journey-host.d.mts.map +1 -1
- package/dist/host/journey-host.mjs +65 -93
- package/dist/host/journey-host.mjs.map +1 -1
- package/dist/host/platform.cjs +21 -0
- package/dist/host/platform.cjs.map +1 -0
- package/dist/host/platform.d.cts +126 -0
- package/dist/host/platform.d.cts.map +1 -0
- package/dist/host/platform.d.mts +126 -0
- package/dist/host/platform.d.mts.map +1 -0
- package/dist/host/platform.mjs +19 -0
- package/dist/host/platform.mjs.map +1 -0
- package/dist/host/senders.cjs +18 -9
- package/dist/host/senders.cjs.map +1 -1
- package/dist/host/senders.d.cts +9 -4
- package/dist/host/senders.d.cts.map +1 -1
- package/dist/host/senders.d.mts +9 -4
- package/dist/host/senders.d.mts.map +1 -1
- package/dist/host/senders.mjs +18 -9
- package/dist/host/senders.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.mjs +1 -1
- package/dist/ir.cjs +5 -7
- package/dist/ir.cjs.map +1 -1
- package/dist/ir.d.cts +3 -12
- package/dist/ir.d.cts.map +1 -1
- package/dist/ir.d.mts +3 -12
- package/dist/ir.d.mts.map +1 -1
- package/dist/ir.mjs +5 -7
- package/dist/ir.mjs.map +1 -1
- package/dist/plan.cjs +27 -33
- package/dist/plan.cjs.map +1 -1
- package/dist/plan.d.cts +1 -1
- package/dist/plan.d.cts.map +1 -1
- package/dist/plan.d.mts +1 -1
- package/dist/plan.d.mts.map +1 -1
- package/dist/plan.mjs +27 -33
- package/dist/plan.mjs.map +1 -1
- package/dist/reporting/observer.cjs +1 -0
- package/dist/reporting/observer.cjs.map +1 -1
- package/dist/reporting/observer.mjs +1 -0
- package/dist/reporting/observer.mjs.map +1 -1
- package/dist/reporting/tracking.cjs +19 -4
- package/dist/reporting/tracking.cjs.map +1 -1
- package/dist/reporting/tracking.d.cts +13 -11
- package/dist/reporting/tracking.d.cts.map +1 -1
- package/dist/reporting/tracking.d.mts +13 -11
- package/dist/reporting/tracking.d.mts.map +1 -1
- package/dist/reporting/tracking.mjs +19 -4
- package/dist/reporting/tracking.mjs.map +1 -1
- package/dist/store/d1.cjs +88 -29
- package/dist/store/d1.cjs.map +1 -1
- package/dist/store/d1.d.cts +29 -11
- package/dist/store/d1.d.cts.map +1 -1
- package/dist/store/d1.d.mts +29 -11
- package/dist/store/d1.d.mts.map +1 -1
- package/dist/store/d1.mjs +88 -29
- package/dist/store/d1.mjs.map +1 -1
- package/dist/store/erasure.cjs +22 -0
- package/dist/store/erasure.cjs.map +1 -0
- package/dist/store/erasure.d.cts +18 -0
- package/dist/store/erasure.d.cts.map +1 -0
- package/dist/store/erasure.d.mts +18 -0
- package/dist/store/erasure.d.mts.map +1 -0
- package/dist/store/erasure.mjs +21 -0
- package/dist/store/erasure.mjs.map +1 -0
- package/dist/store/index.cjs +2 -0
- package/dist/store/index.cjs.map +1 -1
- package/dist/store/index.d.cts +67 -13
- package/dist/store/index.d.cts.map +1 -1
- package/dist/store/index.d.mts +67 -13
- package/dist/store/index.d.mts.map +1 -1
- package/dist/store/index.mjs +2 -1
- package/dist/store/index.mjs.map +1 -1
- package/dist/store/postgres-reporting.cjs +125 -62
- package/dist/store/postgres-reporting.cjs.map +1 -1
- package/dist/store/postgres-reporting.d.cts +30 -2
- package/dist/store/postgres-reporting.d.cts.map +1 -1
- package/dist/store/postgres-reporting.d.mts +30 -2
- package/dist/store/postgres-reporting.d.mts.map +1 -1
- package/dist/store/postgres-reporting.mjs +125 -62
- package/dist/store/postgres-reporting.mjs.map +1 -1
- package/dist/store/postgres.cjs +179 -60
- package/dist/store/postgres.cjs.map +1 -1
- package/dist/store/postgres.d.cts +44 -7
- package/dist/store/postgres.d.cts.map +1 -1
- package/dist/store/postgres.d.mts +44 -7
- package/dist/store/postgres.d.mts.map +1 -1
- package/dist/store/postgres.mjs +179 -60
- package/dist/store/postgres.mjs.map +1 -1
- package/dist/store/tables.cjs +7 -5
- package/dist/store/tables.cjs.map +1 -1
- package/dist/store/tables.d.cts.map +1 -1
- package/dist/store/tables.d.mts.map +1 -1
- package/dist/store/tables.mjs +7 -5
- package/dist/store/tables.mjs.map +1 -1
- package/dist/store/user-lock.cjs +43 -0
- package/dist/store/user-lock.cjs.map +1 -0
- package/dist/store/user-lock.d.cts +32 -0
- package/dist/store/user-lock.d.cts.map +1 -0
- package/dist/store/user-lock.d.mts +32 -0
- package/dist/store/user-lock.d.mts.map +1 -0
- package/dist/store/user-lock.mjs +40 -0
- package/dist/store/user-lock.mjs.map +1 -0
- package/dist/transports/cloudflare-email.cjs +3 -2
- package/dist/transports/cloudflare-email.cjs.map +1 -1
- package/dist/transports/cloudflare-email.mjs +3 -2
- package/dist/transports/cloudflare-email.mjs.map +1 -1
- package/dist/transports/ses.cjs +52 -7
- package/dist/transports/ses.cjs.map +1 -1
- package/dist/transports/ses.d.cts +9 -1
- package/dist/transports/ses.d.cts.map +1 -1
- package/dist/transports/ses.d.mts +9 -1
- package/dist/transports/ses.d.mts.map +1 -1
- package/dist/transports/ses.mjs +52 -8
- package/dist/transports/ses.mjs.map +1 -1
- package/dist/webpush.cjs +133 -47
- package/dist/webpush.cjs.map +1 -1
- package/dist/webpush.d.cts +49 -8
- package/dist/webpush.d.cts.map +1 -1
- package/dist/webpush.d.mts +49 -8
- package/dist/webpush.d.mts.map +1 -1
- package/dist/webpush.mjs +130 -47
- package/dist/webpush.mjs.map +1 -1
- package/package.json +1 -1
- package/src/cloudflare/schema.sql +27 -6
- package/dist/host/router.cjs.map +0 -1
- package/dist/host/router.d.cts.map +0 -1
- package/dist/host/router.d.mts.map +0 -1
- package/dist/host/router.mjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"condition.mjs","names":[],"sources":["../../src/dsl/condition.ts"],"sourcesContent":["import type { ConditionIR, SourceLocIR } from '../ir';\nimport { captureLoc } from '../provenance';\nimport { type Duration, durationIR } from './base';\nimport {\n type EventRef,\n PAYLOAD_PATH,\n type PayloadRef,\n type PayloadRefs,\n type UserPropertyRef,\n payloadRefs,\n} from './refs';\nimport type { Channel } from './template';\n\n/**\n * Conditions — drizzle-style predicate expressions: free functions (eq/gt/…)\n * composed with and/or/not, plus `segment` for naming an expression as a\n * top-level asset. A condition is an opaque handle wrapping its ConditionIR.\n *\n * Type techniques:\n * - Types flow in from the reference's phantom type; operator applicability is\n * a signature constraint (gt only takes string|number refs, contains only\n * string ones), mirroring customer.io's condition panel.\n * - Value parameters are always NoInfer: types come from the reference only,\n * which stops eq(ref, 'typo') from widening T to include the bad value.\n *\n * TODO: JSON array 'where at least one'、JSON object 'has the property'。\n */\n\n/** Opaque condition handle — what predicates, combinators and segments all produce. */\nexport interface Condition {\n readonly __condition: true;\n}\n\ninterface ConditionInternal extends Condition {\n readonly ir: ConditionIR;\n}\n\nconst cond = (ir: ConditionIR, loc?: SourceLocIR): Condition => {\n const impl: ConditionInternal = {\n __condition: true,\n ir: loc === undefined ? ir : { ...ir, meta: { loc } },\n };\n return impl;\n};\n\n/** @internal unwrap a condition to its IR — used by flow/trigger/workflow builders */\nexport const condIR = (c: Condition): ConditionIR => {\n // Partial: the cast is unsound for hand-rolled objects — exactly what this checks\n const ir = (c as Partial<ConditionInternal>).ir;\n if (ir === undefined) {\n // A hand-rolled `{ __condition: true }` would otherwise surface as a\n // baffling zod error at toIR() time, far away from the actual mistake.\n throw new Error(\n 'Condition was not created by this DSL — use the predicates (eq/gt/…), combinators (and/or/not) or segment()'\n );\n }\n return ir;\n};\n\ntype Scalar = string | number | boolean;\n\n/**\n * Predicates accept either kind of reference: a user property (profile\n * condition) or an event payload field (only valid inside a `where` — the\n * bundle compiler enforces the placement, since both produce `Condition`).\n */\ntype CondRef<T> = UserPropertyRef<T> | PayloadRef<T>;\n\n/**\n * A payload ref identifies itself by a symbol key, and a user-property ref by\n * the absence of one. Nothing here reads a *string* key off the reference: a\n * payload ref hands out sub-refs for every string key, so a field named `type`\n * or `path` would otherwise answer in place of the ref itself.\n */\nconst payloadPathOf = (ref: CondRef<unknown>): string | undefined =>\n (ref as Partial<PayloadRef<unknown>>)[PAYLOAD_PATH];\n\nfunction prop(\n ref: CondRef<unknown>,\n op:\n | 'eq'\n | 'ne'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'between'\n | 'not_between'\n | 'in_array'\n | 'not_in_array'\n | 'exists'\n | 'not_exists'\n | 'contains'\n | 'not_contains',\n value?: Scalar,\n values?: readonly Scalar[],\n loc?: SourceLocIR\n): Condition {\n const payloadPath = payloadPathOf(ref);\n return cond(\n {\n type: payloadPath !== undefined ? 'payload' : 'property',\n path: payloadPath ?? (ref as UserPropertyRef<unknown>).path,\n op,\n ...(value !== undefined ? { value } : {}),\n ...(values !== undefined ? { values: [...values] } : {}),\n },\n loc\n );\n}\n\nexport function eq<T>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'eq', value as Scalar, undefined, captureLoc(eq));\n}\nexport function ne<T>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'ne', value as Scalar, undefined, captureLoc(ne));\n}\nexport function gt<T extends string | number>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'gt', value, undefined, captureLoc(gt));\n}\nexport function gte<T extends string | number>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'gte', value, undefined, captureLoc(gte));\n}\nexport function lt<T extends string | number>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'lt', value, undefined, captureLoc(lt));\n}\nexport function lte<T extends string | number>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'lte', value, undefined, captureLoc(lte));\n}\nexport function between<T extends string | number>(\n ref: CondRef<T>,\n min: NoInfer<T>,\n max: NoInfer<T>\n): Condition {\n return prop(ref, 'between', undefined, [min, max], captureLoc(between));\n}\nexport function notBetween<T extends string | number>(\n ref: CondRef<T>,\n min: NoInfer<T>,\n max: NoInfer<T>\n): Condition {\n return prop(ref, 'not_between', undefined, [min, max], captureLoc(notBetween));\n}\nexport function inArray<T>(ref: CondRef<T>, values: readonly NoInfer<T>[]): Condition {\n return prop(ref, 'in_array', undefined, values as readonly Scalar[], captureLoc(inArray));\n}\nexport function notInArray<T>(ref: CondRef<T>, values: readonly NoInfer<T>[]): Condition {\n return prop(ref, 'not_in_array', undefined, values as readonly Scalar[], captureLoc(notInArray));\n}\nexport function exists(ref: CondRef<unknown>): Condition {\n return prop(ref, 'exists', undefined, undefined, captureLoc(exists));\n}\nexport function notExists(ref: CondRef<unknown>): Condition {\n return prop(ref, 'not_exists', undefined, undefined, captureLoc(notExists));\n}\nexport function contains<T extends string>(ref: CondRef<T>, value: string): Condition {\n return prop(ref, 'contains', value, undefined, captureLoc(contains));\n}\nexport function notContains<T extends string>(ref: CondRef<T>, value: string): Condition {\n return prop(ref, 'not_contains', value, undefined, captureLoc(notContains));\n}\n\nexport interface PerformedOptions {\n within?: Duration;\n count?: number;\n}\n\n/** A payload where clause: an arrow taking the typed payload-ref table. Runs once at construction — the result is a serializable condition tree in IR, never a closure. */\nexport type PayloadWhere<P> = (p: PayloadRefs<P>) => Condition;\n\n/**\n * Event predicate: performed an event (optionally within a window / at least N\n * times). \"Did not perform\" is `not(performed(...))` — expressed by the\n * combinator, so there is no separate notPerformed.\n *\n * The optional second argument narrows which events count by their payload —\n * an arrow receiving a typed payload reference table, with the ordinary\n * predicates applying. It compiles to a `where` subtree in IR (data the UI\n * renders), not a runtime closure:\n *\n * performed(e.login)\n * performed(e.login, (p) => and(eq(p.platform, 'web'), eq(p.tags.utm_source, 'meta')))\n * performed(e.purchase, (p) => gt(p.value, 100), { within: '30 days', count: 2 })\n * performed(e.purchase, { within: '30 days' }) // options without a where\n *\n * Time anchoring: evaluated inside a `goal` the count starts at workflow\n * entry, inside `waitUntil` at the moment the wait began (the engine anchors\n * them — a conversion or a wake must not be satisfied by pre-existing\n * history). Everywhere else (branch/filter/exitWhen/segments) it looks over\n * full history, bounded only by `within`.\n */\nexport function performed<P>(event: EventRef<P>, opts?: PerformedOptions): Condition;\nexport function performed<P>(\n event: EventRef<P>,\n where: PayloadWhere<P>,\n opts?: PerformedOptions\n): Condition;\nexport function performed<P>(\n event: EventRef<P>,\n whereOrOpts?: PayloadWhere<P> | PerformedOptions,\n maybeOpts?: PerformedOptions\n): Condition {\n const where = typeof whereOrOpts === 'function' ? whereOrOpts : undefined;\n const opts = typeof whereOrOpts === 'function' ? maybeOpts : whereOrOpts;\n return cond(\n {\n type: 'performed',\n event: event.name,\n ...(where !== undefined ? { where: condIR(where(payloadRefs<P>())) } : {}),\n ...(opts?.within !== undefined ? { within: durationIR(opts.within) } : {}),\n ...(opts?.count !== undefined ? { count: opts.count } : {}),\n },\n captureLoc(performed)\n );\n}\n\n/**\n * The user can be reached on a channel right now. For push it asks the host's\n * device directory (at least one device listed) — the engine keeps no device\n * state, so this is the way to branch on \"has the app on a device that allowed\n * notifications\"; for the other channels it checks the recipient property\n * (`email`, `phone`, …). Inside `waitUntil` it wakes on device changes\n * (`POST /devices/changed`) or profile updates respectively.\n *\n * .branch([reachable('push'), (w) => w.push(tip)], (w) => w.email(tip))\n *\n * (`.prefer([push.tip, email.tip], props)` is this branch for one push and one email.)\n */\nexport function reachable(channel: Channel): Condition {\n return cond({ type: 'reachable', channel }, captureLoc(reachable));\n}\n\n/** Condition combinators: nest freely. */\nexport function and(...conditions: readonly Condition[]): Condition {\n return cond({ type: 'and', conditions: conditions.map(condIR) }, captureLoc(and));\n}\nexport function or(...conditions: readonly Condition[]): Condition {\n return cond({ type: 'or', conditions: conditions.map(condIR) }, captureLoc(or));\n}\nexport function not(condition: Condition): Condition {\n return cond({ type: 'not', condition: condIR(condition) }, captureLoc(not));\n}\n\n/**\n * Segment: a named condition expression and a top-level asset — it shows up in\n * the UI sidebar, is reusable across workflows, is referenced by id in IR,\n * and has a continuously materialized membership count (the prerequisite for\n * segment triggers). Anonymous reuse is just a const expression; a one-off\n * check is an inline expression at the use site.\n * TODO, to match customer.io's panel: form / page / device / screen /\n * opt-out / message data(email opened、sms clicked、webhook …)\n */\nexport interface SegmentRef extends Condition {\n readonly __segment: true;\n /** Wire identity: segment references and the membership store are keyed on it (`SegmentIR.id`). */\n readonly id: string;\n}\n\n/** @internal the compiled shape behind a SegmentRef — compileBundle reads definition/loc off it */\nexport interface SegmentInternal extends SegmentRef {\n readonly ir: ConditionIR;\n /** Human label / description; metadata, so never part of the hash. */\n readonly meta: SegmentMeta | undefined;\n /** The segment's own definition (SegmentIR.condition), as opposed to a reference by id. */\n readonly definition: ConditionIR;\n /** Callsite of the segment() call (provenance; lands in SegmentIR.meta.loc). */\n readonly loc: SourceLocIR | undefined;\n}\n\n/** Labels for a segment: what the studio shows instead of the wire key. */\nexport interface SegmentMeta {\n name?: string;\n description?: string;\n}\n\nexport interface SegmentDefinition extends SegmentMeta {\n /**\n * Wire identity — by-name references and the membership store are keyed on\n * it, so it is not something to rename for readability.\n */\n id: string;\n /** Who is in the segment; the predicates already checked its types. */\n condition: Condition;\n}\n\n/**\n * Segment definition. `name` and `description` are optional labels: metadata,\n * dropped before hashing, and what the studio shows.\n *\n * export const purchaser = segment({\n * id: 'purchaser',\n * name: 'Purchased (last 30d)',\n * condition: performed(e.purchase, { within: '30 days' }),\n * });\n */\nexport function segment({ id, condition, name, description }: SegmentDefinition): SegmentRef {\n const meta: SegmentMeta = {\n ...(name === undefined ? {} : { name }),\n ...(description === undefined ? {} : { description }),\n };\n const impl: SegmentInternal = {\n __condition: true,\n __segment: true,\n id,\n ir: { type: 'segment', segment: id },\n definition: condIR(condition),\n loc: captureLoc(segment),\n meta: Object.keys(meta).length === 0 ? undefined : meta,\n };\n return impl;\n}\n"],"mappings":";;;;AAqCA,MAAM,QAAQ,IAAiB,QAAiC;CAK9D,OAAO;EAHL,aAAa;EACb,IAAI,QAAQ,KAAA,IAAY,KAAK;GAAE,GAAG;GAAI,MAAM,EAAE,IAAI;EAAE;CAE5C;AACZ;;AAGA,MAAa,UAAU,MAA8B;CAEnD,MAAM,KAAM,EAAiC;CAC7C,IAAI,OAAO,KAAA,GAGT,MAAM,IAAI,MACR,6GACF;CAEF,OAAO;AACT;;;;;;;AAiBA,MAAM,iBAAiB,QACpB,IAAqC;AAExC,SAAS,KACP,KACA,IAeA,OACA,QACA,KACW;CACX,MAAM,cAAc,cAAc,GAAG;CACrC,OAAO,KACL;EACE,MAAM,gBAAgB,KAAA,IAAY,YAAY;EAC9C,MAAM,eAAgB,IAAiC;EACvD;EACA,GAAI,UAAU,KAAA,IAAY,EAAE,MAAM,IAAI,CAAC;EACvC,GAAI,WAAW,KAAA,IAAY,EAAE,QAAQ,CAAC,GAAG,MAAM,EAAE,IAAI,CAAC;CACxD,GACA,GACF;AACF;AAEA,SAAgB,GAAM,KAAiB,OAA8B;CACnE,OAAO,KAAK,KAAK,MAAM,OAAiB,KAAA,GAAW,WAAW,EAAE,CAAC;AACnE;AACA,SAAgB,GAAM,KAAiB,OAA8B;CACnE,OAAO,KAAK,KAAK,MAAM,OAAiB,KAAA,GAAW,WAAW,EAAE,CAAC;AACnE;AACA,SAAgB,GAA8B,KAAiB,OAA8B;CAC3F,OAAO,KAAK,KAAK,MAAM,OAAO,KAAA,GAAW,WAAW,EAAE,CAAC;AACzD;AACA,SAAgB,IAA+B,KAAiB,OAA8B;CAC5F,OAAO,KAAK,KAAK,OAAO,OAAO,KAAA,GAAW,WAAW,GAAG,CAAC;AAC3D;AACA,SAAgB,GAA8B,KAA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","names":[],"sources":["../../src/dsl/condition.ts"],"sourcesContent":["import type { ConditionIR, DurationIR, SourceLocIR } from '../ir';\nimport { captureLoc } from '../provenance';\nimport { type Duration, durationIR } from './base';\nimport {\n type EventRef,\n PAYLOAD_PATH,\n type PayloadRef,\n type PayloadRefs,\n type UserPropertyRef,\n payloadRefs,\n} from './refs';\nimport type { Channel } from './template';\n\n/**\n * Conditions — drizzle-style predicate expressions: free functions (eq/gt/…)\n * composed with and/or/not, plus `segment` for naming an expression as a\n * top-level asset. A condition is an opaque handle wrapping its ConditionIR.\n *\n * Type techniques:\n * - Types flow in from the reference's phantom type; operator applicability is\n * a signature constraint (gt only takes string|number refs, contains only\n * string ones), mirroring customer.io's condition panel.\n * - Value parameters are always NoInfer: types come from the reference only,\n * which stops eq(ref, 'typo') from widening T to include the bad value.\n *\n * TODO: JSON array 'where at least one'、JSON object 'has the property'。\n */\n\n/** Opaque condition handle — what predicates, combinators and segments all produce. */\nexport interface Condition {\n readonly __condition: true;\n}\n\ninterface ConditionInternal extends Condition {\n readonly ir: ConditionIR;\n}\n\nconst cond = (ir: ConditionIR, loc?: SourceLocIR): Condition => {\n const impl: ConditionInternal = {\n __condition: true,\n ir: loc === undefined ? ir : { ...ir, meta: { loc } },\n };\n return impl;\n};\n\n/** @internal unwrap a condition to its IR — used by flow/trigger/workflow builders */\nexport const condIR = (c: Condition): ConditionIR => {\n // Partial: the cast is unsound for hand-rolled objects — exactly what this checks\n const ir = (c as Partial<ConditionInternal>).ir;\n if (ir === undefined) {\n // A hand-rolled `{ __condition: true }` would otherwise surface as a\n // baffling zod error at toIR() time, far away from the actual mistake.\n throw new Error(\n 'Condition was not created by this DSL — use the predicates (eq/gt/…), combinators (and/or/not) or segment()'\n );\n }\n return ir;\n};\n\ntype Scalar = string | number | boolean;\n\n/**\n * Predicates accept either kind of reference: a user property (profile\n * condition) or an event payload field (only valid inside a `where` — the\n * bundle compiler enforces the placement, since both produce `Condition`).\n */\ntype CondRef<T> = UserPropertyRef<T> | PayloadRef<T>;\n\n/**\n * A payload ref identifies itself by a symbol key, and a user-property ref by\n * the absence of one. Nothing here reads a *string* key off the reference: a\n * payload ref hands out sub-refs for every string key, so a field named `type`\n * or `path` would otherwise answer in place of the ref itself.\n */\nconst payloadPathOf = (ref: CondRef<unknown>): string | undefined =>\n (ref as Partial<PayloadRef<unknown>>)[PAYLOAD_PATH];\n\nfunction prop(\n ref: CondRef<unknown>,\n op:\n | 'eq'\n | 'ne'\n | 'gt'\n | 'gte'\n | 'lt'\n | 'lte'\n | 'between'\n | 'not_between'\n | 'in_array'\n | 'not_in_array'\n | 'exists'\n | 'not_exists'\n | 'contains'\n | 'not_contains',\n value?: Scalar,\n values?: readonly Scalar[],\n loc?: SourceLocIR\n): Condition {\n const payloadPath = payloadPathOf(ref);\n return cond(\n {\n type: payloadPath !== undefined ? 'payload' : 'property',\n path: payloadPath ?? (ref as UserPropertyRef<unknown>).path,\n op,\n ...(value !== undefined ? { value } : {}),\n ...(values !== undefined ? { values: [...values] } : {}),\n },\n loc\n );\n}\n\nexport function eq<T>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'eq', value as Scalar, undefined, captureLoc(eq));\n}\nexport function ne<T>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'ne', value as Scalar, undefined, captureLoc(ne));\n}\nexport function gt<T extends string | number>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'gt', value, undefined, captureLoc(gt));\n}\nexport function gte<T extends string | number>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'gte', value, undefined, captureLoc(gte));\n}\nexport function lt<T extends string | number>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'lt', value, undefined, captureLoc(lt));\n}\nexport function lte<T extends string | number>(ref: CondRef<T>, value: NoInfer<T>): Condition {\n return prop(ref, 'lte', value, undefined, captureLoc(lte));\n}\nexport function between<T extends string | number>(\n ref: CondRef<T>,\n min: NoInfer<T>,\n max: NoInfer<T>\n): Condition {\n return prop(ref, 'between', undefined, [min, max], captureLoc(between));\n}\nexport function notBetween<T extends string | number>(\n ref: CondRef<T>,\n min: NoInfer<T>,\n max: NoInfer<T>\n): Condition {\n return prop(ref, 'not_between', undefined, [min, max], captureLoc(notBetween));\n}\nexport function inArray<T>(ref: CondRef<T>, values: readonly NoInfer<T>[]): Condition {\n return prop(ref, 'in_array', undefined, values as readonly Scalar[], captureLoc(inArray));\n}\nexport function notInArray<T>(ref: CondRef<T>, values: readonly NoInfer<T>[]): Condition {\n return prop(ref, 'not_in_array', undefined, values as readonly Scalar[], captureLoc(notInArray));\n}\nexport function exists(ref: CondRef<unknown>): Condition {\n return prop(ref, 'exists', undefined, undefined, captureLoc(exists));\n}\nexport function notExists(ref: CondRef<unknown>): Condition {\n return prop(ref, 'not_exists', undefined, undefined, captureLoc(notExists));\n}\nexport function contains<T extends string>(ref: CondRef<T>, value: string): Condition {\n return prop(ref, 'contains', value, undefined, captureLoc(contains));\n}\nexport function notContains<T extends string>(ref: CondRef<T>, value: string): Condition {\n return prop(ref, 'not_contains', value, undefined, captureLoc(notContains));\n}\n\nexport interface PerformedOptions {\n /** Only occurrences this recent count; must be a positive duration. */\n within?: Duration;\n /** At least this many occurrences; a positive integer (1 is the default). */\n count?: number;\n}\n\n/**\n * @internal A duration that has to elapse — a wait's timeout, a goal's window, a performed\n * window. Zero parses as a valid duration but means \"never\" or \"always\" depending on the node,\n * and either way it is not what the author meant.\n */\nexport function positiveDurationIR(value: Duration, what: string): DurationIR {\n const ir = durationIR(value);\n if (ir.ms <= 0) throw new Error(`${what} must be positive, got '${value}'`);\n return ir;\n}\n\n/** A payload where clause: an arrow taking the typed payload-ref table. Runs once at construction — the result is a serializable condition tree in IR, never a closure. */\nexport type PayloadWhere<P> = (p: PayloadRefs<P>) => Condition;\n\n/**\n * Event predicate: performed an event (optionally within a window / at least N\n * times). \"Did not perform\" is `not(performed(...))` — expressed by the\n * combinator, so there is no separate notPerformed.\n *\n * The optional second argument narrows which events count by their payload —\n * an arrow receiving a typed payload reference table, with the ordinary\n * predicates applying. It compiles to a `where` subtree in IR (data the UI\n * renders), not a runtime closure:\n *\n * performed(e.login)\n * performed(e.login, (p) => and(eq(p.platform, 'web'), eq(p.tags.utm_source, 'meta')))\n * performed(e.purchase, (p) => gt(p.value, 100), { within: '30 days', count: 2 })\n * performed(e.purchase, { within: '30 days' }) // options without a where\n *\n * Time anchoring: evaluated inside a `goal` the count starts at workflow\n * entry, inside `waitUntil` at the moment the wait began (the engine anchors\n * them — a conversion or a wake must not be satisfied by pre-existing\n * history). Everywhere else (branch/filter/exitWhen/segments) it looks over\n * full history, bounded only by `within`.\n */\nexport function performed<P>(event: EventRef<P>, opts?: PerformedOptions): Condition;\nexport function performed<P>(\n event: EventRef<P>,\n where: PayloadWhere<P>,\n opts?: PerformedOptions\n): Condition;\nexport function performed<P>(\n event: EventRef<P>,\n whereOrOpts?: PayloadWhere<P> | PerformedOptions,\n maybeOpts?: PerformedOptions\n): Condition {\n const where = typeof whereOrOpts === 'function' ? whereOrOpts : undefined;\n const opts = typeof whereOrOpts === 'function' ? maybeOpts : whereOrOpts;\n // count: 0 is satisfied by nobody having done anything, and a fraction is never reached\n if (opts?.count !== undefined && (!Number.isInteger(opts.count) || opts.count < 1)) {\n throw new Error(`performed(): count must be a positive integer, got ${String(opts.count)}`);\n }\n return cond(\n {\n type: 'performed',\n event: event.name,\n ...(where !== undefined ? { where: condIR(where(payloadRefs<P>())) } : {}),\n ...(opts?.within !== undefined\n ? { within: positiveDurationIR(opts.within, 'performed(): within') }\n : {}),\n ...(opts?.count !== undefined ? { count: opts.count } : {}),\n },\n captureLoc(performed)\n );\n}\n\n/**\n * The user can be reached on a channel right now. For push it asks the host's\n * device directory (at least one device listed) — the engine keeps no device\n * state, so this is the way to branch on \"has the app on a device that allowed\n * notifications\"; for the other channels it checks the recipient property\n * (`email`, `phone`, …). Inside `waitUntil` it wakes on device changes\n * (`POST /devices/changed`) or profile updates respectively.\n *\n * .branch([reachable('push'), (w) => w.push(tip)], (w) => w.email(tip))\n *\n * (`.prefer([push.tip, email.tip], props)` is this branch for one push and one email.)\n */\nexport function reachable(channel: Channel): Condition {\n return cond({ type: 'reachable', channel }, captureLoc(reachable));\n}\n\n/** Condition combinators: nest freely. */\nexport function and(...conditions: readonly Condition[]): Condition {\n return cond({ type: 'and', conditions: conditions.map(condIR) }, captureLoc(and));\n}\nexport function or(...conditions: readonly Condition[]): Condition {\n return cond({ type: 'or', conditions: conditions.map(condIR) }, captureLoc(or));\n}\nexport function not(condition: Condition): Condition {\n return cond({ type: 'not', condition: condIR(condition) }, captureLoc(not));\n}\n\n/**\n * Segment: a named condition expression and a top-level asset — it shows up in\n * the UI sidebar, is reusable across workflows, is referenced by id in IR,\n * and has a continuously materialized membership count (the prerequisite for\n * segment triggers). Anonymous reuse is just a const expression; a one-off\n * check is an inline expression at the use site.\n * TODO, to match customer.io's panel: form / page / device / screen /\n * opt-out / message data(email opened、sms clicked、webhook …)\n */\nexport interface SegmentRef extends Condition {\n readonly __segment: true;\n /** Wire identity: segment references and the membership store are keyed on it (`SegmentIR.id`). */\n readonly id: string;\n}\n\n/** @internal the compiled shape behind a SegmentRef — compileBundle reads definition/loc off it */\nexport interface SegmentInternal extends SegmentRef {\n readonly ir: ConditionIR;\n /** Human label / description; metadata, so never part of the hash. */\n readonly meta: SegmentMeta | undefined;\n /** The segment's own definition (SegmentIR.condition), as opposed to a reference by id. */\n readonly definition: ConditionIR;\n /** Callsite of the segment() call (provenance; lands in SegmentIR.meta.loc). */\n readonly loc: SourceLocIR | undefined;\n}\n\n/** Labels for a segment: what the studio shows instead of the wire key. */\nexport interface SegmentMeta {\n name?: string;\n description?: string;\n}\n\nexport interface SegmentDefinition extends SegmentMeta {\n /**\n * Wire identity — by-name references and the membership store are keyed on\n * it, so it is not something to rename for readability.\n */\n id: string;\n /** Who is in the segment; the predicates already checked its types. */\n condition: Condition;\n}\n\n/**\n * Segment definition. `name` and `description` are optional labels: metadata,\n * dropped before hashing, and what the studio shows.\n *\n * export const purchaser = segment({\n * id: 'purchaser',\n * name: 'Purchased (last 30d)',\n * condition: performed(e.purchase, { within: '30 days' }),\n * });\n */\nexport function segment({ id, condition, name, description }: SegmentDefinition): SegmentRef {\n const meta: SegmentMeta = {\n ...(name === undefined ? {} : { name }),\n ...(description === undefined ? {} : { description }),\n };\n const impl: SegmentInternal = {\n __condition: true,\n __segment: true,\n id,\n ir: { type: 'segment', segment: id },\n definition: condIR(condition),\n loc: captureLoc(segment),\n meta: Object.keys(meta).length === 0 ? undefined : meta,\n };\n return impl;\n}\n"],"mappings":";;;;AAqCA,MAAM,QAAQ,IAAiB,QAAiC;CAK9D,OAAO;EAHL,aAAa;EACb,IAAI,QAAQ,KAAA,IAAY,KAAK;GAAE,GAAG;GAAI,MAAM,EAAE,IAAI;EAAE;CAE5C;AACZ;;AAGA,MAAa,UAAU,MAA8B;CAEnD,MAAM,KAAM,EAAiC;CAC7C,IAAI,OAAO,KAAA,GAGT,MAAM,IAAI,MACR,6GACF;CAEF,OAAO;AACT;;;;;;;AAiBA,MAAM,iBAAiB,QACpB,IAAqC;AAExC,SAAS,KACP,KACA,IAeA,OACA,QACA,KACW;CACX,MAAM,cAAc,cAAc,GAAG;CACrC,OAAO,KACL;EACE,MAAM,gBAAgB,KAAA,IAAY,YAAY;EAC9C,MAAM,eAAgB,IAAiC;EACvD;EACA,GAAI,UAAU,KAAA,IAAY,EAAE,MAAM,IAAI,CAAC;EACvC,GAAI,WAAW,KAAA,IAAY,EAAE,QAAQ,CAAC,GAAG,MAAM,EAAE,IAAI,CAAC;CACxD,GACA,GACF;AACF;AAEA,SAAgB,GAAM,KAAiB,OAA8B;CACnE,OAAO,KAAK,KAAK,MAAM,OAAiB,KAAA,GAAW,WAAW,EAAE,CAAC;AACnE;AACA,SAAgB,GAAM,KAAiB,OAA8B;CACnE,OAAO,KAAK,KAAK,MAAM,OAAiB,KAAA,GAAW,WAAW,EA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AW,EAAE,CAAC;AAChF;AACA,SAAgB,IAAI,WAAiC;CACnD,OAAO,KAAK;EAAE,MAAM;EAAO,WAAW,OAAO,SAAS;CAAE,GAAG,WAAW,GAAG,CAAC;AAC5E;;;;;;;;;;;AAsDA,SAAgB,QAAQ,EAAE,IAAI,WAAW,MAAM,eAA8C;CAC3F,MAAM,OAAoB;EACxB,GAAI,SAAS,KAAA,IAAY,CAAC,IAAI,EAAE,KAAK;EACrC,GAAI,gBAAgB,KAAA,IAAY,CAAC,IAAI,EAAE,YAAY;CACrD;CAUA,OAAO;EARL,aAAa;EACb,WAAW;EACX;EACA,IAAI;GAAE,MAAM;GAAW,SAAS;EAAG;EACnC,YAAY,OAAO,SAAS;EAC5B,KAAK,WAAW,OAAO;EACvB,MAAM,OAAO,KAAK,IAAI,CAAC,CAAC,WAAW,IAAI,KAAA,IAAY;CAE3C;AACZ"}
|
package/dist/dsl/flow.cjs
CHANGED
|
@@ -23,6 +23,14 @@ function templateUses(builder) {
|
|
|
23
23
|
return builder instanceof FlowBuilderImpl ? builder.uses : [];
|
|
24
24
|
}
|
|
25
25
|
/**
|
|
26
|
+
* @internal The action definitions a workflow runs, sub-flows and fragments included. The IR
|
|
27
|
+
* names an action only; compileBundle checks that each ref is the very object listed in
|
|
28
|
+
* `actions`, which is what keeps two definitions from sharing one name. Never part of the IR.
|
|
29
|
+
*/
|
|
30
|
+
function actionUses(builder) {
|
|
31
|
+
return builder instanceof FlowBuilderImpl ? builder.actions : [];
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
26
34
|
* A cohort arm name has two jobs, and both constrain its spelling:
|
|
27
35
|
* - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),
|
|
28
36
|
* and an id is a durable step name — a dot would fake a nesting level and can
|
|
@@ -34,15 +42,17 @@ function templateUses(builder) {
|
|
|
34
42
|
* experiment would prepend itself and re-bucket everyone already in it.
|
|
35
43
|
*/
|
|
36
44
|
const ARM_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
37
|
-
/** A sub-flow's nodes; the template definitions it sends are added to `uses`. */
|
|
38
|
-
function resolveSubFlow(sub, uses) {
|
|
45
|
+
/** A sub-flow's nodes; the template definitions it sends and the actions it runs are added to `uses` / `actions`. */
|
|
46
|
+
function resolveSubFlow(sub, uses, actions) {
|
|
39
47
|
if (typeof sub === "function") {
|
|
40
48
|
const builder = new FlowBuilderImpl();
|
|
41
49
|
if (typeof sub(builder)?.then === "function") throw new TypeError("sub-flow callbacks must be synchronous: they run once, while the workflow is defined");
|
|
42
50
|
uses.push(...builder.uses);
|
|
51
|
+
actions.push(...builder.actions);
|
|
43
52
|
return builder.nodes;
|
|
44
53
|
}
|
|
45
54
|
uses.push(...sub.uses);
|
|
55
|
+
actions.push(...sub.actions);
|
|
46
56
|
return structuredClone(sub.nodes);
|
|
47
57
|
}
|
|
48
58
|
const DEFINED_CHANNELS = new Set(Object.values(require_templates.CHANNEL_OF));
|
|
@@ -67,6 +77,8 @@ var FlowBuilderImpl = class {
|
|
|
67
77
|
nodes = [];
|
|
68
78
|
/** The template definitions sent, with where: compile-time only, never in the IR. */
|
|
69
79
|
uses = [];
|
|
80
|
+
/** The action definitions run: compile-time identity only, never in the IR. */
|
|
81
|
+
actions = [];
|
|
70
82
|
/** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */
|
|
71
83
|
pushNode(node, loc) {
|
|
72
84
|
this.nodes.push({
|
|
@@ -157,6 +169,14 @@ var FlowBuilderImpl = class {
|
|
|
157
169
|
}
|
|
158
170
|
timeWindow(opts) {
|
|
159
171
|
const loc = require_provenance.captureLoc(this.timeWindow);
|
|
172
|
+
if (opts.days !== void 0) {
|
|
173
|
+
if (opts.days.length === 0) throw new Error("timeWindow(): 'days' must name at least one day");
|
|
174
|
+
const seen = /* @__PURE__ */ new Set();
|
|
175
|
+
for (const day of opts.days) {
|
|
176
|
+
if (seen.has(day)) throw new Error(`timeWindow(): 'days' lists '${day}' twice`);
|
|
177
|
+
seen.add(day);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
160
180
|
const start = require_dsl_base.timeOfDayMinutes(opts.between[0]);
|
|
161
181
|
if (require_dsl_base.timeOfDayMinutes(opts.between[1]) <= start) throw new Error(`timeWindow(): 'between' must open before it closes within one day, got [${opts.between[0]}, ${opts.between[1]}] (overnight windows are not supported yet)`);
|
|
162
182
|
return this.pushNode({
|
|
@@ -182,12 +202,12 @@ var FlowBuilderImpl = class {
|
|
|
182
202
|
id: "",
|
|
183
203
|
type: "wait_until",
|
|
184
204
|
condition: require_dsl_condition.condIR(condition),
|
|
185
|
-
timeout:
|
|
186
|
-
onTimeout: onTimeout === "continue" || onTimeout === "exit" ? onTimeout : resolveSubFlow(onTimeout, this.uses)
|
|
205
|
+
timeout: require_dsl_condition.positiveDurationIR(opts.timeout, "waitUntil(): timeout"),
|
|
206
|
+
onTimeout: onTimeout === "continue" || onTimeout === "exit" ? onTimeout : resolveSubFlow(onTimeout, this.uses, this.actions)
|
|
187
207
|
}, loc);
|
|
188
208
|
}
|
|
189
209
|
use(fragment) {
|
|
190
|
-
this.nodes.push(...resolveSubFlow(fragment, this.uses));
|
|
210
|
+
this.nodes.push(...resolveSubFlow(fragment, this.uses, this.actions));
|
|
191
211
|
return this;
|
|
192
212
|
}
|
|
193
213
|
branch(...args) {
|
|
@@ -202,12 +222,12 @@ var FlowBuilderImpl = class {
|
|
|
202
222
|
const [condition, sub] = arm;
|
|
203
223
|
cases.push({
|
|
204
224
|
condition: require_dsl_condition.condIR(condition),
|
|
205
|
-
flow: resolveSubFlow(sub, this.uses)
|
|
225
|
+
flow: resolveSubFlow(sub, this.uses, this.actions)
|
|
206
226
|
});
|
|
207
227
|
} else {
|
|
208
228
|
if (otherwise !== void 0) throw new Error("branch(): only one default arm (bare sub-flow) is allowed");
|
|
209
229
|
if (i !== arms.length - 1) throw new Error("branch(): default arm (bare sub-flow) must be the last argument");
|
|
210
|
-
otherwise = resolveSubFlow(arm, this.uses);
|
|
230
|
+
otherwise = resolveSubFlow(arm, this.uses, this.actions);
|
|
211
231
|
}
|
|
212
232
|
});
|
|
213
233
|
return this.pushNode({
|
|
@@ -244,7 +264,7 @@ var FlowBuilderImpl = class {
|
|
|
244
264
|
arms: entries.map(([name, a]) => ({
|
|
245
265
|
name,
|
|
246
266
|
weight: a.weight,
|
|
247
|
-
flow: a.flow ? resolveSubFlow(a.flow, this.uses) : []
|
|
267
|
+
flow: a.flow ? resolveSubFlow(a.flow, this.uses, this.actions) : []
|
|
248
268
|
}))
|
|
249
269
|
}, loc);
|
|
250
270
|
}
|
|
@@ -270,12 +290,12 @@ var FlowBuilderImpl = class {
|
|
|
270
290
|
}, require_provenance.captureLoc(this.sendEvent));
|
|
271
291
|
}
|
|
272
292
|
run(a, ...args) {
|
|
293
|
+
this.actions.push(a);
|
|
273
294
|
return this.pushNode({
|
|
274
295
|
id: "",
|
|
275
296
|
type: "action",
|
|
276
297
|
action: a.name,
|
|
277
|
-
args: args[0] ?? {}
|
|
278
|
-
codeHash: a.codeHash
|
|
298
|
+
args: args[0] ?? {}
|
|
279
299
|
}, require_provenance.captureLoc(this.run));
|
|
280
300
|
}
|
|
281
301
|
};
|
|
@@ -289,11 +309,13 @@ function flow(build) {
|
|
|
289
309
|
return {
|
|
290
310
|
__flow: true,
|
|
291
311
|
nodes: builder.nodes,
|
|
292
|
-
uses: builder.uses
|
|
312
|
+
uses: builder.uses,
|
|
313
|
+
actions: builder.actions
|
|
293
314
|
};
|
|
294
315
|
}
|
|
295
316
|
//#endregion
|
|
296
317
|
exports.FlowBuilderImpl = FlowBuilderImpl;
|
|
318
|
+
exports.actionUses = actionUses;
|
|
297
319
|
exports.flow = flow;
|
|
298
320
|
exports.templateUses = templateUses;
|
|
299
321
|
|
package/dist/dsl/flow.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.cjs","names":["isTemplate","CHANNEL_OF","captureLoc","durationIR","timeOfDayMinutes","condIR"],"sources":["../../src/dsl/flow.ts"],"sourcesContent":["import type { ChannelIR, ConditionIR, NodeIR, PropValueIR, SourceLocIR } from '../ir';\nimport { captureLoc } from '../provenance';\nimport {\n type AnyTemplate,\n CHANNEL_OF,\n type DiscordTemplate,\n type EmailTemplate,\n type PropsSchema,\n type PushTemplate,\n type SlackTemplate,\n isTemplate,\n} from '../templates';\nimport type { ActionRef } from './action';\nimport { type Duration, type TimeOfDay, type Weekday, durationIR, timeOfDayMinutes } from './base';\nimport { type Condition, condIR } from './condition';\nimport type { EventRef, MessageArgs, PropInput, PropsInput } from './refs';\nimport type { PropsOf, TemplateRef } from './template';\n\n/**\n * The flow chain — FlowBuilder is the DSL's step surface (messages, delays,\n * flow control, data), and its implementation is the compiler front half: each\n * chained call executes no logic, it just collects one IR node (ids are\n * assigned later, in workflow.toIR()). Sub-flow callbacks run exactly once at\n * construction — builder in, builder out — so the output is always a static\n * tree.\n *\n * Every public method also captures its callsite (provenance): the loc lands\n * in the node's hash-excluded meta and is the anchor for future in-place\n * editing from the studio.\n */\n\ntype Scalar = string | number | boolean;\n\n/** An emitted field: a scalar (or a profile ref to one); a nested field cannot be sent. */\ntype EmitValue<T> = [NonNullable<T>] extends [Scalar] ? PropInput<T> : never;\n\n/** The payload `sendEvent` accepts for an event: its fields, scalar ones only. */\nexport type EmitPayload<P> = { [K in keyof P]: EmitValue<P[K]> };\n\n/** Payload may be omitted when the event declares no required field. */\nexport type EmitArgs<P> =\n Record<string, never> extends P ? [payload?: EmitPayload<P>] : [payload: EmitPayload<P>];\n\n/** Per-node push options. */\nexport interface PushOptions {\n /** Which devices get a copy: 'all' (the default) or only the most recently registered. */\n devices?: 'all' | 'latest';\n}\n\n/** `prefer()` options. */\nexport interface PreferOptions {\n /** The generated branch's name in IR (UI title / observability handle), as `branch(label, …)`. */\n label?: string;\n}\n\n/** The candidates `prefer()` takes: one push and one email template, in priority order. */\ntype PreferPair = readonly [PushTemplate, EmailTemplate] | readonly [EmailTemplate, PushTemplate];\n\ntype NormalizeProps<P> = { -readonly [K in keyof P]: P[K] };\ntype Equal<A, B> =\n (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;\n\n/** Both candidates render the one props object, so they must declare the same props type — not merely overlap. */\ntype SameProps<T extends PreferPair> =\n Equal<NormalizeProps<PropsOf<T[0]>>, NormalizeProps<PropsOf<T[1]>>> extends true\n ? unknown\n : { readonly __prefer_error__: 'Both templates must declare the same props type' };\n\n/** Distributes, so a field only one member of a union variable has still counts as extra. */\ntype KeysOfUnion<A> = A extends unknown ? keyof A : never;\n/** Rejects known extra fields, which `{}` (an empty props schema) would otherwise accept. */\ntype NoExtra<A, P> = Record<Exclude<KeysOfUnion<A>, keyof P>, never>;\n\n/** prefer() is typed strictly, but a JS caller (or an `any`) reaches it unchecked — fail at the call, not at send time. */\nfunction checkPreferArgs(candidates: unknown, props: unknown, options: unknown): void {\n if (!Array.isArray(candidates) || candidates.length !== 2) {\n throw new TypeError('prefer(): candidates must be exactly two templates — one push, one email');\n }\n const channels = (candidates as unknown[]).map((candidate) =>\n isTemplate(candidate) ? CHANNEL_OF[candidate.kind] : undefined\n );\n if (!channels.every((channel) => channel === 'push' || channel === 'email')) {\n throw new TypeError('prefer(): each candidate must be a pushTemplate or an emailTemplate');\n }\n if (channels[0] === channels[1]) {\n throw new TypeError('prefer(): candidates must be one push and one email template');\n }\n if (typeof props !== 'object' || props === null || Array.isArray(props)) {\n throw new TypeError(\n 'prefer(): props must be an object — pass {} when the templates declare none'\n );\n }\n if (options === undefined) return;\n if (typeof options !== 'object' || options === null || Array.isArray(options)) {\n throw new TypeError('prefer(): options must be an object');\n }\n for (const [name, value] of Object.entries(options)) {\n if (name !== 'label') {\n throw new TypeError(\n `prefer(): unknown option '${name}' — props go in the second argument, options take only 'label'`\n );\n }\n if (typeof value !== 'string') throw new TypeError(\"prefer(): 'label' must be a string\");\n }\n}\n\n/** A reusable flow fragment (what `flow(...)` returns), referenced directly by branch arms. */\nexport interface Flow {\n readonly __flow: true;\n}\n\ninterface FlowInternal extends Flow {\n readonly nodes: NodeIR[];\n readonly uses: readonly TemplateUse[];\n}\n\n/**\n * @internal A template definition a flow sends, kept beside the IR (which names it by id only):\n * compileConfig checks that the registered definition under that id is this very object, so the\n * schema that typed the call is the one that renders it. Never part of the IR or its hash.\n */\nexport interface TemplateUse {\n readonly template: AnyTemplate;\n readonly loc: SourceLocIR | undefined;\n}\n\n/** @internal The template definitions a workflow sends, sub-flows and fragments included. */\nexport function templateUses(builder: FlowBuilder): readonly TemplateUse[] {\n return builder instanceof FlowBuilderImpl ? builder.uses : [];\n}\n\n/** Sub-flow: a named fragment, or an inline callback (runs once at construction — builder in, builder out). */\nexport type SubFlow = Flow | ((w: FlowBuilder) => FlowBuilder);\n\n/** A branch arm: the [condition, sub-flow] tuple — an [if, then] ordering convention. */\nexport type BranchCase = readonly [condition: Condition, flow: SubFlow];\n\n/**\n * A branch argument: either a tuple arm, or a bare sub-flow meaning the default\n * arm. The bare form may appear once, and must come last (checked at runtime).\n */\nexport type BranchArm = BranchCase | SubFlow;\n\n/**\n * A cohort arm name has two jobs, and both constrain its spelling:\n * - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),\n * and an id is a durable step name — a dot would fake a nesting level and can\n * collide with a real one, an empty name gives '{id}..{j}';\n * - it is an object key, and JavaScript lists integer-like keys first in\n * ascending numeric order however the author wrote them. The arms array is\n * documented (and interpreted) as authoring order, and the bucketing walk\n * accumulates weights along it, so an arm named '0' added to a live\n * experiment would prepend itself and re-bucket everyone already in it.\n */\nconst ARM_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;\n\n/** A sub-flow's nodes; the template definitions it sends are added to `uses`. */\nfunction resolveSubFlow(sub: SubFlow, uses: TemplateUse[]): NodeIR[] {\n if (typeof sub === 'function') {\n const builder = new FlowBuilderImpl();\n const returned: unknown = sub(builder);\n // An async callback would add its nodes after construction is over — after ids were assigned\n if (typeof (returned as { then?: unknown } | undefined)?.then === 'function') {\n throw new TypeError(\n 'sub-flow callbacks must be synchronous: they run once, while the workflow is defined'\n );\n }\n uses.push(...builder.uses);\n return builder.nodes;\n }\n uses.push(...(sub as FlowInternal).uses);\n /*\n * A named fragment is a value, and the convention is to reuse it — two branch\n * arms may hold the same one. Handing out its own nodes aliases them into\n * both places, and assignIds writes ids *in place*: the second prefix\n * overwrites the first, so the two placements end up as one object under one\n * id — one durable step name, one message idempotency key, one bucket seed.\n * A copy per placement is what makes a fragment behave like a value.\n */\n return structuredClone((sub as FlowInternal).nodes);\n}\n\nexport interface FlowBuilder {\n /* ---- Messages: every channel is one message node; separate methods buy channel-level typing ---- */\n email<T extends EmailTemplate>(template: T, ...props: MessageArgs<PropsOf<T>>): this;\n sms<P extends object>(template: TemplateRef<'sms', P>, ...props: MessageArgs<P>): this;\n /**\n * Push to the user's devices — every device the host's directory lists, or\n * only the most recently registered with `{ devices: 'latest' }`. A user with\n * no device is skipped (`prefer([pushTpl, emailTpl], props)` falls back to email).\n */\n push<T extends PushTemplate>(\n template: T,\n ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]\n ): this;\n inApp<P extends object>(template: TemplateRef<'in_app', P>, ...props: MessageArgs<P>): this;\n slack<T extends SlackTemplate<PropsSchema, never>>(\n template: T,\n ...props: MessageArgs<PropsOf<T>>\n ): this;\n discord<T extends DiscordTemplate<PropsSchema, never>>(\n template: T,\n ...props: MessageArgs<PropsOf<T>>\n ): this;\n survey<P extends object>(template: TemplateRef<'survey', P>, ...props: MessageArgs<P>): this;\n\n /**\n * Send one message on the first channel the user can be reached on: one push\n * and one email template, in priority order, rendered with the same props.\n * Sugar for the branch it compiles to — same IR, ids and hash as writing\n *\n * .branch(label, [reachable(first.channel), (b) => b.<first>(first, props)], (b) => b.<second>(second, props))\n *\n * so the choice is made once, when the step is reached, and a first choice\n * that fails to send retries as itself — it never falls through to the\n * second. Props are always passed (`{}` for templates that declare none),\n * and both templates must declare the same props type; for differing props\n * or other channels, write the branch.\n *\n * .prefer([push.tip, email.tip], { name: u.name }, { label: 'tip by channel' })\n */\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>,\n options?: PreferOptions\n ): this;\n\n /* --------------------------------- Delays --------------------------------- */\n /** Time Delay; passing { min, max } makes it a Randomized Delay. */\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n\n /** Time Window: hold until inside the window (e.g. weekdays 09:00–17:00). tz: 'user' uses the user's timezone. */\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this;\n\n /**\n * Wait Until: continue on the main line once the condition holds, or take\n * onTimeout when it expires (default 'continue'). On the engine side this is\n * \"await event racing a timer\" — a native primitive of durable runtimes.\n */\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this;\n\n /**\n * Splice a fragment in place: a named `flow(...)` or a callback, expanded\n * once while the workflow is defined — a composition step before compiling,\n * not a node (the IR has no trace of it, and ids are assigned over the whole\n * workflow as if the steps were written inline). Each use gets its own copy,\n * so one fragment can be used in several places and workflows.\n *\n * const officeHours = flow((w) => w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] }));\n * workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(email.tip, { name: u.name })\n */\n use(fragment: SubFlow): this;\n\n /* ------------------------------ Flow Control ------------------------------ */\n /**\n * Conditional branch: ordered first-match (same semantics as Step Functions\n * Choice / Knock branch). This one primitive covers both the UI's True/False\n * Branch (two arms) and Multi-Split Branch (N arms). Arms are\n * [condition, sub-flow] tuples; a bare sub-flow in tail position is the\n * default arm. With no match and no default, execution simply continues.\n * Rejoin is structural: after the matching arm finishes, execution resumes\n * at the node following the branch — to opt out, call .exit() inside the arm.\n *\n * .branch([activeSubscriber, upgradeFlow], firstTimeFlow) // True/False\n * .branch([vip, vipFlow], [trial, trialFlow], defaultFlow) // Multi-Split\n * .branch([not(usedStaging), eduFlow]) // single arm: no match continues\n *\n * The optional first argument `label` becomes the node's name in IR (UI title\n * / observability handle). It is not a jump target — there is no goto here;\n * looping is a future re-entry-policy topic (see sendEvent). Arm labels in\n * the UI are derived from the condition.\n */\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n\n /**\n * Gate: exit unless the condition holds, otherwise continue. A first-class\n * node rather than sugar over branch — same semantics as Zapier's \"only\n * continue if\" / Iterable's Filter tile, and rendered on its own in the UI.\n * `reason` is the audit-log line — metadata, so rewording it is free\n * (excluded from contentHash, see hash.ts).\n */\n filter(condition: Condition, opts?: { reason?: string }): this;\n\n /**\n * Random Cohort Branch (A/B): weights must sum to 100 (checked at runtime).\n * `key` names the experiment: bucketing hashes `userId:key` instead of the\n * structural node id, so assignments survive node insertion/moves and the\n * experiment keeps one identity across workflow versions — set it for any\n * A/B whose results you intend to read.\n *\n * Arm names become node id segments and are read back in authoring order, so\n * they are restricted to letters, digits, '_' and '-', never starting with a\n * digit (checked at runtime).\n */\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this;\n\n /**\n * Exit: end the whole workflow immediately (the UI's Exit node); `reason`\n * goes into the audit log and is metadata, so rewording it neither repins\n * in-flight journeys nor shows up in plan. Inside a branch arm this means\n * \"terminate, do not rejoin\" — it stops here instead of falling through,\n * while an arm without exit rejoins naturally.\n */\n exit(reason?: string): this;\n\n /* ---------------------------------- Data ---------------------------------- */\n /**\n * Emit a typed event (customer.io's Send Event). The event comes from an\n * e.xxx reference, so payload types flow in the same way trigger.event works.\n * This is how workflows compose: an event can trigger another workflow, and\n * the resulting call graph is statically analyzable. Payload values may\n * reference u.xxx. Only scalar fields can be sent (IR carries literals and\n * profile refs, not nested JSON): an event whose payload requires a nested\n * field cannot be emitted from a journey, and the types say so.\n *\n * Note on loops: a trailing self-triggering sendEvent will become the\n * official periodic-flow shape *once a re-entry policy exists* — today the\n * entry policy is once-per-user, so a self-trigger cannot re-enter and does\n * not loop.\n * TODO: the rest of the Data category — outbound webhook / profile update /\n * journey attributes.\n */\n sendEvent<P extends object>(event: EventRef<P>, ...payload: EmitArgs<P>): this;\n\n /**\n * Run a custom action (see dsl/action.ts for the model). The chain records\n * identity only — name, args, codeHash — never the code: the implementation\n * ships inside the deployed Worker bundle and is resolved by name from the\n * runtime registry. Args are typed by the ActionRef and may reference u.xxx,\n * resolved at run time exactly like message props. Executed inside a durable\n * step: retried on throw, checkpointed on success.\n */\n run<A extends object>(action: ActionRef<A>, ...args: MessageArgs<A>): this;\n}\n\nconst DEFINED_CHANNELS: ReadonlySet<ChannelIR> = new Set(Object.values(CHANNEL_OF));\n\n/** A message's template: a definition of the channel (named by its id), or a reference by key. */\ntype MessageTemplate = AnyTemplate | TemplateRef;\n\nfunction templateKey(channel: ChannelIR, tpl: MessageTemplate): string {\n if (!DEFINED_CHANNELS.has(channel)) return (tpl as TemplateRef).key;\n // Typed, but a JS caller (or an `any`) reaches it unchecked: fail where the workflow is written\n if (!isTemplate(tpl) || CHANNEL_OF[tpl.kind] !== channel) {\n throw new TypeError(`${channel}(): expects a ${channel} template definition`);\n }\n return tpl.id;\n}\n\nfunction messageNode(\n channel: ChannelIR,\n tpl: MessageTemplate,\n props: object | undefined,\n devices?: 'latest'\n): NodeIR {\n return {\n id: '',\n type: 'message',\n channel,\n template: templateKey(channel, tpl),\n props: (props ?? {}) as Record<string, PropValueIR>,\n // Absent for 'all', so adding the option left every existing push's hash as it was\n ...(devices !== undefined ? { devices } : {}),\n };\n}\n\n/* oxlint-disable typescript/unbound-method --\n * `captureLoc(this.xxx)` passes the method by identity as the stack-trace\n * boundary for Error.captureStackTrace; it is never invoked, so `this`\n * scoping cannot go wrong. */\n/** @internal extended by WorkflowBuilderImpl; not part of the public API */\nexport class FlowBuilderImpl implements FlowBuilder {\n /** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */\n readonly nodes: NodeIR[] = [];\n /** The template definitions sent, with where: compile-time only, never in the IR. */\n readonly uses: TemplateUse[] = [];\n\n /** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */\n private pushNode(node: NodeIR, loc: SourceLocIR | undefined): this {\n this.nodes.push({ ...node, ...(loc !== undefined ? { meta: { loc } } : {}) });\n return this;\n }\n\n private message(\n channel: ChannelIR,\n tpl: MessageTemplate,\n props: object | undefined,\n loc: SourceLocIR | undefined,\n devices?: 'latest'\n ): this {\n this.pushNode(messageNode(channel, tpl, props, devices), loc);\n if (isTemplate(tpl)) this.uses.push({ template: tpl, loc });\n return this;\n }\n\n email<T extends EmailTemplate>(t: T, ...args: MessageArgs<PropsOf<T>>): this {\n return this.message('email', t, args[0], captureLoc(this.email));\n }\n sms<P extends object>(t: TemplateRef<'sms', P>, ...args: MessageArgs<P>): this {\n return this.message('sms', t, args[0], captureLoc(this.sms));\n }\n push<T extends PushTemplate>(\n t: T,\n ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]\n ): this {\n const [props, options] = args as unknown as [object | undefined, PushOptions | undefined];\n const devices = options?.devices === 'latest' ? 'latest' : undefined;\n return this.message('push', t, props, captureLoc(this.push), devices);\n }\n inApp<P extends object>(t: TemplateRef<'in_app', P>, ...args: MessageArgs<P>): this {\n return this.message('in_app', t, args[0], captureLoc(this.inApp));\n }\n slack<T extends SlackTemplate<PropsSchema, never>>(t: T, ...args: MessageArgs<PropsOf<T>>): this {\n return this.message('slack', t, args[0], captureLoc(this.slack));\n }\n discord<T extends DiscordTemplate<PropsSchema, never>>(\n t: T,\n ...args: MessageArgs<PropsOf<T>>\n ): this {\n return this.message('discord', t, args[0], captureLoc(this.discord));\n }\n survey<P extends object>(t: TemplateRef<'survey', P>, ...args: MessageArgs<P>): this {\n return this.message('survey', t, args[0], captureLoc(this.survey));\n }\n\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>,\n options?: PreferOptions\n ): this {\n checkPreferArgs(candidates, props, options);\n // Every generated node points at the author's prefer() call, not at this method's body\n const loc = captureLoc(this.prefer);\n const meta = loc !== undefined ? { meta: { loc } } : {};\n const [first, second] = candidates as readonly (EmailTemplate | PushTemplate)[];\n const channel = (tpl: EmailTemplate | PushTemplate) => CHANNEL_OF[tpl.kind] as 'email' | 'push';\n // Both are sent from here as far as the registry check goes, the fallback included\n this.uses.push({ template: first, loc }, { template: second, loc });\n // A copy per message, as two separately written calls would hold\n const arm = (tpl: EmailTemplate | PushTemplate): NodeIR[] => [\n { ...messageNode(channel(tpl), tpl, { ...props }), ...meta },\n ];\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(options?.label !== undefined ? { label: options.label } : {}),\n cases: [\n { condition: { type: 'reachable', channel: channel(first), ...meta }, flow: arm(first) },\n ],\n otherwise: arm(second),\n },\n loc\n );\n }\n\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n delay(d: Duration | { min: Duration; max: Duration }): this {\n const loc = captureLoc(this.delay);\n if (typeof d === 'string') {\n return this.pushNode({ id: '', type: 'delay', duration: durationIR(d) }, loc);\n }\n const min = durationIR(d.min);\n const max = durationIR(d.max);\n /*\n * The interpreter draws `min + random(max - min)` with the span clamped at\n * zero, so a backwards range does not fail — it quietly collapses into a\n * fixed `min` sleep. Reject it here, where the author can still see it.\n */\n if (max.ms < min.ms) {\n throw new Error(\n `delay(): 'max' must not be shorter than 'min', got { min: '${d.min}', max: '${d.max}' }`\n );\n }\n return this.pushNode({ id: '', type: 'random_delay', min, max }, loc);\n }\n\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this {\n const loc = captureLoc(this.timeWindow);\n const start = timeOfDayMinutes(opts.between[0]);\n const end = timeOfDayMinutes(opts.between[1]);\n if (end <= start) {\n throw new Error(\n `timeWindow(): 'between' must open before it closes within one day, got [${opts.between[0]}, ${opts.between[1]}] (overnight windows are not supported yet)`\n );\n }\n return this.pushNode(\n {\n id: '',\n type: 'time_window',\n days: [...(opts.days ?? (['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const))],\n between: [opts.between[0], opts.between[1]],\n tz: opts.tz ?? 'user',\n },\n loc\n );\n }\n\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this {\n const loc = captureLoc(this.waitUntil);\n const onTimeout = opts.onTimeout ?? 'continue';\n return this.pushNode(\n {\n id: '',\n type: 'wait_until',\n condition: condIR(condition),\n timeout: durationIR(opts.timeout),\n onTimeout:\n onTimeout === 'continue' || onTimeout === 'exit'\n ? onTimeout\n : resolveSubFlow(onTimeout, this.uses),\n },\n loc\n );\n }\n\n use(fragment: SubFlow): this {\n // The fragment's nodes carry their own provenance (where the fragment was written)\n this.nodes.push(...resolveSubFlow(fragment, this.uses));\n return this;\n }\n\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n branch(...args: readonly (string | BranchArm)[]): this {\n const loc = captureLoc(this.branch);\n const label = typeof args[0] === 'string' ? args[0] : undefined;\n const arms = (label === undefined ? args : args.slice(1)) as readonly BranchArm[];\n\n const cases: { condition: ConditionIR; flow: NodeIR[] }[] = [];\n let otherwise: NodeIR[] | undefined;\n arms.forEach((arm, i) => {\n if (Array.isArray(arm)) {\n if (otherwise !== undefined) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n const [condition, sub] = arm as BranchCase;\n cases.push({ condition: condIR(condition), flow: resolveSubFlow(sub, this.uses) });\n } else {\n if (otherwise !== undefined) {\n throw new Error('branch(): only one default arm (bare sub-flow) is allowed');\n }\n if (i !== arms.length - 1) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n otherwise = resolveSubFlow(arm as SubFlow, this.uses);\n }\n });\n\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(label !== undefined ? { label } : {}),\n cases,\n ...(otherwise !== undefined ? { otherwise } : {}),\n },\n loc\n );\n }\n\n filter(condition: Condition, opts?: { reason?: string }): this {\n return this.pushNode(\n {\n id: '',\n type: 'filter',\n condition: condIR(condition),\n ...(opts?.reason !== undefined ? { reason: opts.reason } : {}),\n },\n captureLoc(this.filter)\n );\n }\n\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this {\n const loc = captureLoc(this.cohort);\n const entries = Object.entries(arms);\n /*\n * Weights live on a 0.01% grid: the runtime buckets into 10,000 slots\n * (basis points), so anything finer would be silently quantized — reject\n * it here instead. Converting to integer basis points also makes the\n * sum check exact; no epsilon needed.\n */\n const basisPoints = entries.map(([name, a]) => {\n if (!ARM_NAME.test(name)) {\n throw new Error(\n `cohort(): arm name '${name}' must start with a letter or '_' and contain only letters, digits, '_' or '-' — arm names become node id segments, and integer-like names would silently reorder the arms`\n );\n }\n const bp = a.weight * 100;\n if (Math.abs(bp - Math.round(bp)) > 1e-6) {\n throw new Error(\n `cohort(): arm '${name}' weight ${a.weight} is finer than the 0.01% bucketing grid — use at most two decimal places`\n );\n }\n /*\n * The sum check alone accepts -50 / 150: the runtime walks the arms\n * accumulating basis points and takes the first whose cumulative total\n * clears the bucket, so a negative weight hands 100% of users to its\n * neighbour instead of splitting anything.\n */\n if (bp < 0) {\n throw new Error(`cohort(): arm '${name}' weight ${a.weight} must not be negative`);\n }\n return Math.round(bp);\n });\n const total = basisPoints.reduce((sum, bp) => sum + bp, 0);\n if (total !== 10_000) {\n throw new Error(`cohort(): weights must sum to 100, got ${total / 100}`);\n }\n return this.pushNode(\n {\n id: '',\n type: 'cohort',\n ...(opts?.key !== undefined ? { key: opts.key } : {}),\n arms: entries.map(([name, a]) => ({\n name,\n weight: a.weight,\n flow: a.flow ? resolveSubFlow(a.flow, this.uses) : [],\n })),\n },\n loc\n );\n }\n\n exit(reason?: string): this {\n return this.pushNode(\n { id: '', type: 'exit', ...(reason !== undefined ? { reason } : {}) },\n captureLoc(this.exit)\n );\n }\n\n sendEvent<P extends object>(ev: EventRef<P>, ...payload: EmitArgs<P>): this {\n const values = (payload[0] ?? {}) as Record<string, unknown>;\n for (const [field, value] of Object.entries(values)) {\n const ref =\n typeof value === 'object' &&\n value !== null &&\n (value as { type?: unknown }).type === 'user_property';\n if (!ref && !['string', 'number', 'boolean'].includes(typeof value)) {\n throw new TypeError(\n `sendEvent('${ev.name}'): '${field}' is not a scalar or a u.xxx reference — an emitted payload carries scalar fields only`\n );\n }\n }\n return this.pushNode(\n {\n id: '',\n type: 'send_event',\n event: ev.name,\n payload: values as Record<string, PropValueIR>,\n },\n captureLoc(this.sendEvent)\n );\n }\n\n run<A extends object>(a: ActionRef<A>, ...args: MessageArgs<A>): this {\n return this.pushNode(\n {\n id: '',\n type: 'action',\n action: a.name,\n args: (args[0] ?? {}) as Record<string, PropValueIR>,\n codeHash: a.codeHash,\n },\n captureLoc(this.run)\n );\n }\n}\n/* oxlint-enable typescript/unbound-method */\n\n/**\n * A reusable flow fragment: a free function. Once personalization goes through\n * u.xxx and events through e.xxx, the flow layer carries no schema generics.\n */\nexport function flow(build: (w: FlowBuilder) => FlowBuilder): Flow {\n const builder = new FlowBuilderImpl();\n build(builder);\n const impl: FlowInternal = { __flow: true, nodes: builder.nodes, uses: builder.uses };\n return impl;\n}\n"],"mappings":";;;;;;;AA0EA,SAAS,gBAAgB,YAAqB,OAAgB,SAAwB;CACpF,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,WAAW,WAAW,GACtD,MAAM,IAAI,UAAU,0EAA0E;CAEhG,MAAM,WAAY,WAAyB,KAAK,cAC9CA,kBAAAA,WAAW,SAAS,IAAIC,kBAAAA,WAAW,UAAU,QAAQ,KAAA,CACvD;CACA,IAAI,CAAC,SAAS,OAAO,YAAY,YAAY,UAAU,YAAY,OAA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,GAAG,KAAK,OAAO,MAAM,uFACrC;EAGJ,OAAO,KAAK,SACV;GACE,IAAI;GACJ,MAAM;GACN,OAAO,GAAG;GACV,SAAS;EACX,GACAA,mBAAAA,WAAW,KAAK,SAAS,CAC3B;CACF;CAEA,IAAsB,GAAiB,GAAG,MAA4B;EACpE,OAAO,KAAK,SACV;GACE,IAAI;GACJ,MAAM;GACN,QAAQ,EAAE;GACV,MAAO,KAAK,MAAM,CAAC;GACnB,UAAU,EAAE;EACd,GACAA,mBAAAA,WAAW,KAAK,GAAG,CACrB;CACF;AACF;;;;;AAOA,SAAgB,KAAK,OAA8C;CACjE,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,OAAO;CAEb,OAAO;EADsB,QAAQ;EAAM,OAAO,QAAQ;EAAO,MAAM,QAAQ;CACrE;AACZ"}
|
|
1
|
+
{"version":3,"file":"flow.cjs","names":["isTemplate","CHANNEL_OF","captureLoc","durationIR","timeOfDayMinutes","condIR","positiveDurationIR"],"sources":["../../src/dsl/flow.ts"],"sourcesContent":["import type { ChannelIR, ConditionIR, NodeIR, PropValueIR, SourceLocIR } from '../ir';\nimport { captureLoc } from '../provenance';\nimport {\n type AnyTemplate,\n CHANNEL_OF,\n type DiscordTemplate,\n type EmailTemplate,\n type PropsSchema,\n type PushTemplate,\n type SlackTemplate,\n isTemplate,\n} from '../templates';\nimport type { ActionRef } from './action';\nimport { type Duration, type TimeOfDay, type Weekday, durationIR, timeOfDayMinutes } from './base';\nimport { type Condition, condIR, positiveDurationIR } from './condition';\nimport type { EventRef, MessageArgs, PropInput, PropsInput } from './refs';\nimport type { PropsOf, TemplateRef } from './template';\n\n/**\n * The flow chain — FlowBuilder is the DSL's step surface (messages, delays,\n * flow control, data), and its implementation is the compiler front half: each\n * chained call executes no logic, it just collects one IR node (ids are\n * assigned later, in workflow.toIR()). Sub-flow callbacks run exactly once at\n * construction — builder in, builder out — so the output is always a static\n * tree.\n *\n * Every public method also captures its callsite (provenance): the loc lands\n * in the node's hash-excluded meta and is the anchor for future in-place\n * editing from the studio.\n */\n\ntype Scalar = string | number | boolean;\n\n/** An emitted field: a scalar (or a profile ref to one); a nested field cannot be sent. */\ntype EmitValue<T> = [NonNullable<T>] extends [Scalar] ? PropInput<T> : never;\n\n/** The payload `sendEvent` accepts for an event: its fields, scalar ones only. */\nexport type EmitPayload<P> = { [K in keyof P]: EmitValue<P[K]> };\n\n/** Payload may be omitted when the event declares no required field. */\nexport type EmitArgs<P> =\n Record<string, never> extends P ? [payload?: EmitPayload<P>] : [payload: EmitPayload<P>];\n\n/** Per-node push options. */\nexport interface PushOptions {\n /** Which devices get a copy: 'all' (the default) or only the most recently registered. */\n devices?: 'all' | 'latest';\n}\n\n/** `prefer()` options. */\nexport interface PreferOptions {\n /** The generated branch's name in IR (UI title / observability handle), as `branch(label, …)`. */\n label?: string;\n}\n\n/** The candidates `prefer()` takes: one push and one email template, in priority order. */\ntype PreferPair = readonly [PushTemplate, EmailTemplate] | readonly [EmailTemplate, PushTemplate];\n\ntype NormalizeProps<P> = { -readonly [K in keyof P]: P[K] };\ntype Equal<A, B> =\n (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;\n\n/** Both candidates render the one props object, so they must declare the same props type — not merely overlap. */\ntype SameProps<T extends PreferPair> =\n Equal<NormalizeProps<PropsOf<T[0]>>, NormalizeProps<PropsOf<T[1]>>> extends true\n ? unknown\n : { readonly __prefer_error__: 'Both templates must declare the same props type' };\n\n/** Distributes, so a field only one member of a union variable has still counts as extra. */\ntype KeysOfUnion<A> = A extends unknown ? keyof A : never;\n/** Rejects known extra fields, which `{}` (an empty props schema) would otherwise accept. */\ntype NoExtra<A, P> = Record<Exclude<KeysOfUnion<A>, keyof P>, never>;\n\n/** prefer() is typed strictly, but a JS caller (or an `any`) reaches it unchecked — fail at the call, not at send time. */\nfunction checkPreferArgs(candidates: unknown, props: unknown, options: unknown): void {\n if (!Array.isArray(candidates) || candidates.length !== 2) {\n throw new TypeError('prefer(): candidates must be exactly two templates — one push, one email');\n }\n const channels = (candidates as unknown[]).map((candidate) =>\n isTemplate(candidate) ? CHANNEL_OF[candidate.kind] : undefined\n );\n if (!channels.every((channel) => channel === 'push' || channel === 'email')) {\n throw new TypeError('prefer(): each candidate must be a pushTemplate or an emailTemplate');\n }\n if (channels[0] === channels[1]) {\n throw new TypeError('prefer(): candidates must be one push and one email template');\n }\n if (typeof props !== 'object' || props === null || Array.isArray(props)) {\n throw new TypeError(\n 'prefer(): props must be an object — pass {} when the templates declare none'\n );\n }\n if (options === undefined) return;\n if (typeof options !== 'object' || options === null || Array.isArray(options)) {\n throw new TypeError('prefer(): options must be an object');\n }\n for (const [name, value] of Object.entries(options)) {\n if (name !== 'label') {\n throw new TypeError(\n `prefer(): unknown option '${name}' — props go in the second argument, options take only 'label'`\n );\n }\n if (typeof value !== 'string') throw new TypeError(\"prefer(): 'label' must be a string\");\n }\n}\n\n/** A reusable flow fragment (what `flow(...)` returns), referenced directly by branch arms. */\nexport interface Flow {\n readonly __flow: true;\n}\n\ninterface FlowInternal extends Flow {\n readonly nodes: NodeIR[];\n readonly uses: readonly TemplateUse[];\n readonly actions: readonly ActionRef[];\n}\n\n/**\n * @internal A template definition a flow sends, kept beside the IR (which names it by id only):\n * compileConfig checks that the registered definition under that id is this very object, so the\n * schema that typed the call is the one that renders it. Never part of the IR or its hash.\n */\nexport interface TemplateUse {\n readonly template: AnyTemplate;\n readonly loc: SourceLocIR | undefined;\n}\n\n/** @internal The template definitions a workflow sends, sub-flows and fragments included. */\nexport function templateUses(builder: FlowBuilder): readonly TemplateUse[] {\n return builder instanceof FlowBuilderImpl ? builder.uses : [];\n}\n\n/**\n * @internal The action definitions a workflow runs, sub-flows and fragments included. The IR\n * names an action only; compileBundle checks that each ref is the very object listed in\n * `actions`, which is what keeps two definitions from sharing one name. Never part of the IR.\n */\nexport function actionUses(builder: FlowBuilder): readonly ActionRef[] {\n return builder instanceof FlowBuilderImpl ? builder.actions : [];\n}\n\n/** Sub-flow: a named fragment, or an inline callback (runs once at construction — builder in, builder out). */\nexport type SubFlow = Flow | ((w: FlowBuilder) => FlowBuilder);\n\n/** A branch arm: the [condition, sub-flow] tuple — an [if, then] ordering convention. */\nexport type BranchCase = readonly [condition: Condition, flow: SubFlow];\n\n/**\n * A branch argument: either a tuple arm, or a bare sub-flow meaning the default\n * arm. The bare form may appear once, and must come last (checked at runtime).\n */\nexport type BranchArm = BranchCase | SubFlow;\n\n/**\n * A cohort arm name has two jobs, and both constrain its spelling:\n * - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),\n * and an id is a durable step name — a dot would fake a nesting level and can\n * collide with a real one, an empty name gives '{id}..{j}';\n * - it is an object key, and JavaScript lists integer-like keys first in\n * ascending numeric order however the author wrote them. The arms array is\n * documented (and interpreted) as authoring order, and the bucketing walk\n * accumulates weights along it, so an arm named '0' added to a live\n * experiment would prepend itself and re-bucket everyone already in it.\n */\nconst ARM_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;\n\n/** A sub-flow's nodes; the template definitions it sends and the actions it runs are added to `uses` / `actions`. */\nfunction resolveSubFlow(sub: SubFlow, uses: TemplateUse[], actions: ActionRef[]): NodeIR[] {\n if (typeof sub === 'function') {\n const builder = new FlowBuilderImpl();\n const returned: unknown = sub(builder);\n // An async callback would add its nodes after construction is over — after ids were assigned\n if (typeof (returned as { then?: unknown } | undefined)?.then === 'function') {\n throw new TypeError(\n 'sub-flow callbacks must be synchronous: they run once, while the workflow is defined'\n );\n }\n uses.push(...builder.uses);\n actions.push(...builder.actions);\n return builder.nodes;\n }\n uses.push(...(sub as FlowInternal).uses);\n actions.push(...(sub as FlowInternal).actions);\n /*\n * A named fragment is a value, and the convention is to reuse it — two branch\n * arms may hold the same one. Handing out its own nodes aliases them into\n * both places, and assignIds writes ids *in place*: the second prefix\n * overwrites the first, so the two placements end up as one object under one\n * id — one durable step name, one message idempotency key, one bucket seed.\n * A copy per placement is what makes a fragment behave like a value.\n */\n return structuredClone((sub as FlowInternal).nodes);\n}\n\nexport interface FlowBuilder {\n /* ---- Messages: every channel is one message node; separate methods buy channel-level typing ---- */\n email<T extends EmailTemplate>(template: T, ...props: MessageArgs<PropsOf<T>>): this;\n sms<P extends object>(template: TemplateRef<'sms', P>, ...props: MessageArgs<P>): this;\n /**\n * Push to the user's devices — every device the host's directory lists, or\n * only the most recently registered with `{ devices: 'latest' }`. A user with\n * no device is skipped (`prefer([pushTpl, emailTpl], props)` falls back to email).\n */\n push<T extends PushTemplate>(\n template: T,\n ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]\n ): this;\n inApp<P extends object>(template: TemplateRef<'in_app', P>, ...props: MessageArgs<P>): this;\n slack<T extends SlackTemplate<PropsSchema, never>>(\n template: T,\n ...props: MessageArgs<PropsOf<T>>\n ): this;\n discord<T extends DiscordTemplate<PropsSchema, never>>(\n template: T,\n ...props: MessageArgs<PropsOf<T>>\n ): this;\n survey<P extends object>(template: TemplateRef<'survey', P>, ...props: MessageArgs<P>): this;\n\n /**\n * Send one message on the first channel the user can be reached on: one push\n * and one email template, in priority order, rendered with the same props.\n * Sugar for the branch it compiles to — same IR, ids and hash as writing\n *\n * .branch(label, [reachable(first.channel), (b) => b.<first>(first, props)], (b) => b.<second>(second, props))\n *\n * so the choice is made once, when the step is reached, and a first choice\n * that fails to send retries as itself — it never falls through to the\n * second. Props are always passed (`{}` for templates that declare none),\n * and both templates must declare the same props type; for differing props\n * or other channels, write the branch.\n *\n * .prefer([push.tip, email.tip], { name: u.name }, { label: 'tip by channel' })\n */\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>,\n options?: PreferOptions\n ): this;\n\n /* --------------------------------- Delays --------------------------------- */\n /** Time Delay; passing { min, max } makes it a Randomized Delay. */\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n\n /** Time Window: hold until inside the window (e.g. weekdays 09:00–17:00). tz: 'user' uses the user's timezone. */\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this;\n\n /**\n * Wait Until: continue on the main line once the condition holds, or take\n * onTimeout when it expires (default 'continue'). On the engine side this is\n * \"await event racing a timer\" — a native primitive of durable runtimes.\n */\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this;\n\n /**\n * Splice a fragment in place: a named `flow(...)` or a callback, expanded\n * once while the workflow is defined — a composition step before compiling,\n * not a node (the IR has no trace of it, and ids are assigned over the whole\n * workflow as if the steps were written inline). Each use gets its own copy,\n * so one fragment can be used in several places and workflows.\n *\n * const officeHours = flow((w) => w.timeWindow({ days: ['mon', 'tue', 'wed', 'thu', 'fri'], between: ['09:00', '17:00'] }));\n * workflow({ id: 'onboarding', ... }).delay('1 day').use(officeHours).email(email.tip, { name: u.name })\n */\n use(fragment: SubFlow): this;\n\n /* ------------------------------ Flow Control ------------------------------ */\n /**\n * Conditional branch: ordered first-match (same semantics as Step Functions\n * Choice / Knock branch). This one primitive covers both the UI's True/False\n * Branch (two arms) and Multi-Split Branch (N arms). Arms are\n * [condition, sub-flow] tuples; a bare sub-flow in tail position is the\n * default arm. With no match and no default, execution simply continues.\n * Rejoin is structural: after the matching arm finishes, execution resumes\n * at the node following the branch — to opt out, call .exit() inside the arm.\n *\n * .branch([activeSubscriber, upgradeFlow], firstTimeFlow) // True/False\n * .branch([vip, vipFlow], [trial, trialFlow], defaultFlow) // Multi-Split\n * .branch([not(usedStaging), eduFlow]) // single arm: no match continues\n *\n * The optional first argument `label` becomes the node's name in IR (UI title\n * / observability handle). It is not a jump target — there is no goto here;\n * looping is a future re-entry-policy topic (see sendEvent). Arm labels in\n * the UI are derived from the condition.\n */\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n\n /**\n * Gate: exit unless the condition holds, otherwise continue. A first-class\n * node rather than sugar over branch — same semantics as Zapier's \"only\n * continue if\" / Iterable's Filter tile, and rendered on its own in the UI.\n * `reason` is the audit-log line — metadata, so rewording it is free\n * (excluded from contentHash, see hash.ts).\n */\n filter(condition: Condition, opts?: { reason?: string }): this;\n\n /**\n * Random Cohort Branch (A/B): weights must sum to 100 (checked at runtime).\n * `key` names the experiment: bucketing hashes `userId:key` instead of the\n * structural node id, so assignments survive node insertion/moves and the\n * experiment keeps one identity across workflow versions — set it for any\n * A/B whose results you intend to read.\n *\n * Arm names become node id segments and are read back in authoring order, so\n * they are restricted to letters, digits, '_' and '-', never starting with a\n * digit (checked at runtime).\n */\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this;\n\n /**\n * Exit: end the whole workflow immediately (the UI's Exit node); `reason`\n * goes into the audit log and is metadata, so rewording it neither repins\n * in-flight journeys nor shows up in plan. Inside a branch arm this means\n * \"terminate, do not rejoin\" — it stops here instead of falling through,\n * while an arm without exit rejoins naturally.\n */\n exit(reason?: string): this;\n\n /* ---------------------------------- Data ---------------------------------- */\n /**\n * Emit a typed event (customer.io's Send Event). The event comes from an\n * e.xxx reference, so payload types flow in the same way trigger.event works.\n * This is how workflows compose: an event can trigger another workflow, and\n * the resulting call graph is statically analyzable. Payload values may\n * reference u.xxx. Only scalar fields can be sent (IR carries literals and\n * profile refs, not nested JSON): an event whose payload requires a nested\n * field cannot be emitted from a journey, and the types say so.\n *\n * Note on loops: a trailing self-triggering sendEvent will become the\n * official periodic-flow shape *once a re-entry policy exists* — today the\n * entry policy is once-per-user, so a self-trigger cannot re-enter and does\n * not loop.\n * TODO: the rest of the Data category — outbound webhook / profile update /\n * journey attributes.\n */\n sendEvent<P extends object>(event: EventRef<P>, ...payload: EmitArgs<P>): this;\n\n /**\n * Run a custom action (see dsl/action.ts for the model). The chain records\n * identity only — name and args — never the code: the implementation\n * ships inside the deployed Worker bundle and is resolved by name from the\n * runtime registry. Args are typed by the ActionRef and may reference u.xxx,\n * resolved at run time exactly like message props. Executed inside a durable\n * step: retried on throw, checkpointed on success.\n */\n run<A extends object>(action: ActionRef<A>, ...args: MessageArgs<A>): this;\n}\n\nconst DEFINED_CHANNELS: ReadonlySet<ChannelIR> = new Set(Object.values(CHANNEL_OF));\n\n/** A message's template: a definition of the channel (named by its id), or a reference by key. */\ntype MessageTemplate = AnyTemplate | TemplateRef;\n\nfunction templateKey(channel: ChannelIR, tpl: MessageTemplate): string {\n if (!DEFINED_CHANNELS.has(channel)) return (tpl as TemplateRef).key;\n // Typed, but a JS caller (or an `any`) reaches it unchecked: fail where the workflow is written\n if (!isTemplate(tpl) || CHANNEL_OF[tpl.kind] !== channel) {\n throw new TypeError(`${channel}(): expects a ${channel} template definition`);\n }\n return tpl.id;\n}\n\nfunction messageNode(\n channel: ChannelIR,\n tpl: MessageTemplate,\n props: object | undefined,\n devices?: 'latest'\n): NodeIR {\n return {\n id: '',\n type: 'message',\n channel,\n template: templateKey(channel, tpl),\n props: (props ?? {}) as Record<string, PropValueIR>,\n // Absent for 'all', so adding the option left every existing push's hash as it was\n ...(devices !== undefined ? { devices } : {}),\n };\n}\n\n/* oxlint-disable typescript/unbound-method --\n * `captureLoc(this.xxx)` passes the method by identity as the stack-trace\n * boundary for Error.captureStackTrace; it is never invoked, so `this`\n * scoping cannot go wrong. */\n/** @internal extended by WorkflowBuilderImpl; not part of the public API */\nexport class FlowBuilderImpl implements FlowBuilder {\n /** Nodes as collected; ids are assigned in one pass inside toIR, so '' is a placeholder here. */\n readonly nodes: NodeIR[] = [];\n /** The template definitions sent, with where: compile-time only, never in the IR. */\n readonly uses: TemplateUse[] = [];\n /** The action definitions run: compile-time identity only, never in the IR. */\n readonly actions: ActionRef[] = [];\n\n /** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */\n private pushNode(node: NodeIR, loc: SourceLocIR | undefined): this {\n this.nodes.push({ ...node, ...(loc !== undefined ? { meta: { loc } } : {}) });\n return this;\n }\n\n private message(\n channel: ChannelIR,\n tpl: MessageTemplate,\n props: object | undefined,\n loc: SourceLocIR | undefined,\n devices?: 'latest'\n ): this {\n this.pushNode(messageNode(channel, tpl, props, devices), loc);\n if (isTemplate(tpl)) this.uses.push({ template: tpl, loc });\n return this;\n }\n\n email<T extends EmailTemplate>(t: T, ...args: MessageArgs<PropsOf<T>>): this {\n return this.message('email', t, args[0], captureLoc(this.email));\n }\n sms<P extends object>(t: TemplateRef<'sms', P>, ...args: MessageArgs<P>): this {\n return this.message('sms', t, args[0], captureLoc(this.sms));\n }\n push<T extends PushTemplate>(\n t: T,\n ...args: [...props: MessageArgs<PropsOf<T>>, options?: PushOptions]\n ): this {\n const [props, options] = args as unknown as [object | undefined, PushOptions | undefined];\n const devices = options?.devices === 'latest' ? 'latest' : undefined;\n return this.message('push', t, props, captureLoc(this.push), devices);\n }\n inApp<P extends object>(t: TemplateRef<'in_app', P>, ...args: MessageArgs<P>): this {\n return this.message('in_app', t, args[0], captureLoc(this.inApp));\n }\n slack<T extends SlackTemplate<PropsSchema, never>>(t: T, ...args: MessageArgs<PropsOf<T>>): this {\n return this.message('slack', t, args[0], captureLoc(this.slack));\n }\n discord<T extends DiscordTemplate<PropsSchema, never>>(\n t: T,\n ...args: MessageArgs<PropsOf<T>>\n ): this {\n return this.message('discord', t, args[0], captureLoc(this.discord));\n }\n survey<P extends object>(t: TemplateRef<'survey', P>, ...args: MessageArgs<P>): this {\n return this.message('survey', t, args[0], captureLoc(this.survey));\n }\n\n prefer<const T extends PreferPair, const A extends PropsInput<NoInfer<PropsOf<T[0]>>>>(\n candidates: T & SameProps<NoInfer<T>>,\n props: A & NoInfer<NoExtra<A, PropsOf<T[0]>>>,\n options?: PreferOptions\n ): this {\n checkPreferArgs(candidates, props, options);\n // Every generated node points at the author's prefer() call, not at this method's body\n const loc = captureLoc(this.prefer);\n const meta = loc !== undefined ? { meta: { loc } } : {};\n const [first, second] = candidates as readonly (EmailTemplate | PushTemplate)[];\n const channel = (tpl: EmailTemplate | PushTemplate) => CHANNEL_OF[tpl.kind] as 'email' | 'push';\n // Both are sent from here as far as the registry check goes, the fallback included\n this.uses.push({ template: first, loc }, { template: second, loc });\n // A copy per message, as two separately written calls would hold\n const arm = (tpl: EmailTemplate | PushTemplate): NodeIR[] => [\n { ...messageNode(channel(tpl), tpl, { ...props }), ...meta },\n ];\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(options?.label !== undefined ? { label: options.label } : {}),\n cases: [\n { condition: { type: 'reachable', channel: channel(first), ...meta }, flow: arm(first) },\n ],\n otherwise: arm(second),\n },\n loc\n );\n }\n\n delay(duration: Duration): this;\n delay(range: { min: Duration; max: Duration }): this;\n delay(d: Duration | { min: Duration; max: Duration }): this {\n const loc = captureLoc(this.delay);\n if (typeof d === 'string') {\n return this.pushNode({ id: '', type: 'delay', duration: durationIR(d) }, loc);\n }\n const min = durationIR(d.min);\n const max = durationIR(d.max);\n /*\n * The interpreter draws `min + random(max - min)` with the span clamped at\n * zero, so a backwards range does not fail — it quietly collapses into a\n * fixed `min` sleep. Reject it here, where the author can still see it.\n */\n if (max.ms < min.ms) {\n throw new Error(\n `delay(): 'max' must not be shorter than 'min', got { min: '${d.min}', max: '${d.max}' }`\n );\n }\n return this.pushNode({ id: '', type: 'random_delay', min, max }, loc);\n }\n\n timeWindow(opts: {\n days?: readonly Weekday[];\n between: readonly [TimeOfDay, TimeOfDay];\n tz?: 'user' | (string & {});\n }): this {\n const loc = captureLoc(this.timeWindow);\n if (opts.days !== undefined) {\n // An empty list is a window that never opens: the node would hold the user forever\n if (opts.days.length === 0) {\n throw new Error(\"timeWindow(): 'days' must name at least one day\");\n }\n const seen = new Set<Weekday>();\n for (const day of opts.days) {\n if (seen.has(day)) throw new Error(`timeWindow(): 'days' lists '${day}' twice`);\n seen.add(day);\n }\n }\n const start = timeOfDayMinutes(opts.between[0]);\n const end = timeOfDayMinutes(opts.between[1]);\n if (end <= start) {\n throw new Error(\n `timeWindow(): 'between' must open before it closes within one day, got [${opts.between[0]}, ${opts.between[1]}] (overnight windows are not supported yet)`\n );\n }\n return this.pushNode(\n {\n id: '',\n type: 'time_window',\n days: [...(opts.days ?? (['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun'] as const))],\n between: [opts.between[0], opts.between[1]],\n tz: opts.tz ?? 'user',\n },\n loc\n );\n }\n\n waitUntil(\n condition: Condition,\n opts: { timeout: Duration; onTimeout?: 'continue' | 'exit' | SubFlow }\n ): this {\n const loc = captureLoc(this.waitUntil);\n const onTimeout = opts.onTimeout ?? 'continue';\n return this.pushNode(\n {\n id: '',\n type: 'wait_until',\n condition: condIR(condition),\n timeout: positiveDurationIR(opts.timeout, 'waitUntil(): timeout'),\n onTimeout:\n onTimeout === 'continue' || onTimeout === 'exit'\n ? onTimeout\n : resolveSubFlow(onTimeout, this.uses, this.actions),\n },\n loc\n );\n }\n\n use(fragment: SubFlow): this {\n // The fragment's nodes carry their own provenance (where the fragment was written)\n this.nodes.push(...resolveSubFlow(fragment, this.uses, this.actions));\n return this;\n }\n\n branch(...arms: readonly BranchArm[]): this;\n branch(label: string, ...arms: readonly BranchArm[]): this;\n branch(...args: readonly (string | BranchArm)[]): this {\n const loc = captureLoc(this.branch);\n const label = typeof args[0] === 'string' ? args[0] : undefined;\n const arms = (label === undefined ? args : args.slice(1)) as readonly BranchArm[];\n\n const cases: { condition: ConditionIR; flow: NodeIR[] }[] = [];\n let otherwise: NodeIR[] | undefined;\n arms.forEach((arm, i) => {\n if (Array.isArray(arm)) {\n if (otherwise !== undefined) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n const [condition, sub] = arm as BranchCase;\n cases.push({\n condition: condIR(condition),\n flow: resolveSubFlow(sub, this.uses, this.actions),\n });\n } else {\n if (otherwise !== undefined) {\n throw new Error('branch(): only one default arm (bare sub-flow) is allowed');\n }\n if (i !== arms.length - 1) {\n throw new Error('branch(): default arm (bare sub-flow) must be the last argument');\n }\n otherwise = resolveSubFlow(arm as SubFlow, this.uses, this.actions);\n }\n });\n\n return this.pushNode(\n {\n id: '',\n type: 'branch',\n ...(label !== undefined ? { label } : {}),\n cases,\n ...(otherwise !== undefined ? { otherwise } : {}),\n },\n loc\n );\n }\n\n filter(condition: Condition, opts?: { reason?: string }): this {\n return this.pushNode(\n {\n id: '',\n type: 'filter',\n condition: condIR(condition),\n ...(opts?.reason !== undefined ? { reason: opts.reason } : {}),\n },\n captureLoc(this.filter)\n );\n }\n\n cohort(arms: Record<string, { weight: number; flow?: SubFlow }>, opts?: { key?: string }): this {\n const loc = captureLoc(this.cohort);\n const entries = Object.entries(arms);\n /*\n * Weights live on a 0.01% grid: the runtime buckets into 10,000 slots\n * (basis points), so anything finer would be silently quantized — reject\n * it here instead. Converting to integer basis points also makes the\n * sum check exact; no epsilon needed.\n */\n const basisPoints = entries.map(([name, a]) => {\n if (!ARM_NAME.test(name)) {\n throw new Error(\n `cohort(): arm name '${name}' must start with a letter or '_' and contain only letters, digits, '_' or '-' — arm names become node id segments, and integer-like names would silently reorder the arms`\n );\n }\n const bp = a.weight * 100;\n if (Math.abs(bp - Math.round(bp)) > 1e-6) {\n throw new Error(\n `cohort(): arm '${name}' weight ${a.weight} is finer than the 0.01% bucketing grid — use at most two decimal places`\n );\n }\n /*\n * The sum check alone accepts -50 / 150: the runtime walks the arms\n * accumulating basis points and takes the first whose cumulative total\n * clears the bucket, so a negative weight hands 100% of users to its\n * neighbour instead of splitting anything.\n */\n if (bp < 0) {\n throw new Error(`cohort(): arm '${name}' weight ${a.weight} must not be negative`);\n }\n return Math.round(bp);\n });\n const total = basisPoints.reduce((sum, bp) => sum + bp, 0);\n if (total !== 10_000) {\n throw new Error(`cohort(): weights must sum to 100, got ${total / 100}`);\n }\n return this.pushNode(\n {\n id: '',\n type: 'cohort',\n ...(opts?.key !== undefined ? { key: opts.key } : {}),\n arms: entries.map(([name, a]) => ({\n name,\n weight: a.weight,\n flow: a.flow ? resolveSubFlow(a.flow, this.uses, this.actions) : [],\n })),\n },\n loc\n );\n }\n\n exit(reason?: string): this {\n return this.pushNode(\n { id: '', type: 'exit', ...(reason !== undefined ? { reason } : {}) },\n captureLoc(this.exit)\n );\n }\n\n sendEvent<P extends object>(ev: EventRef<P>, ...payload: EmitArgs<P>): this {\n const values = (payload[0] ?? {}) as Record<string, unknown>;\n for (const [field, value] of Object.entries(values)) {\n const ref =\n typeof value === 'object' &&\n value !== null &&\n (value as { type?: unknown }).type === 'user_property';\n if (!ref && !['string', 'number', 'boolean'].includes(typeof value)) {\n throw new TypeError(\n `sendEvent('${ev.name}'): '${field}' is not a scalar or a u.xxx reference — an emitted payload carries scalar fields only`\n );\n }\n }\n return this.pushNode(\n {\n id: '',\n type: 'send_event',\n event: ev.name,\n payload: values as Record<string, PropValueIR>,\n },\n captureLoc(this.sendEvent)\n );\n }\n\n run<A extends object>(a: ActionRef<A>, ...args: MessageArgs<A>): this {\n this.actions.push(a);\n return this.pushNode(\n {\n id: '',\n type: 'action',\n action: a.name,\n args: (args[0] ?? {}) as Record<string, PropValueIR>,\n },\n captureLoc(this.run)\n );\n }\n}\n/* oxlint-enable typescript/unbound-method */\n\n/**\n * A reusable flow fragment: a free function. Once personalization goes through\n * u.xxx and events through e.xxx, the flow layer carries no schema generics.\n */\nexport function flow(build: (w: FlowBuilder) => FlowBuilder): Flow {\n const builder = new FlowBuilderImpl();\n build(builder);\n const impl: FlowInternal = {\n __flow: true,\n nodes: builder.nodes,\n uses: builder.uses,\n actions: builder.actions,\n };\n return impl;\n}\n"],"mappings":";;;;;;;AA0EA,SAAS,gBAAgB,YAAqB,OAAgB,SAAwB;CACpF,IAAI,CAAC,MAAM,QAAQ,UAAU,KAAK,WAAW,WAAW,GACtD,MAAM,IAAI,UAAU,0EAA0E;CAEhG,MAAM,WAAY,WAAyB,KAAK,cAC9CA,kBAAAA,WAAW,SAAS,IAAIC,kBAAAA,WAAW,UAAU,QAAQ,KAAA,CACvD;CACA,IAAI,CAAC,SAAS,OAAO,YA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;IACV,MAAM,EAAE,OAAO,eAAe,EAAE,MAAM,KAAK,MAAM,KAAK,OAAO,IAAI,CAAC;GACpE,EAAE;EACJ,GACA,GACF;CACF;CAEA,KAAK,QAAuB;EAC1B,OAAO,KAAK,SACV;GAAE,IAAI;GAAI,MAAM;GAAQ,GAAI,WAAW,KAAA,IAAY,EAAE,OAAO,IAAI,CAAC;EAAG,GACpEA,mBAAAA,WAAW,KAAK,IAAI,CACtB;CACF;CAEA,UAA4B,IAAiB,GAAG,SAA4B;EAC1E,MAAM,SAAU,QAAQ,MAAM,CAAC;EAC/B,KAAK,MAAM,CAAC,OAAO,UAAU,OAAO,QAAQ,MAAM,GAKhD,IAAI,EAHF,OAAO,UAAU,YACjB,UAAU,QACT,MAA6B,SAAS,oBAC7B,CAAC;GAAC;GAAU;GAAU;EAAS,CAAC,CAAC,SAAS,OAAO,KAAK,GAChE,MAAM,IAAI,UACR,cAAc,GAAG,KAAK,OAAO,MAAM,uFACrC;EAGJ,OAAO,KAAK,SACV;GACE,IAAI;GACJ,MAAM;GACN,OAAO,GAAG;GACV,SAAS;EACX,GACAA,mBAAAA,WAAW,KAAK,SAAS,CAC3B;CACF;CAEA,IAAsB,GAAiB,GAAG,MAA4B;EACpE,KAAK,QAAQ,KAAK,CAAC;EACnB,OAAO,KAAK,SACV;GACE,IAAI;GACJ,MAAM;GACN,QAAQ,EAAE;GACV,MAAO,KAAK,MAAM,CAAC;EACrB,GACAA,mBAAAA,WAAW,KAAK,GAAG,CACrB;CACF;AACF;;;;;AAOA,SAAgB,KAAK,OAA8C;CACjE,MAAM,UAAU,IAAI,gBAAgB;CACpC,MAAM,OAAO;CAOb,OAAO;EALL,QAAQ;EACR,OAAO,QAAQ;EACf,MAAM,QAAQ;EACd,SAAS,QAAQ;CAET;AACZ"}
|
package/dist/dsl/flow.d.cts
CHANGED
|
@@ -62,6 +62,12 @@ export interface TemplateUse {
|
|
|
62
62
|
}
|
|
63
63
|
/** @internal The template definitions a workflow sends, sub-flows and fragments included. */
|
|
64
64
|
export declare function templateUses(builder: FlowBuilder): readonly TemplateUse[];
|
|
65
|
+
/**
|
|
66
|
+
* @internal The action definitions a workflow runs, sub-flows and fragments included. The IR
|
|
67
|
+
* names an action only; compileBundle checks that each ref is the very object listed in
|
|
68
|
+
* `actions`, which is what keeps two definitions from sharing one name. Never part of the IR.
|
|
69
|
+
*/
|
|
70
|
+
export declare function actionUses(builder: FlowBuilder): readonly ActionRef[];
|
|
65
71
|
/** Sub-flow: a named fragment, or an inline callback (runs once at construction — builder in, builder out). */
|
|
66
72
|
export type SubFlow = Flow | ((w: FlowBuilder) => FlowBuilder);
|
|
67
73
|
/** A branch arm: the [condition, sub-flow] tuple — an [if, then] ordering convention. */
|
|
@@ -206,7 +212,7 @@ export interface FlowBuilder {
|
|
|
206
212
|
sendEvent<P extends object>(event: EventRef<P>, ...payload: EmitArgs<P>): this;
|
|
207
213
|
/**
|
|
208
214
|
* Run a custom action (see dsl/action.ts for the model). The chain records
|
|
209
|
-
* identity only — name
|
|
215
|
+
* identity only — name and args — never the code: the implementation
|
|
210
216
|
* ships inside the deployed Worker bundle and is resolved by name from the
|
|
211
217
|
* runtime registry. Args are typed by the ActionRef and may reference u.xxx,
|
|
212
218
|
* resolved at run time exactly like message props. Executed inside a durable
|
|
@@ -220,6 +226,8 @@ export declare class FlowBuilderImpl implements FlowBuilder {
|
|
|
220
226
|
readonly nodes: NodeIR[];
|
|
221
227
|
/** The template definitions sent, with where: compile-time only, never in the IR. */
|
|
222
228
|
readonly uses: TemplateUse[];
|
|
229
|
+
/** The action definitions run: compile-time identity only, never in the IR. */
|
|
230
|
+
readonly actions: ActionRef[];
|
|
223
231
|
/** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */
|
|
224
232
|
private pushNode;
|
|
225
233
|
private message;
|
package/dist/dsl/flow.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.d.cts","names":[],"sources":["../../src/dsl/flow.ts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ow sends, sub-flows and fragments included. */
|
|
64
64
|
export declare function templateUses(builder: FlowBuilder): readonly TemplateUse[];
|
|
65
|
+
/**
|
|
66
|
+
* @internal The action definitions a workflow runs, sub-flows and fragments included. The IR
|
|
67
|
+
* names an action only; compileBundle checks that each ref is the very object listed in
|
|
68
|
+
* `actions`, which is what keeps two definitions from sharing one name. Never part of the IR.
|
|
69
|
+
*/
|
|
70
|
+
export declare function actionUses(builder: FlowBuilder): readonly ActionRef[];
|
|
65
71
|
/** Sub-flow: a named fragment, or an inline callback (runs once at construction — builder in, builder out). */
|
|
66
72
|
export type SubFlow = Flow | ((w: FlowBuilder) => FlowBuilder);
|
|
67
73
|
/** A branch arm: the [condition, sub-flow] tuple — an [if, then] ordering convention. */
|
|
@@ -206,7 +212,7 @@ export interface FlowBuilder {
|
|
|
206
212
|
sendEvent<P extends object>(event: EventRef<P>, ...payload: EmitArgs<P>): this;
|
|
207
213
|
/**
|
|
208
214
|
* Run a custom action (see dsl/action.ts for the model). The chain records
|
|
209
|
-
* identity only — name
|
|
215
|
+
* identity only — name and args — never the code: the implementation
|
|
210
216
|
* ships inside the deployed Worker bundle and is resolved by name from the
|
|
211
217
|
* runtime registry. Args are typed by the ActionRef and may reference u.xxx,
|
|
212
218
|
* resolved at run time exactly like message props. Executed inside a durable
|
|
@@ -220,6 +226,8 @@ export declare class FlowBuilderImpl implements FlowBuilder {
|
|
|
220
226
|
readonly nodes: NodeIR[];
|
|
221
227
|
/** The template definitions sent, with where: compile-time only, never in the IR. */
|
|
222
228
|
readonly uses: TemplateUse[];
|
|
229
|
+
/** The action definitions run: compile-time identity only, never in the IR. */
|
|
230
|
+
readonly actions: ActionRef[];
|
|
223
231
|
/** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */
|
|
224
232
|
private pushNode;
|
|
225
233
|
private message;
|
package/dist/dsl/flow.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"flow.d.mts","names":[],"sources":["../../src/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|
import { durationIR, timeOfDayMinutes } from "./base.mjs";
|
|
3
|
-
import { condIR } from "./condition.mjs";
|
|
3
|
+
import { condIR, positiveDurationIR } from "./condition.mjs";
|
|
4
4
|
import { CHANNEL_OF, isTemplate } from "../templates.mjs";
|
|
5
5
|
//#region src/dsl/flow.ts
|
|
6
6
|
/** prefer() is typed strictly, but a JS caller (or an `any`) reaches it unchecked — fail at the call, not at send time. */
|
|
@@ -22,6 +22,14 @@ function templateUses(builder) {
|
|
|
22
22
|
return builder instanceof FlowBuilderImpl ? builder.uses : [];
|
|
23
23
|
}
|
|
24
24
|
/**
|
|
25
|
+
* @internal The action definitions a workflow runs, sub-flows and fragments included. The IR
|
|
26
|
+
* names an action only; compileBundle checks that each ref is the very object listed in
|
|
27
|
+
* `actions`, which is what keeps two definitions from sharing one name. Never part of the IR.
|
|
28
|
+
*/
|
|
29
|
+
function actionUses(builder) {
|
|
30
|
+
return builder instanceof FlowBuilderImpl ? builder.actions : [];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
25
33
|
* A cohort arm name has two jobs, and both constrain its spelling:
|
|
26
34
|
* - it is interpolated into the node ids of the arm's flow ('{id}.{name}.{j}'),
|
|
27
35
|
* and an id is a durable step name — a dot would fake a nesting level and can
|
|
@@ -33,15 +41,17 @@ function templateUses(builder) {
|
|
|
33
41
|
* experiment would prepend itself and re-bucket everyone already in it.
|
|
34
42
|
*/
|
|
35
43
|
const ARM_NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
36
|
-
/** A sub-flow's nodes; the template definitions it sends are added to `uses`. */
|
|
37
|
-
function resolveSubFlow(sub, uses) {
|
|
44
|
+
/** A sub-flow's nodes; the template definitions it sends and the actions it runs are added to `uses` / `actions`. */
|
|
45
|
+
function resolveSubFlow(sub, uses, actions) {
|
|
38
46
|
if (typeof sub === "function") {
|
|
39
47
|
const builder = new FlowBuilderImpl();
|
|
40
48
|
if (typeof sub(builder)?.then === "function") throw new TypeError("sub-flow callbacks must be synchronous: they run once, while the workflow is defined");
|
|
41
49
|
uses.push(...builder.uses);
|
|
50
|
+
actions.push(...builder.actions);
|
|
42
51
|
return builder.nodes;
|
|
43
52
|
}
|
|
44
53
|
uses.push(...sub.uses);
|
|
54
|
+
actions.push(...sub.actions);
|
|
45
55
|
return structuredClone(sub.nodes);
|
|
46
56
|
}
|
|
47
57
|
const DEFINED_CHANNELS = new Set(Object.values(CHANNEL_OF));
|
|
@@ -66,6 +76,8 @@ var FlowBuilderImpl = class {
|
|
|
66
76
|
nodes = [];
|
|
67
77
|
/** The template definitions sent, with where: compile-time only, never in the IR. */
|
|
68
78
|
uses = [];
|
|
79
|
+
/** The action definitions run: compile-time identity only, never in the IR. */
|
|
80
|
+
actions = [];
|
|
69
81
|
/** Provenance: the callsite (captured in the public method) lands in meta.loc, outside the hash. */
|
|
70
82
|
pushNode(node, loc) {
|
|
71
83
|
this.nodes.push({
|
|
@@ -156,6 +168,14 @@ var FlowBuilderImpl = class {
|
|
|
156
168
|
}
|
|
157
169
|
timeWindow(opts) {
|
|
158
170
|
const loc = captureLoc(this.timeWindow);
|
|
171
|
+
if (opts.days !== void 0) {
|
|
172
|
+
if (opts.days.length === 0) throw new Error("timeWindow(): 'days' must name at least one day");
|
|
173
|
+
const seen = /* @__PURE__ */ new Set();
|
|
174
|
+
for (const day of opts.days) {
|
|
175
|
+
if (seen.has(day)) throw new Error(`timeWindow(): 'days' lists '${day}' twice`);
|
|
176
|
+
seen.add(day);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
159
179
|
const start = timeOfDayMinutes(opts.between[0]);
|
|
160
180
|
if (timeOfDayMinutes(opts.between[1]) <= start) throw new Error(`timeWindow(): 'between' must open before it closes within one day, got [${opts.between[0]}, ${opts.between[1]}] (overnight windows are not supported yet)`);
|
|
161
181
|
return this.pushNode({
|
|
@@ -181,12 +201,12 @@ var FlowBuilderImpl = class {
|
|
|
181
201
|
id: "",
|
|
182
202
|
type: "wait_until",
|
|
183
203
|
condition: condIR(condition),
|
|
184
|
-
timeout:
|
|
185
|
-
onTimeout: onTimeout === "continue" || onTimeout === "exit" ? onTimeout : resolveSubFlow(onTimeout, this.uses)
|
|
204
|
+
timeout: positiveDurationIR(opts.timeout, "waitUntil(): timeout"),
|
|
205
|
+
onTimeout: onTimeout === "continue" || onTimeout === "exit" ? onTimeout : resolveSubFlow(onTimeout, this.uses, this.actions)
|
|
186
206
|
}, loc);
|
|
187
207
|
}
|
|
188
208
|
use(fragment) {
|
|
189
|
-
this.nodes.push(...resolveSubFlow(fragment, this.uses));
|
|
209
|
+
this.nodes.push(...resolveSubFlow(fragment, this.uses, this.actions));
|
|
190
210
|
return this;
|
|
191
211
|
}
|
|
192
212
|
branch(...args) {
|
|
@@ -201,12 +221,12 @@ var FlowBuilderImpl = class {
|
|
|
201
221
|
const [condition, sub] = arm;
|
|
202
222
|
cases.push({
|
|
203
223
|
condition: condIR(condition),
|
|
204
|
-
flow: resolveSubFlow(sub, this.uses)
|
|
224
|
+
flow: resolveSubFlow(sub, this.uses, this.actions)
|
|
205
225
|
});
|
|
206
226
|
} else {
|
|
207
227
|
if (otherwise !== void 0) throw new Error("branch(): only one default arm (bare sub-flow) is allowed");
|
|
208
228
|
if (i !== arms.length - 1) throw new Error("branch(): default arm (bare sub-flow) must be the last argument");
|
|
209
|
-
otherwise = resolveSubFlow(arm, this.uses);
|
|
229
|
+
otherwise = resolveSubFlow(arm, this.uses, this.actions);
|
|
210
230
|
}
|
|
211
231
|
});
|
|
212
232
|
return this.pushNode({
|
|
@@ -243,7 +263,7 @@ var FlowBuilderImpl = class {
|
|
|
243
263
|
arms: entries.map(([name, a]) => ({
|
|
244
264
|
name,
|
|
245
265
|
weight: a.weight,
|
|
246
|
-
flow: a.flow ? resolveSubFlow(a.flow, this.uses) : []
|
|
266
|
+
flow: a.flow ? resolveSubFlow(a.flow, this.uses, this.actions) : []
|
|
247
267
|
}))
|
|
248
268
|
}, loc);
|
|
249
269
|
}
|
|
@@ -269,12 +289,12 @@ var FlowBuilderImpl = class {
|
|
|
269
289
|
}, captureLoc(this.sendEvent));
|
|
270
290
|
}
|
|
271
291
|
run(a, ...args) {
|
|
292
|
+
this.actions.push(a);
|
|
272
293
|
return this.pushNode({
|
|
273
294
|
id: "",
|
|
274
295
|
type: "action",
|
|
275
296
|
action: a.name,
|
|
276
|
-
args: args[0] ?? {}
|
|
277
|
-
codeHash: a.codeHash
|
|
297
|
+
args: args[0] ?? {}
|
|
278
298
|
}, captureLoc(this.run));
|
|
279
299
|
}
|
|
280
300
|
};
|
|
@@ -288,10 +308,11 @@ function flow(build) {
|
|
|
288
308
|
return {
|
|
289
309
|
__flow: true,
|
|
290
310
|
nodes: builder.nodes,
|
|
291
|
-
uses: builder.uses
|
|
311
|
+
uses: builder.uses,
|
|
312
|
+
actions: builder.actions
|
|
292
313
|
};
|
|
293
314
|
}
|
|
294
315
|
//#endregion
|
|
295
|
-
export { FlowBuilderImpl, flow, templateUses };
|
|
316
|
+
export { FlowBuilderImpl, actionUses, flow, templateUses };
|
|
296
317
|
|
|
297
318
|
//# sourceMappingURL=flow.mjs.map
|