@camstack/server 1.2.929 → 1.2.930

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.
Files changed (29) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/package.json +9 -11
  3. package/system/dist/builtins/alerts/alerts.addon.js +1 -1
  4. package/system/dist/builtins/alerts/alerts.addon.mjs +1 -1
  5. package/system/dist/builtins/composer/composer.addon.js +3 -3
  6. package/system/dist/builtins/composer/composer.addon.mjs +3 -3
  7. package/system/dist/builtins/core-blocks/actions-service.d.ts +18 -1
  8. package/system/dist/builtins/core-blocks/core-blocks.addon.js +986 -208
  9. package/system/dist/builtins/core-blocks/core-blocks.addon.mjs +985 -208
  10. package/system/dist/builtins/core-blocks/tcp-connect.d.ts +3 -0
  11. package/system/dist/builtins/core-notifier/core-notifier.addon.js +6 -487
  12. package/system/dist/builtins/core-notifier/core-notifier.addon.mjs +3 -484
  13. package/system/dist/builtins/device-manager/device-manager.addon.js +3 -3
  14. package/system/dist/builtins/device-manager/device-manager.addon.mjs +3 -3
  15. package/system/dist/{composition-sources-Caqv7O7z.mjs → composition-sources-BEUWn2s_.mjs} +1 -1
  16. package/system/dist/{composition-sources-CgnHjm8Q.js → composition-sources-acfR4hDq.js} +1 -1
  17. package/system/dist/{core-blocks.cap-LEMqVwxO.js → core-blocks.cap-BMeMCBrx.js} +37 -9
  18. package/system/dist/{core-blocks.cap-C6iKAZ-x.mjs → core-blocks.cap-BRPsLAij.mjs} +32 -10
  19. package/system/dist/index.js +2 -2
  20. package/system/dist/index.mjs +2 -2
  21. package/system/dist/{notification-rules.cap-B__YBgnG.js → notification-rules.cap-BDh0LDhV.js} +6 -0
  22. package/system/dist/{notification-rules.cap-D9ArZlwx.mjs → notification-rules.cap-DUmiMBQB.mjs} +1 -1
  23. package/system/dist/notification-targets-CRH-9Dy5.js +509 -0
  24. package/system/dist/notification-targets-DaNE-pIt.mjs +486 -0
  25. package/system/dist/{prefix-walk-DC0ljmbB.js → prefix-walk-BkMxoXpL.js} +1 -1
  26. package/system/dist/{prefix-walk-B4b2-9aK.mjs → prefix-walk-ifwg_ukx.mjs} +1 -1
  27. package/system/dist/{rename-composition-block-CcWLwVhG.js → rename-composition-block-BJsL58Ih.js} +121 -15
  28. package/system/dist/{rename-composition-block-7WIICIDq.mjs → rename-composition-block-OAtErZgq.mjs} +121 -15
  29. package/system/package.json +1 -1
@@ -11707,9 +11707,11 @@ function refineKnownAction(step, ctx) {
11707
11707
  }
11708
11708
  var AutomationCommandStepSchema = /* @__PURE__ */ AutomationCommandStepBaseSchema.superRefine(refineKnownAction);
11709
11709
  /**
11710
- * The steps an internal Action may contain: command and wait, and nothing that can
11711
- * call back into an Action — so an Action can never reach itself (no cycles).
11712
- * This is the LEAF shape: no condition of its own.
11710
+ * The leaf steps of an `else` list: command and wait, with no condition of their
11711
+ * own. (An Action's own list is wider: {@link ActionStepSchema}. It may call
11712
+ * another Action, so the cycle is cut elsewhere — `findActionCycle` refuses the
11713
+ * save that closes one, and a run carries a visited set and a depth bound,
11714
+ * `action-graph.ts`.)
11713
11715
  */
11714
11716
  var LeafActionStepSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [AutomationWaitStepSchema, AutomationCommandStepSchema]);
11715
11717
  /**
@@ -11729,11 +11731,13 @@ var elseNeedsIf = {
11729
11731
  var GuardedWaitStepSchema = /* @__PURE__ */ AutomationWaitStepSchema.extend(stepGuardShape).refine((step) => step.else === void 0 || step.if !== void 0, elseNeedsIf);
11730
11732
  var GuardedCommandStepSchema = /* @__PURE__ */ AutomationCommandStepBaseSchema.extend(stepGuardShape).superRefine(refineKnownAction).refine((step) => step.else === void 0 || step.if !== void 0, elseNeedsIf);
11731
11733
  /**
11732
- * A step of a STANDALONE list (an action, a scheduler point, a preset): the
11733
- * same two step kinds an automation runs, minus a guard that reads the
11734
- * automation's trigger, which such a list does not have.
11734
+ * The NARROW step of a list that runs a device command or waits, and nothing
11735
+ * else: a scheduler point, a notification rule's action list. Pinned on
11736
+ * purpose — such a list has no run bag, no notification target of its own and
11737
+ * no place to nest a block, so it is not offered the rest of an Action's steps.
11738
+ * It is a subset of {@link ActionStep}: a runner built for the wide step runs it.
11735
11739
  */
11736
- var ActionStepSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [GuardedWaitStepSchema, GuardedCommandStepSchema]).superRefine((step, ctx) => {
11740
+ var NarrowActionStepSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [GuardedWaitStepSchema, GuardedCommandStepSchema]).superRefine((step, ctx) => {
11737
11741
  if (step.if !== void 0 && hasTriggeredByLeaves(step.if)) ctx.addIssue({
11738
11742
  code: "custom",
11739
11743
  message: TRIGGERED_BY_NEEDS_AUTOMATION,
@@ -11804,6 +11808,8 @@ var AutomationNotifyStepSchema = /* @__PURE__ */ z.object({
11804
11808
  var HTTP_URL_MAX = 2e3;
11805
11809
  var HTTP_BODY_MAX = 16384;
11806
11810
  var HTTP_HEADER_VALUE_MAX = 1e3;
11811
+ /** How much of a response body a run keeps, in bytes: the rest is cut. */
11812
+ var HTTP_TEXT_CAP = 65536;
11807
11813
  var saveAsSchema = /* @__PURE__ */ z.string().regex(SET_VAR_NAME_RE, "a variable name is letters, digits and _, not starting with a digit (max 40)").refine((name) => !RESERVED_RUN_VARS.includes(name), { message: `the names ${/* @__PURE__ */ RESERVED_RUN_VARS.join(", ")} belong to the run and cannot be used` });
11808
11814
  var retryUntilSecondsSchema = /* @__PURE__ */ z.number().int().min(1).max(600, `a retry window is at most 600 s`);
11809
11815
  /**
@@ -12051,6 +12057,13 @@ var AutomationActionSchema = /* @__PURE__ */ z.discriminatedUnion("kind", [
12051
12057
  code: /* @__PURE__ */ z.string().min(1).max(2e4)
12052
12058
  })
12053
12059
  ]);
12060
+ var ActionStepSchema = /* @__PURE__ */ AutomationActionSchema.refine((step) => step.kind !== "code", { message: "an action is interpreted, so it has no code step: a code step is bundled into the block of an automation" }).superRefine((step, ctx) => {
12061
+ for (const condition of stepConditionsOf(step)) if (hasTriggeredByLeaves(condition.when)) ctx.addIssue({
12062
+ code: "custom",
12063
+ message: TRIGGERED_BY_NEEDS_AUTOMATION,
12064
+ path: condition.path.split(".").map((part) => /^\d+$/.test(part) ? Number(part) : part)
12065
+ });
12066
+ });
12054
12067
  /**
12055
12068
  * How a trigger that arrives while the automation is busy (or cooling down) is
12056
12069
  * handled. One of the automation's execution modes, never a property of its
@@ -12258,7 +12271,7 @@ var HoldOverrideSchema = /* @__PURE__ */ z.discriminatedUnion("mode", [/* @__PUR
12258
12271
  var DEFAULT_HOLD_OVERRIDE = { mode: "respect" };
12259
12272
  /** A missed edge up to this late still runs. */
12260
12273
  var DEFAULT_MAX_LATE_MS = 10 * 6e4;
12261
- var SchedulerStepSchema = /* @__PURE__ */ ActionStepSchema.refine((step) => step.kind !== "wait" || step.seconds <= 300, {
12274
+ var SchedulerStepSchema = /* @__PURE__ */ NarrowActionStepSchema.refine((step) => step.kind !== "wait" || step.seconds <= 300, {
12262
12275
  message: `a scheduler point waits at most five minutes (300 s); put a longer wait in an action`,
12263
12276
  path: ["seconds"]
12264
12277
  });
@@ -15054,7 +15067,16 @@ var CAP_CUSTOMIZE_CATALOG = {
15054
15067
  when: "always"
15055
15068
  }]
15056
15069
  }
15057
- ]
15070
+ ],
15071
+ sourceGroups: [{
15072
+ id: "meter-device",
15073
+ targets: [
15074
+ "power",
15075
+ "energy",
15076
+ "voltage",
15077
+ "current"
15078
+ ]
15079
+ }]
15058
15080
  },
15059
15081
  "power-source": {
15060
15082
  version: 1,
@@ -17983,4 +18005,4 @@ var coreBlocksCapability = {
17983
18005
  vocabulary: { notOperatorFacing: NOT_A_DEVICE.INTERNAL }
17984
18006
  };
17985
18007
  //#endregion
17986
- export { alertsCapability as $, weekdayOfLocalDate as $t, CAP_RUNTIME_FIELD_UNITS as A, forEachLeaf as At, customKeyOfRole as B, QuantityUnitError as Bt, powerSourceCapability as C, TemplateActionValueSchema as Ct, COMPOSED_ITEM_FIXED_FIELDS as D, AutomationWhenSchema as Dt, featureForwards as E, TemplateTimeWindowValueSchema as Et, findChannelSource as F, holdOf as Ft, IrNativeCodeSchema as G, enumerateItemArrayFields as Gt, isRemoteRole as H, isQuantityValue as Ht, irSourceProblem as I, describeWantedFaults as It, TransmitSettingsSchema as J, isKnownTimeZone as Jt, IrNativeFormatSchema as K, enumerateSchemaFields as Kt, remoteSourceSteps as L, faultMatches as Lt, mediaPlayerCapability as M, isEventLeaf as Mt, REMOTE_STEP_DELAY_MAX_MS as N, compareValues as Nt, expressionContainsBuiltinCall as O, EVENT_LEAF_ID_RE as Ot, RemoteSourceSchema as P, describeHoldMs as Pt, AlertSchema as Q, siteFor as Qt, resolveRemoteSource as R, readFault as Rt, PowerSourceStateSchema as S, validateRecipeBounds as St, commandedMethods as T, TemplateEventValueSchema as Tt, isRemoteWidgetRole as U, paramMeta as Ut, isRemoteCustomKey as V, convertQuantityInput as Vt, toTimings as W, paramMetaOf as Wt, CompositionRunStatusSchema as X, nextOccurrence as Xt, CompositionBlockStateSchema as Y, localDateOf as Yt, compositionFieldKey as Z, occurrenceOn as Zt, replacedFieldKeys as _, AutomationRecipeSchema as _t, coreBlockComposition as a, VocabActionError as an, buildStepArgsTrace as at, powerSourceLinkOfComposition as b, stepConditionsOf as bt, coreBlocksCapability as c, assertDeviceOffers as cn, SchedulerConflictSchema as ct, resolveCoreBlockFiles as d, vocabCall as dn, SchedulerPreviewSchema as dt, zoneOnlySite as en, AutomationRunOutcomeSchema as et, describeComposableCaps as f, CAP_VOCABULARY_BY_NAME as fn, SchedulerSchema as ft, planComposition as g, AutomationBranchStepSchema as gt, compositionUnionReads as h, ActionStepSchema as ht, coreBlockAddonId as i, canonicalStoredStepTargets as in, appendTrace as it, MediaPlayerStatusSchema as j, hasEventLeaves as jt, CAP_CUSTOMIZE_CATALOG as k, eventLeafIdAt as kt, normalizeCoreBlockWrite as l, findVocabAction as ln, SchedulerError as lt, compositionSourceRefs as m, validateSchedulerInput as mt, CORE_BLOCK_ADDON_PREFIX as n, ACTION_TARGET_INVALIDATION_EVENTS as nn, AutomationStateDocSchema as nt, coreBlockIdFromAddonId as o, actionEffect as on, DEFAULT_HOLD_OVERRIDE as ot, buildCapabilityLookup as p, SchedulerStatusSchema as pt, IrTimingsSchema as q, unwrapSchema as qt, CoreBlockSchema as r, ActionTargetResolver as rn, EMPTY_AUTOMATION_STATE as rt, coreBlockSourceKind as s, allVocabActions as sn, LOCAL_DATE_PATTERN as st, CORE_BLOCKS_ADDON_ID as t, EventVocabularyEntrySchema as tn, AutomationRunTraceSchema as tt, resolveCoreBlockEntry as u, vocabActionIdFor as un, SchedulerInputSchema as ut, validateComposition as v, REPEAT_ITEM_VAR as vt, DEVICE_ID_FIELD as w, TemplateEntriesValueSchema as wt, PowerSourceInfoSchema as x, stepGuardOf as xt, powerSourceActuatorConflicts as y, nestedStepsOf as yt, RemoteRoleSchema as z, anySubjectMatches as zt };
18008
+ export { alertsCapability as $, siteFor as $t, CAP_RUNTIME_FIELD_UNITS as A, eventLeafIdAt as At, customKeyOfRole as B, anySubjectMatches as Bt, powerSourceCapability as C, validateRecipeBounds as Ct, COMPOSED_ITEM_FIXED_FIELDS as D, TemplateTimeWindowValueSchema as Dt, featureForwards as E, TemplateEventValueSchema as Et, findChannelSource as F, describeHoldMs as Ft, IrNativeCodeSchema as G, paramMetaOf as Gt, isRemoteRole as H, convertQuantityInput as Ht, irSourceProblem as I, holdOf as It, TransmitSettingsSchema as J, unwrapSchema as Jt, IrNativeFormatSchema as K, enumerateItemArrayFields as Kt, remoteSourceSteps as L, describeWantedFaults as Lt, mediaPlayerCapability as M, hasEventLeaves as Mt, REMOTE_STEP_DELAY_MAX_MS as N, isEventLeaf as Nt, expressionContainsBuiltinCall as O, AutomationWhenSchema as Ot, RemoteSourceSchema as P, compareValues as Pt, AlertSchema as Q, occurrenceOn as Qt, resolveRemoteSource as R, faultMatches as Rt, PowerSourceStateSchema as S, stepGuardOf as St, commandedMethods as T, TemplateEntriesValueSchema as Tt, isRemoteWidgetRole as U, isQuantityValue as Ut, isRemoteCustomKey as V, QuantityUnitError as Vt, toTimings as W, paramMeta as Wt, CompositionRunStatusSchema as X, localDateOf as Xt, CompositionBlockStateSchema as Y, isKnownTimeZone as Yt, compositionFieldKey as Z, nextOccurrence as Zt, replacedFieldKeys as _, AutomationRecipeSchema as _t, coreBlockComposition as a, canonicalStoredStepTargets as an, buildStepArgsTrace as at, powerSourceLinkOfComposition as b, nestedStepsOf as bt, coreBlocksCapability as c, allVocabActions as cn, SchedulerConflictSchema as ct, resolveCoreBlockFiles as d, vocabActionIdFor as dn, SchedulerPreviewSchema as dt, weekdayOfLocalDate as en, AutomationRunOutcomeSchema as et, describeComposableCaps as f, vocabCall as fn, SchedulerSchema as ft, planComposition as g, AutomationBranchStepSchema as gt, compositionUnionReads as h, ActionStepSchema as ht, coreBlockAddonId as i, ActionTargetResolver as in, appendTrace as it, MediaPlayerStatusSchema as j, forEachLeaf as jt, CAP_CUSTOMIZE_CATALOG as k, EVENT_LEAF_ID_RE as kt, normalizeCoreBlockWrite as l, assertDeviceOffers as ln, SchedulerError as lt, compositionSourceRefs as m, validateSchedulerInput as mt, CORE_BLOCK_ADDON_PREFIX as n, EventVocabularyEntrySchema as nn, AutomationStateDocSchema as nt, coreBlockIdFromAddonId as o, VocabActionError as on, DEFAULT_HOLD_OVERRIDE as ot, buildCapabilityLookup as p, CAP_VOCABULARY_BY_NAME as pn, SchedulerStatusSchema as pt, IrTimingsSchema as q, enumerateSchemaFields as qt, CoreBlockSchema as r, ACTION_TARGET_INVALIDATION_EVENTS as rn, EMPTY_AUTOMATION_STATE as rt, coreBlockSourceKind as s, actionEffect as sn, LOCAL_DATE_PATTERN as st, CORE_BLOCKS_ADDON_ID as t, zoneOnlySite as tn, AutomationRunTraceSchema as tt, resolveCoreBlockEntry as u, findVocabAction as un, SchedulerInputSchema as ut, validateComposition as v, HTTP_TEXT_CAP as vt, DEVICE_ID_FIELD as w, TemplateActionValueSchema as wt, PowerSourceInfoSchema as x, stepConditionsOf as xt, powerSourceActuatorConflicts as y, REPEAT_ITEM_VAR as yt, RemoteRoleSchema as z, readFault as zt };
@@ -2,14 +2,14 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_chunk = require("./chunk-Cek0wNdY.js");
3
3
  const require_base_addon = require("./base-addon-DD5dIfcZ.js");
4
4
  const require_scoped_settings = require("./scoped-settings-CylSSq_8.js");
5
- const require_rename_composition_block = require("./rename-composition-block-CcWLwVhG.js");
5
+ const require_rename_composition_block = require("./rename-composition-block-BJsL58Ih.js");
6
6
  const require_camstack_error = require("./camstack-error-DJ-TUAi1.js");
7
7
  const require_capability_definition = require("./capability-definition-HCmTem8c.js");
8
8
  const require_record_kind = require("./record-kind-DoBfYHCs.js");
9
9
  const require_wal_maintenance = require("./wal-maintenance-DyrebYKF.js");
10
10
  const require_device_certificate = require("./device-certificate-CguVACQO.js");
11
11
  const require_addon_settings_cap = require("./addon-settings.cap-DAiE0Nb0.js");
12
- const require_prefix_walk = require("./prefix-walk-DC0ljmbB.js");
12
+ const require_prefix_walk = require("./prefix-walk-BkMxoXpL.js");
13
13
  const require_network_access_cap = require("./network-access.cap-B5TWLDCC.js");
14
14
  const require_constants = require("./constants-C860Y6U4.js");
15
15
  const require_addon_id = require("./addon-id-Di0lNJ89.js");
@@ -1,14 +1,14 @@
1
1
  import { i as __require } from "./chunk-CNf5ZN-e.mjs";
2
2
  import { b as EventCategory$1, i as collectSecretMarkerRefs, p as createEvent$1 } from "./base-addon-Md14i7pe.mjs";
3
3
  import { Z as errMsg$1 } from "./scoped-settings-DVWUIP7Z.mjs";
4
- import { Un as lifecycleJobSchema, a as isCollectionArrayMethod, c as kebabToCamel$1, d as objectInputDeclaresRequiredDeviceId, dr as compareVersions, f as procedureAuthKey, fr as describeUnmet, i as isArrayOutputSchema, l as looseSchema, m as ALL_CAPABILITY_DEFINITIONS, o as isObjectInput, p as resolveMethodAuth, pr as unmetRequirements, r as extractNestedAddonId, s as isVoidInput, u as objectInputDeclaresAddonId, ur as PackageRequiresSchema } from "./rename-composition-block-7WIICIDq.mjs";
4
+ import { Un as lifecycleJobSchema, a as isCollectionArrayMethod, c as kebabToCamel$1, d as objectInputDeclaresRequiredDeviceId, dr as compareVersions, f as procedureAuthKey, fr as describeUnmet, i as isArrayOutputSchema, l as looseSchema, m as ALL_CAPABILITY_DEFINITIONS, o as isObjectInput, p as resolveMethodAuth, pr as unmetRequirements, r as extractNestedAddonId, s as isVoidInput, u as objectInputDeclaresAddonId, ur as PackageRequiresSchema } from "./rename-composition-block-OAtErZgq.mjs";
5
5
  import { t as userError } from "./camstack-error-viZYfcj9.mjs";
6
6
  import { a as expandCapMethods, n as DEVICE_STATUS_METHOD, t as DEVICE_SETTINGS_CONTRIBUTION_METHODS, u as resolveCapMount } from "./capability-definition-C2rJdVeX.mjs";
7
7
  import { s as defineRecordKinds } from "./record-kind-ub6NXqfh.mjs";
8
8
  import { D as RecordsEngine, J as asNumber, X as parseJsonObject, Y as asString$1, Z as parseJsonUnknown, l as SqliteSettingsBackend, q as asJsonObject$1 } from "./wal-maintenance-BG01rOn9.mjs";
9
9
  import { f as AppPageLangSchema } from "./device-certificate-Cddm4Idn.mjs";
10
10
  import { i as addonSettingsCapability } from "./addon-settings.cap-3-TIIMq_.mjs";
11
- import { t as loadPrefixed } from "./prefix-walk-B4b2-9aK.mjs";
11
+ import { t as loadPrefixed } from "./prefix-walk-ifwg_ukx.mjs";
12
12
  import { a as AGENT_MDNS_TXT_KEYS, i as AGENT_MDNS_SERVICE_TYPE } from "./network-access.cap-BJnGbE6n.mjs";
13
13
  import { t as RUNTIME_DEFAULTS } from "./constants-DCLpoF4L.mjs";
14
14
  import { t as bareAddonId } from "./addon-id-CVg1_r5E.mjs";
@@ -3396,6 +3396,12 @@ Object.defineProperty(exports, "NotificationFieldSchema", {
3396
3396
  return NotificationFieldSchema;
3397
3397
  }
3398
3398
  });
3399
+ Object.defineProperty(exports, "NotificationSchema", {
3400
+ enumerable: true,
3401
+ get: function() {
3402
+ return NotificationSchema;
3403
+ }
3404
+ });
3399
3405
  Object.defineProperty(exports, "TargetSchema", {
3400
3406
  enumerable: true,
3401
3407
  get: function() {
@@ -3354,4 +3354,4 @@ var notificationRulesCapability = {
3354
3354
  vocabulary: { notOperatorFacing: "notification rules — authored on their own page" }
3355
3355
  };
3356
3356
  //#endregion
3357
- export { notificationRulesCapability as a, alarmPanelCapability as c, notificationOutputCapability as d, NcTaggedRuleKindSchema as i, NotificationFieldSchema as l, NcConditionsSchema as n, AlarmPanelStatusSchema as o, NcScheduleSchema as r, AlarmStateSchema as s, NcConditionDescriptorSchema as t, TargetSchema as u };
3357
+ export { notificationRulesCapability as a, alarmPanelCapability as c, TargetSchema as d, notificationOutputCapability as f, NcTaggedRuleKindSchema as i, NotificationFieldSchema as l, NcConditionsSchema as n, AlarmPanelStatusSchema as o, NcScheduleSchema as r, AlarmStateSchema as s, NcConditionDescriptorSchema as t, NotificationSchema as u };
@@ -0,0 +1,509 @@
1
+ const require_base_addon = require("./base-addon-DD5dIfcZ.js");
2
+ const require_notification_rules_cap = require("./notification-rules.cap-BDh0LDhV.js");
3
+ const require_entry_kind = require("./entry-kind-cq90c--V.js");
4
+ let zod = require("zod");
5
+ //#region ../types/dist/esm/addon/compose-instance-kinds.mjs
6
+ /** No part holds the id a call named. */
7
+ var UnknownInstanceError = class extends Error {
8
+ instanceId;
9
+ constructor(instanceId) {
10
+ super(`Unknown instance '${instanceId}'`);
11
+ this.instanceId = instanceId;
12
+ this.name = "UnknownInstanceError";
13
+ }
14
+ };
15
+ /** A create or a form named no kind, or a kind no part serves. */
16
+ var UnknownInstanceKindError = class extends Error {
17
+ kindId;
18
+ constructor(kindId) {
19
+ super(kindId === void 0 ? "This provider has several kinds: name one" : `Unknown instance kind '${kindId}'`);
20
+ this.kindId = kindId;
21
+ this.name = "UnknownInstanceKindError";
22
+ }
23
+ };
24
+ function composeInstanceKinds(parts, base) {
25
+ const byKind = (kindId) => {
26
+ if (kindId === void 0) {
27
+ const only = parts.length === 1 ? parts[0] : void 0;
28
+ if (only === void 0) throw new UnknownInstanceKindError(void 0);
29
+ return only;
30
+ }
31
+ const part = parts.find((candidate) => candidate.kind.id === kindId);
32
+ if (part === void 0) throw new UnknownInstanceKindError(kindId);
33
+ return part;
34
+ };
35
+ /**
36
+ * Whether a part's kind offers a Test. A kind that states `canTest` is believed; one that does not
37
+ * takes what its OWN provider declares, never the composed base (a calendar or an integration
38
+ * inherited the account's `canTest: true` and offered a button nothing answered, planning#543).
39
+ */
40
+ const canTestPart = async (part) => part.kind.canTest ?? (await part.provider.describe()).canTest === true;
41
+ /**
42
+ * The part a DRAFT test runs on. A named kind is that kind; an unnamed one is the provider's only
43
+ * testable kind. Several testable kinds and none named is a typed refusal that lists them, never a throw.
44
+ */
45
+ const draftPart = async (kindId) => {
46
+ if (kindId !== void 0) return parts.find((candidate) => candidate.kind.id === kindId) ?? { error: `Unknown instance kind '${kindId}'` };
47
+ const flags = await Promise.all(parts.map(canTestPart));
48
+ const testable = parts.filter((_part, index) => flags[index] === true);
49
+ const only = testable.length === 1 ? testable[0] : parts.length === 1 ? parts[0] : void 0;
50
+ if (only !== void 0) return only;
51
+ return { error: `This provider has several kinds: name one of ${(testable.length > 0 ? testable : parts).map((part) => part.kind.id).join(", ")}` };
52
+ };
53
+ const holderOf = async (id) => {
54
+ for (const part of parts) if (await part.provider.getInstance({ id }) !== null) return part;
55
+ throw new UnknownInstanceError(id);
56
+ };
57
+ const tagged = (part, instance) => ({
58
+ ...instance,
59
+ kind: part.kind.id
60
+ });
61
+ return {
62
+ describe: async () => {
63
+ const links = (await Promise.all(parts.map(async (part) => (await part.provider.describe()).links ?? []))).flat();
64
+ return {
65
+ ...base,
66
+ kinds: await Promise.all(parts.map(async (part) => ({
67
+ ...part.kind,
68
+ canTest: await canTestPart(part)
69
+ }))),
70
+ ...links.length > 0 ? { links } : {}
71
+ };
72
+ },
73
+ instanceFormSchema: async ({ id, kind }) => {
74
+ return (id === null ? byKind(kind) : await holderOf(id)).provider.instanceFormSchema({ id });
75
+ },
76
+ listInstances: async (input) => {
77
+ return (await Promise.all(parts.map(async (part) => (await part.provider.listInstances(input)).map((instance) => tagged(part, instance))))).flat();
78
+ },
79
+ getInstance: async ({ id }) => {
80
+ for (const part of parts) {
81
+ const found = await part.provider.getInstance({ id });
82
+ if (found !== null) return tagged(part, found);
83
+ }
84
+ return null;
85
+ },
86
+ createInstance: async (input) => byKind(input.kind).provider.createInstance(input),
87
+ updateInstance: async (input) => (await holderOf(input.id)).provider.updateInstance(input),
88
+ setInstanceEnabled: async (input) => (await holderOf(input.id)).provider.setInstanceEnabled(input),
89
+ deleteInstance: async (input) => (await holderOf(input.id)).provider.deleteInstance(input),
90
+ testInstance: async (input) => {
91
+ const resolved = input.id === null ? await draftPart(input.kind) : await holderOf(input.id);
92
+ if ("error" in resolved) return {
93
+ success: false,
94
+ status: "inconclusive",
95
+ error: resolved.error
96
+ };
97
+ const test = resolved.provider.testInstance;
98
+ if (test === void 0) return {
99
+ success: false,
100
+ status: "inconclusive",
101
+ error: "This kind cannot be tested"
102
+ };
103
+ return test(input);
104
+ }
105
+ };
106
+ }
107
+ //#endregion
108
+ //#region ../types/dist/esm/addon/instances-of-cap.mjs
109
+ /**
110
+ * The kind's instances answer for `cap`: it is the kind's `functionCap`, or one the kind declares in
111
+ * `alsoServes`. The one rule a link (a picker, a resolver, a delete guard) matches a target by.
112
+ */
113
+ function kindServesCap(kind, cap) {
114
+ return kind.functionCap === cap || (kind.alsoServes ?? []).includes(cap);
115
+ }
116
+ async function instancesOfCap(source, cap, filter = {}) {
117
+ const instances = [];
118
+ const unreadable = [];
119
+ for (const addonId of await source.holders(cap)) try {
120
+ const kinds = ((await source.describe(addonId)).kinds ?? []).filter((kind) => kindServesCap(kind, cap));
121
+ if (kinds.length === 0) continue;
122
+ for (const instance of await source.listInstances(addonId)) {
123
+ const kind = kinds.find((candidate) => candidate.id === instance.kind);
124
+ if (kind === void 0) continue;
125
+ if (filter.kind !== void 0 && (kind.brokerKind ?? kind.id) !== filter.kind) continue;
126
+ instances.push({
127
+ addonId,
128
+ kind,
129
+ instance
130
+ });
131
+ }
132
+ } catch (err) {
133
+ unreadable.push({
134
+ addonId,
135
+ error: err instanceof Error ? err.message : String(err)
136
+ });
137
+ }
138
+ return {
139
+ instances,
140
+ unreadable
141
+ };
142
+ }
143
+ async function providersOf(api, name) {
144
+ const info = await api.capabilities.getCapability.query({ name });
145
+ if (info === null) throw new Error(`the capability registry did not answer for ${name}`);
146
+ return info.providers;
147
+ }
148
+ /**
149
+ * The source over `ctx.api`. Every provider of the cap is a holder, not only those that also serve
150
+ * `integration-instances`: a provider that does not (an addon older than the hub during an update)
151
+ * then fails `describe` and is reported unreadable, so its instances are retried as transient
152
+ * instead of vanishing from the catalogue and failing for good.
153
+ */
154
+ function instanceSourceOverApi(api) {
155
+ return {
156
+ holders: (cap) => providersOf(api, cap),
157
+ describe: (addonId) => api.integrationInstances.describe.query({ addonId }),
158
+ listInstances: (addonId) => api.integrationInstances.listInstances.query({ addonId })
159
+ };
160
+ }
161
+ //#endregion
162
+ //#region ../types/dist/esm/addon/notification-targets.mjs
163
+ /**
164
+ * Notification targets as instances of the function cap `notification-output` (epic #440, step 6).
165
+ *
166
+ * A notification target used to be one row of one record kind (`{ name, kind, addonId, enabled,
167
+ * config }`) with a free-form `config` blob whose secrets nobody could name. Now every target KIND
168
+ * the provider offers (ntfy, telegram, webhook, ...) is a record kind of its own whose flat body IS
169
+ * that kind's form: the adapter's `configSchema` lifted into a Zod object, a `password` field marked
170
+ * `.meta({ secret: true })` so the records door keeps it in the keychain, an `instance-select` field
171
+ * declared as a link so the hub refuses to delete what a target points at.
172
+ *
173
+ * Three providers (notifiers, Home Assistant, Alexa) serve the same shape, so the pieces are shared:
174
+ * - {@link defineNotificationTargetKind}: the record kind of one `TargetKind` descriptor;
175
+ * - {@link NotificationTargetStore}: the `Target`-shaped facade the provider's own code keeps
176
+ * using (send, the notification-center bridge), over one handle per kind;
177
+ * - {@link listNotificationTargets}: the targets as an addon on `ctx.api` reads them;
178
+ * - {@link buildNotificationTargetInstances}: the `integration-instances` provider, one kind each;
179
+ * - {@link moveTargetRows}: the D987 procedure that flattens the old `config` blobs into the bodies.
180
+ */
181
+ /** The function cap every notification target is an instance of. */
182
+ var NOTIFICATION_OUTPUT_CAP = "notification-output";
183
+ /** The most targets one provider lists (a settings page, not a table). */
184
+ var TARGETS_LIST_MAX = 1e3;
185
+ /** The record kind name of one target kind: `telegram` is stored under `notify-telegram`. */
186
+ function notificationTargetKindName(kind) {
187
+ return `notify-${kind}`;
188
+ }
189
+ /** The body schema of a target kind: the entry's name and switch plus the adapter's fields. */
190
+ var TargetBodyBaseSchema = /* @__PURE__ */ zod.z.looseObject({
191
+ name: /* @__PURE__ */ zod.z.string().min(1),
192
+ enabled: /* @__PURE__ */ zod.z.boolean().optional()
193
+ });
194
+ /** The shape of one `editable-array` row: the item fields, a `password` one a secret. */
195
+ function rowSchemaOf(itemFields) {
196
+ const shape = {};
197
+ let idKey = null;
198
+ let hasSecret = false;
199
+ for (const item of itemFields) {
200
+ if (item.type === "password") {
201
+ shape[item.key] = zod.z.string().optional().meta({ secret: true });
202
+ hasSecret = true;
203
+ continue;
204
+ }
205
+ shape[item.key] = zod.z.unknown().optional();
206
+ idKey ??= item.key;
207
+ }
208
+ return {
209
+ row: zod.z.looseObject(shape),
210
+ idKey,
211
+ hasSecret
212
+ };
213
+ }
214
+ /**
215
+ * The Zod fields of a descriptor's form. A `password` field is a secret; an `instance-select` field is
216
+ * a link to an instance of its function cap; an `editable-array` keeps its rows (a password inside a
217
+ * row is a secret matched by the row's first plain field); every other field keeps whatever the
218
+ * adapter's own parse accepts, because the form already validated its shape. The body is loose, so a key
219
+ * the schema does not know (the owner of a personal target) survives a write.
220
+ */
221
+ function fieldsOf(descriptor) {
222
+ const shape = {};
223
+ const secretArrayKeys = {};
224
+ for (const section of descriptor.configSchema.sections) for (const field of section.fields) switch (field.type) {
225
+ case "info": break;
226
+ case "password":
227
+ shape[field.key] = zod.z.string().optional().meta({ secret: true });
228
+ break;
229
+ case "instance-select":
230
+ shape[field.key] = require_base_addon.optionalLinkField({
231
+ cap: field.functionCap,
232
+ ...field.kind !== void 0 ? { kind: field.kind } : {}
233
+ });
234
+ break;
235
+ case "editable-array": {
236
+ const { row, idKey, hasSecret } = rowSchemaOf(field.itemFields);
237
+ shape[field.key] = zod.z.array(row).optional();
238
+ if (hasSecret && idKey !== null) secretArrayKeys[field.key] = idKey;
239
+ break;
240
+ }
241
+ default: shape[field.key] = zod.z.unknown().optional();
242
+ }
243
+ return {
244
+ shape,
245
+ secretArrayKeys
246
+ };
247
+ }
248
+ /** The record kind of one target kind, derived from its descriptor. */
249
+ function defineNotificationTargetKind(descriptor) {
250
+ const { shape, secretArrayKeys } = fieldsOf(descriptor);
251
+ return require_entry_kind.defineEntryKind(notificationTargetKindName(descriptor.kind), {
252
+ title: `${descriptor.label} notification targets`,
253
+ schema: TargetBodyBaseSchema.extend(shape),
254
+ writeTrigger: `an operator adds, edits, switches or removes a ${descriptor.label} notification target`,
255
+ ...Object.keys(secretArrayKeys).length > 0 ? { secretArrayKeys } : {}
256
+ });
257
+ }
258
+ /** The record kinds of a provider's descriptors, keyed by the record kind name (for `records.declare`). */
259
+ function notificationTargetKinds(descriptors) {
260
+ return Object.fromEntries(descriptors.map((descriptor) => {
261
+ const defined = defineNotificationTargetKind(descriptor);
262
+ return [defined.name, defined];
263
+ }));
264
+ }
265
+ /** The body a stored target becomes: the switch and the name, and the config fields flat beside them. */
266
+ function targetBody(target) {
267
+ return {
268
+ ...target.config,
269
+ name: target.name.length > 0 ? target.name : target.id,
270
+ enabled: target.enabled
271
+ };
272
+ }
273
+ /** The `Target` a record of a kind is; null when the row is not a target. */
274
+ function targetOfRecord(addonId, kind, id, data) {
275
+ const { name, enabled: _enabled, ...config } = data;
276
+ const parsed = require_notification_rules_cap.TargetSchema.safeParse({
277
+ id,
278
+ name,
279
+ kind,
280
+ addonId,
281
+ enabled: require_base_addon.isInstanceOn(id),
282
+ config
283
+ });
284
+ return parsed.success ? parsed.data : null;
285
+ }
286
+ function targetOfOld(addonId, row) {
287
+ return {
288
+ id: row.id,
289
+ name: row.name,
290
+ kind: row.kind,
291
+ addonId,
292
+ enabled: row.enabled,
293
+ config: { ...row.config }
294
+ };
295
+ }
296
+ /**
297
+ * The `Target`-shaped facade over one record kind per target kind. `list` returns the stored form (a
298
+ * secret is a keychain marker: every reader redacts it anyway); `getById` returns the target with its
299
+ * secrets resolved, which is what a send, a probe and an edit's secret merge need. A keychain that
300
+ * cannot answer throws: a write never goes ahead with a secret it could not read (D49).
301
+ */
302
+ var NotificationTargetStore = class NotificationTargetStore {
303
+ addonId;
304
+ handles;
305
+ options;
306
+ constructor(addonId, handles, options) {
307
+ this.addonId = addonId;
308
+ this.handles = handles;
309
+ this.options = options;
310
+ }
311
+ static of(records, addonId, kinds, descriptors, options = {}) {
312
+ const handles = [];
313
+ for (const descriptor of descriptors) {
314
+ const defined = kinds[notificationTargetKindName(descriptor.kind)];
315
+ if (defined === void 0) continue;
316
+ handles.push({
317
+ kind: descriptor.kind,
318
+ handle: records.kind(defined)
319
+ });
320
+ }
321
+ return new NotificationTargetStore(addonId, handles, options);
322
+ }
323
+ /** The record handle of each kind, for the migration ports. */
324
+ handlesByKind() {
325
+ return new Map(this.handles.map((entry) => [entry.kind, entry.handle]));
326
+ }
327
+ async list() {
328
+ const out = [];
329
+ for (const { kind, handle } of this.handles) {
330
+ const page = await handle.query({ limit: TARGETS_LIST_MAX });
331
+ for (const record of page.records) {
332
+ const target = targetOfRecord(this.addonId, kind, record.id, record.data);
333
+ if (target !== null) {
334
+ out.push(target);
335
+ continue;
336
+ }
337
+ this.options.logger?.warn("notification target record is not a valid target; left out of the list", { meta: {
338
+ targetId: record.id,
339
+ kind
340
+ } });
341
+ }
342
+ }
343
+ const held = new Set(out.map((target) => target.id));
344
+ for (const row of await this.legacyRows()) if (!held.has(row.id)) out.push(targetOfOld(this.addonId, row));
345
+ return out;
346
+ }
347
+ /** The legacy rows of a kind this provider serves (the others are not ours to show). */
348
+ async legacyRows() {
349
+ const legacy = this.options.legacy;
350
+ if (legacy === void 0) return [];
351
+ const served = new Set(this.handles.map((entry) => entry.kind));
352
+ return (await legacy.list()).filter((row) => served.has(row.kind));
353
+ }
354
+ async getById(id) {
355
+ for (const { kind, handle } of this.handles) {
356
+ const row = await handle.getResolved(id);
357
+ if (row !== null) return targetOfRecord(this.addonId, kind, row.id, row.data);
358
+ }
359
+ const old = (await this.legacyRows()).find((row) => row.id === id);
360
+ return old === void 0 ? null : targetOfOld(this.addonId, old);
361
+ }
362
+ /** Insert or replace by id; a target whose kind changed leaves the record of its old kind. */
363
+ async upsert(target) {
364
+ const own = this.handles.find((entry) => entry.kind === target.kind);
365
+ if (own === void 0) throw new Error(`invalid target '${target.id}': unknown kind '${target.kind}'`);
366
+ const { enabled: _switch, ...data } = targetBody(target);
367
+ await own.handle.put({
368
+ id: target.id,
369
+ data
370
+ });
371
+ require_base_addon.recordInstanceSwitch(target.id, target.enabled);
372
+ for (const other of this.handles) if (other !== own) await other.handle.delete(target.id);
373
+ await this.options.legacy?.delete(target.id);
374
+ }
375
+ async delete(id) {
376
+ for (const { handle } of this.handles) await handle.delete(id);
377
+ await this.options.legacy?.delete(id);
378
+ }
379
+ };
380
+ /**
381
+ * A probe's answer as the tri-state of `testInstance`: `ok` validated; a refusal that carries an HTTP
382
+ * status is the remote saying no (`rejected`); a failure with no answer at all (the network, a missing
383
+ * field) proves nothing about the credentials (`inconclusive`).
384
+ */
385
+ function probeToTestResult(probed) {
386
+ if (probed.ok) return {
387
+ success: true,
388
+ status: "validated",
389
+ ...probed.stateInstance !== void 0 ? { detail: probed.stateInstance } : {}
390
+ };
391
+ const error = probed.error ?? "the probe failed";
392
+ return {
393
+ success: false,
394
+ status: probed.httpStatus !== void 0 ? "rejected" : "inconclusive",
395
+ error
396
+ };
397
+ }
398
+ /** The form of a kind: the adapter's own sections. */
399
+ function formOf(descriptor) {
400
+ return descriptor.configSchema;
401
+ }
402
+ /** The instance kinds of a notification provider, one per target kind: a part a composition can take. */
403
+ function notificationTargetParts(records, spec) {
404
+ return spec.descriptors.flatMap((descriptor) => {
405
+ const defined = spec.kinds[notificationTargetKindName(descriptor.kind)];
406
+ if (defined === void 0) return [];
407
+ const canTest = spec.probe !== void 0 && spec.canProbe(descriptor.kind);
408
+ const kind = {
409
+ id: descriptor.kind,
410
+ label: descriptor.label,
411
+ functionCap: NOTIFICATION_OUTPUT_CAP,
412
+ role: "services",
413
+ canTest,
414
+ ...spec.widgets?.(descriptor.kind) !== void 0 ? { widgets: spec.widgets(descriptor.kind) } : {},
415
+ ...descriptor.iconUrl !== void 0 ? { iconUrl: descriptor.iconUrl } : {},
416
+ ...descriptor.iconMediaType !== void 0 ? { iconMediaType: descriptor.iconMediaType } : {}
417
+ };
418
+ return [{
419
+ kind,
420
+ provider: new require_base_addon.RecordIntegrationInstances(records, defined, {
421
+ description: {
422
+ role: "services",
423
+ instanceMode: "multiple",
424
+ kind: "target",
425
+ canTest,
426
+ kinds: [kind]
427
+ },
428
+ formSchema: () => formOf(descriptor),
429
+ initialBody: (name) => ({ name }),
430
+ mintId: () => spec.mintId(),
431
+ configured: () => true,
432
+ validateWrite: ({ body }) => spec.validate?.({
433
+ kind: descriptor.kind,
434
+ config: body
435
+ }),
436
+ test: async ({ id, values }) => {
437
+ if (spec.probe === void 0 || !canTest) return {
438
+ success: false,
439
+ status: "unsupported",
440
+ error: "This kind cannot be tested"
441
+ };
442
+ return probeToTestResult(await spec.probe({
443
+ kind: descriptor.kind,
444
+ config: values,
445
+ targetId: id ?? void 0
446
+ }));
447
+ }
448
+ }).toProvider()
449
+ }];
450
+ });
451
+ }
452
+ /** The `integration-instances` provider of a notification provider: one kind per target kind. */
453
+ function buildNotificationTargetInstances(records, spec) {
454
+ const parts = notificationTargetParts(records, spec);
455
+ return composeInstanceKinds(parts, {
456
+ role: "services",
457
+ instanceMode: "multiple",
458
+ kind: "target",
459
+ canTest: parts.some((part) => part.kind.canTest === true),
460
+ mintsId: true
461
+ });
462
+ }
463
+ /**
464
+ * Every notification target, read as the instances of `notification-output` (D1013 rule 5). A holder
465
+ * that could not answer is NAMED in `unreadable`: a caller that acts on a target's absence (drops a
466
+ * selection, refuses a send) must check it first, because a partial read is not "deleted" (D315, D49).
467
+ */
468
+ async function listNotificationTargets(api) {
469
+ const { instances, unreadable } = await instancesOfCap(instanceSourceOverApi(api), NOTIFICATION_OUTPUT_CAP);
470
+ return {
471
+ targets: instances.map(({ addonId, kind, instance }) => {
472
+ const owner = instance.formValues["ownerUserId"];
473
+ return {
474
+ id: instance.id,
475
+ name: instance.name,
476
+ kind: kind.id,
477
+ addonId,
478
+ enabled: instance.enabled !== false,
479
+ ...typeof owner === "string" && owner.length > 0 ? { ownerUserId: owner } : {}
480
+ };
481
+ }),
482
+ unreadable
483
+ };
484
+ }
485
+ //#endregion
486
+ Object.defineProperty(exports, "NotificationTargetStore", {
487
+ enumerable: true,
488
+ get: function() {
489
+ return NotificationTargetStore;
490
+ }
491
+ });
492
+ Object.defineProperty(exports, "buildNotificationTargetInstances", {
493
+ enumerable: true,
494
+ get: function() {
495
+ return buildNotificationTargetInstances;
496
+ }
497
+ });
498
+ Object.defineProperty(exports, "listNotificationTargets", {
499
+ enumerable: true,
500
+ get: function() {
501
+ return listNotificationTargets;
502
+ }
503
+ });
504
+ Object.defineProperty(exports, "notificationTargetKinds", {
505
+ enumerable: true,
506
+ get: function() {
507
+ return notificationTargetKinds;
508
+ }
509
+ });