@camstack/develop 0.1.50 → 0.1.52
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/CHANGELOG.md +12 -0
- package/dist/hub-discovery/hub-candidates.d.ts +3 -0
- package/dist/hub-discovery/hub-candidates.d.ts.map +1 -1
- package/dist/hub-discovery/hub-candidates.js +5 -0
- package/dist/hub-discovery/mdns-browse.d.ts +2 -0
- package/dist/hub-discovery/mdns-browse.d.ts.map +1 -1
- package/dist/hub-discovery/mdns-browse.js +6 -1
- package/dist/scaffold/integration-device.d.ts +1 -1
- package/dist/scaffold/integration-device.d.ts.map +1 -1
- package/dist/scaffold/integration-device.js +2 -0
- package/dist/scaffold/integration-exporter.d.ts +1 -1
- package/dist/scaffold/integration-exporter.d.ts.map +1 -1
- package/dist/scaffold/integration-exporter.js +2 -0
- package/dist/scaffold/integration-service.d.ts +1 -1
- package/dist/scaffold/integration-service.d.ts.map +1 -1
- package/dist/scaffold/integration-service.js +2 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [0.1.52] - 2026-11-10
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Hub discovery reads the hub id a hub announces on the LAN
|
|
15
|
+
|
|
16
|
+
## [0.1.51] - 2026-11-08
|
|
17
|
+
|
|
18
|
+
### Changed
|
|
19
|
+
|
|
20
|
+
- The addon scaffolds for an integration, a service and an exporter now declare their instance kind, so a generated addon loads
|
|
21
|
+
|
|
10
22
|
## [0.1.50] - 2026-11-08
|
|
11
23
|
|
|
12
24
|
### Changed
|
|
@@ -15,6 +15,8 @@ export interface HubCandidate {
|
|
|
15
15
|
readonly host: string;
|
|
16
16
|
readonly port: number;
|
|
17
17
|
readonly nodeId: string | null;
|
|
18
|
+
/** The hub's announced identity (#494); absent when no source named one. */
|
|
19
|
+
readonly hubId?: string;
|
|
18
20
|
readonly version: string | null;
|
|
19
21
|
/** Human labels: "LAN (mDNS)", "saved session admin", "CAMSTACK_HUB_URL"… */
|
|
20
22
|
readonly sources: readonly string[];
|
|
@@ -24,6 +26,7 @@ export interface RawCandidate {
|
|
|
24
26
|
readonly url: string;
|
|
25
27
|
readonly source: string;
|
|
26
28
|
readonly nodeId?: string | null;
|
|
29
|
+
readonly hubId?: string;
|
|
27
30
|
readonly version?: string | null;
|
|
28
31
|
}
|
|
29
32
|
export interface DiscoverHubsDeps {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hub-candidates.d.ts","sourceRoot":"","sources":["../../src/hub-discovery/hub-candidates.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,KAAK,aAAa,EAAkB,KAAK,OAAO,EAAE,MAAM,kBAAkB,CAAA;AAKnF,eAAO,MAAM,iBAAiB,eAAe,CAAA;AAE7C,qDAAqD;AACrD,MAAM,WAAW,YAAY;IAC3B,oDAAoD;IACpD,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAA;IAC9B,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAA;IAC/B,6EAA6E;IAC7E,QAAQ,CAAC,OAAO,EAAE,SAAS,MAAM,EAAE,CAAA;CACpC;AAED,oDAAoD;AACpD,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;IACpB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAAA;IAC/B,QAAQ,CAAC,OAAO,CAAC,EAAE,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B,GAAG,OAAO,CAAC,SAAS,YAAY,EAAE,CAAC,CAoBhG;AAED;;;;GAIG;AACH,wBAAsB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAwB7E"}
|
|
@@ -31,6 +31,9 @@ export function normalizeHubUrl(value) {
|
|
|
31
31
|
const shown = host.includes(':') ? `[${host}]` : host;
|
|
32
32
|
return { url: `https://${shown}:${port}`, host, port };
|
|
33
33
|
}
|
|
34
|
+
function hubIdField(hubId) {
|
|
35
|
+
return hubId !== undefined ? { hubId } : {};
|
|
36
|
+
}
|
|
34
37
|
/** Merge raw candidates by host:port, keeping every source and any identity. */
|
|
35
38
|
export function mergeCandidates(raw) {
|
|
36
39
|
const merged = new Map();
|
|
@@ -45,6 +48,7 @@ export function mergeCandidates(raw) {
|
|
|
45
48
|
host: n.host,
|
|
46
49
|
port: n.port,
|
|
47
50
|
nodeId: prev?.nodeId ?? r.nodeId ?? null,
|
|
51
|
+
...hubIdField(prev?.hubId ?? r.hubId),
|
|
48
52
|
version: prev?.version ?? r.version ?? null,
|
|
49
53
|
sources: prev?.sources.includes(r.source)
|
|
50
54
|
? prev.sources
|
|
@@ -66,6 +70,7 @@ export async function discoverHubs(deps = {}) {
|
|
|
66
70
|
url: h.url,
|
|
67
71
|
source: MDNS_SOURCE_LABEL,
|
|
68
72
|
nodeId: h.nodeId,
|
|
73
|
+
...hubIdField(h.hubId),
|
|
69
74
|
version: h.version,
|
|
70
75
|
})),
|
|
71
76
|
...(deps.known ?? []),
|
|
@@ -33,6 +33,8 @@ export interface MdnsHub {
|
|
|
33
33
|
/** Base https URL, no trailing slash. */
|
|
34
34
|
readonly url: string;
|
|
35
35
|
readonly nodeId: string | null;
|
|
36
|
+
/** The hub's announced identity (`hub-<16 hex>`, #494); absent when it announces none. */
|
|
37
|
+
readonly hubId?: string;
|
|
36
38
|
readonly version: string | null;
|
|
37
39
|
}
|
|
38
40
|
export interface B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AAC1F,wBAAsB,cAAc,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,SAAS,OAAO,EAAE,CAAC,CAyBxF"}
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* for that service — it never reads the mesh multicast channel (D826 retired
|
|
5
5
|
* it on the hub, so it can only ever show pre-D826 hubs).
|
|
6
6
|
*/
|
|
7
|
-
import { HUB_MDNS_QUERY_NAME, HUB_MDNS_ROLE, HUB_MDNS_TXT_KEYS } from '@camstack/types';
|
|
7
|
+
import { HUB_MDNS_QUERY_NAME, HUB_MDNS_ROLE, HUB_MDNS_TXT_KEYS, isHubId } from '@camstack/types';
|
|
8
8
|
import makeMdns from 'multicast-dns';
|
|
9
9
|
export function createRealMdnsSocket() {
|
|
10
10
|
const socket = makeMdns();
|
|
@@ -54,6 +54,10 @@ function originOf(value) {
|
|
|
54
54
|
return null;
|
|
55
55
|
}
|
|
56
56
|
}
|
|
57
|
+
/** `{ hubId }` when the TXT names a real hub id, else nothing (a forged `hub` is dropped). */
|
|
58
|
+
function hubIdOf(value) {
|
|
59
|
+
return isHubId(value) ? { hubId: value } : {};
|
|
60
|
+
}
|
|
57
61
|
/** Fold the responses into hubs. Pure, so it is tested without sockets. */
|
|
58
62
|
export function hubsFromResponses(responses) {
|
|
59
63
|
const found = new Map();
|
|
@@ -78,6 +82,7 @@ export function hubsFromResponses(responses) {
|
|
|
78
82
|
found.set(url, {
|
|
79
83
|
url,
|
|
80
84
|
nodeId: txt.get(HUB_MDNS_TXT_KEYS.nodeId) ?? null,
|
|
85
|
+
...hubIdOf(txt.get(HUB_MDNS_TXT_KEYS.hubId)),
|
|
81
86
|
version: txt.get(HUB_MDNS_TXT_KEYS.version) ?? null,
|
|
82
87
|
});
|
|
83
88
|
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* is a typed instance record (connection + secret + test) and which brings devices. The
|
|
4
4
|
* integration's Gateway device is a SIBLING of the devices it brings, never their parent.
|
|
5
5
|
*/
|
|
6
|
-
export declare const DEVICE_INSTANCES_TS = "/**\n * <%= displayName %> integrations as `integration-instances` (D1007): one `connections` record per\n * integration, keyed by the registry id, holding the connection to ONE <%= displayName %> system. The\n * token is a secret by TYPE; the records door keeps it in the keychain. The Gateway device is not\n * part of the record: it is a device OF the integration, adopted from it.\n */\nimport {\n type ConfigUISchema,\n defineEntryKind,\n entryBody,\n type IntegrationTestConnectionResult,\n RecordIntegrationInstances,\n type RecordsAccess,\n} from '@camstack/types'\nimport { z } from 'zod'\n\nexport const <%= className %>ConnectionsKind = defineEntryKind('connections', {\n title: '<%= displayName %> integrations',\n schema: entryBody({\n host: z.string().optional(),\n token: z.string().optional().meta({ secret: true }),\n }),\n writeTrigger: 'an operator adds, edits or removes a <%= displayName %> integration',\n})\nexport type <%= className %>ConnectionBody = z.infer<typeof <%= className %>ConnectionsKind.schema>\n\n/** Every record kind this addon declares, keyed by its name. */\nexport const <%= className %>RecordKinds = { connections: <%= className %>ConnectionsKind } as const\n\nexport function build<%= className %>ConnectionForm(): ConfigUISchema {\n return {\n sections: [\n {\n id: 'connection',\n title: 'Connection',\n columns: 1,\n fields: [\n { type: 'text', key: 'name', label: 'Name' },\n { type: 'text', key: 'host', label: 'Host' },\n { type: 'password', key: 'token', label: 'Token', showToggle: true },\n ],\n },\n ],\n }\n}\n\nexport interface <%= className %>InstanceDeps {\n /** Re-apply the runtime from the records after a create, update, enable or delete. */\n readonly onChanged: () => Promise<void>\n /** Probe the remote with the (possibly unsaved) values; a failed probe is not a pass. */\n readonly probe: (values: Readonly<Record<string, unknown>>) => Promise<IntegrationTestConnectionResult>\n}\n\nexport function build<%= className %>Instances(\n records: Pick<RecordsAccess, 'kind' | 'owner'>,\n deps: <%= className %>InstanceDeps,\n): RecordIntegrationInstances<<%= className %>ConnectionBody> {\n return new RecordIntegrationInstances<<%= className %>ConnectionBody>(\n records,\n <%= className %>ConnectionsKind,\n {\n description: {\n role: 'devices',\n discovery: { mode: 'account', scopedToInstance: true },\n instanceMode: 'multiple',\n kind: 'server',\n canTest: true,\n },\n formSchema: () => build<%= className %>ConnectionForm(),\n initialBody: (name): <%= className %>ConnectionBody => ({ name }),\n configured: (body) => (body.host ?? '').length > 0,\n onChanged: () => deps.onChanged(),\n test: ({ values }) => deps.probe(values),\n },\n )\n}\n";
|
|
6
|
+
export declare const DEVICE_INSTANCES_TS = "/**\n * <%= displayName %> integrations as `integration-instances` (D1007): one `connections` record per\n * integration, keyed by the registry id, holding the connection to ONE <%= displayName %> system. The\n * token is a secret by TYPE; the records door keeps it in the keychain. The Gateway device is not\n * part of the record: it is a device OF the integration, adopted from it.\n */\nimport {\n type ConfigUISchema,\n defineEntryKind,\n entryBody,\n type IntegrationTestConnectionResult,\n RecordIntegrationInstances,\n type RecordsAccess,\n} from '@camstack/types'\nimport { z } from 'zod'\n\nexport const <%= className %>ConnectionsKind = defineEntryKind('connections', {\n title: '<%= displayName %> integrations',\n schema: entryBody({\n host: z.string().optional(),\n token: z.string().optional().meta({ secret: true }),\n }),\n writeTrigger: 'an operator adds, edits or removes a <%= displayName %> integration',\n})\nexport type <%= className %>ConnectionBody = z.infer<typeof <%= className %>ConnectionsKind.schema>\n\n/** Every record kind this addon declares, keyed by its name. */\nexport const <%= className %>RecordKinds = { connections: <%= className %>ConnectionsKind } as const\n\nexport function build<%= className %>ConnectionForm(): ConfigUISchema {\n return {\n sections: [\n {\n id: 'connection',\n title: 'Connection',\n columns: 1,\n fields: [\n { type: 'text', key: 'name', label: 'Name' },\n { type: 'text', key: 'host', label: 'Host' },\n { type: 'password', key: 'token', label: 'Token', showToggle: true },\n ],\n },\n ],\n }\n}\n\nexport interface <%= className %>InstanceDeps {\n /** Re-apply the runtime from the records after a create, update, enable or delete. */\n readonly onChanged: () => Promise<void>\n /** Probe the remote with the (possibly unsaved) values; a failed probe is not a pass. */\n readonly probe: (values: Readonly<Record<string, unknown>>) => Promise<IntegrationTestConnectionResult>\n}\n\nexport function build<%= className %>Instances(\n records: Pick<RecordsAccess, 'kind' | 'owner'>,\n deps: <%= className %>InstanceDeps,\n): RecordIntegrationInstances<<%= className %>ConnectionBody> {\n return new RecordIntegrationInstances<<%= className %>ConnectionBody>(\n records,\n <%= className %>ConnectionsKind,\n {\n description: {\n role: 'devices',\n discovery: { mode: 'account', scopedToInstance: true },\n instanceMode: 'multiple',\n kind: 'server',\n canTest: true,\n // The one kind this provider serves; its functionCap is the cap an instance of it feeds.\n kinds: [{ id: 'server', label: '<%= displayName %>', functionCap: 'device-provider', role: 'devices' }],\n },\n formSchema: () => build<%= className %>ConnectionForm(),\n initialBody: (name): <%= className %>ConnectionBody => ({ name }),\n configured: (body) => (body.host ?? '').length > 0,\n onChanged: () => deps.onChanged(),\n test: ({ values }) => deps.probe(values),\n },\n )\n}\n";
|
|
7
7
|
export declare const DEVICE_DEVICES_TS = "/**\n * The devices of an integration. Every one carries its `integrationId` in its persisted config, so\n * a cascade can find what an integration owns. The Gateway is the integration's own presence in the\n * device list and a SIBLING of the sensors: nothing is its child.\n *\n * Per-device configuration lives ONLY in `ctx.settings.*DeviceStore`, never in a field of the\n * addon's own storage (D865).\n */\nimport { BaseDevice, type DeviceContext, type DeviceFeature, DeviceType } from '@camstack/types'\nimport { z } from 'zod'\n\nexport const <%= className %>_SYSTEM = '<%= fileName %>'\nexport const <%= className %>_GATEWAY_ID = 'gateway'\n\nexport const <%= className %>GatewaySchema = z.object({\n equipment: z.literal(<%= className %>_GATEWAY_ID),\n integrationId: z.string().min(1).describe('Owning integration'),\n system: z.literal(<%= className %>_SYSTEM).optional(),\n})\n\nexport class <%= className %>GatewayDevice extends BaseDevice<typeof <%= className %>GatewaySchema> {\n readonly features: readonly DeviceFeature[] = []\n\n constructor(ctx: DeviceContext) {\n <%= className %>GatewaySchema.parse(ctx.persistedConfig ?? {})\n super(ctx, <%= className %>GatewaySchema, { type: DeviceType.Gateway })\n }\n}\n\nexport const <%= className %>SensorSchema = z.object({\n equipment: z.string().min(1).describe('Remote id of the sensor'),\n integrationId: z.string().min(1).describe('Owning integration'),\n system: z.literal(<%= className %>_SYSTEM).optional(),\n})\n\nexport class <%= className %>SensorDevice extends BaseDevice<typeof <%= className %>SensorSchema> {\n readonly features: readonly DeviceFeature[] = []\n\n constructor(ctx: DeviceContext) {\n <%= className %>SensorSchema.parse(ctx.persistedConfig ?? {})\n super(ctx, <%= className %>SensorSchema, { type: DeviceType.Sensor })\n }\n}\n";
|
|
8
8
|
export declare const DEVICE_ADOPTION_TS = "/**\n * Discovery and adoption for <%= displayName %>. The Gateway and every sensor are offered as\n * SIBLING candidates (the Gateway is never the parent of the sensors); adopting one creates a\n * top-level device carrying the integration id. Replace `discover` with a real read of the remote.\n */\nimport {\n DeviceType,\n type DiscoveredChildDevice,\n errMsg,\n type IDeviceAdoptionProvider,\n type IScopedLogger,\n} from '@camstack/types'\nimport { <%= className %>_GATEWAY_ID } from './<%= fileName %>-devices.js'\n\nexport interface RemoteSensor {\n readonly id: string\n readonly name: string\n}\n\nexport interface <%= className %>AdoptionDeps {\n readonly hasIntegration: (integrationId: string) => Promise<boolean>\n readonly listIntegrations: () => Promise<readonly string[]>\n /** What the remote reports for the integration, or null while it is unreachable. */\n readonly discover: (integrationId: string) => Promise<readonly RemoteSensor[] | null>\n /** Remote ids of the devices already adopted for the integration, with their device id. */\n readonly adopted: (integrationId: string) => Promise<ReadonlyMap<string, number>>\n readonly create: (input: {\n readonly integrationId: string\n readonly equipment: string\n readonly type: DeviceType.Gateway | DeviceType.Sensor\n readonly name: string\n }) => Promise<number>\n readonly remove: (deviceId: number) => Promise<void>\n readonly logger: IScopedLogger\n}\n\nexport function build<%= className %>AdoptionProvider(\n deps: <%= className %>AdoptionDeps,\n): IDeviceAdoptionProvider {\n async function candidates(integrationId: string): Promise<readonly DiscoveredChildDevice[]> {\n const sensors = await deps.discover(integrationId)\n const adopted = await deps.adopted(integrationId)\n const offered: DiscoveredChildDevice[] = [\n {\n childNativeId: <%= className %>_GATEWAY_ID,\n name: '<%= displayName %>',\n type: DeviceType.Gateway,\n status: sensors === null ? 'offline' : 'online',\n metadata: {},\n alreadyAdopted: adopted.has(<%= className %>_GATEWAY_ID),\n adoptedDeviceId: adopted.get(<%= className %>_GATEWAY_ID) ?? null,\n capabilities: [],\n },\n ]\n for (const sensor of sensors ?? []) {\n offered.push({\n childNativeId: sensor.id,\n name: sensor.name,\n type: DeviceType.Sensor,\n status: 'online',\n metadata: {},\n alreadyAdopted: adopted.has(sensor.id),\n adoptedDeviceId: adopted.get(sensor.id) ?? null,\n capabilities: [],\n })\n }\n return offered\n }\n\n async function status(integrationId: string) {\n const all = await candidates(integrationId)\n return {\n lastDiscoveryAt: Date.now(),\n candidateCount: all.length,\n adoptedCount: all.filter((c) => c.alreadyAdopted).length,\n lastError: null,\n }\n }\n\n return {\n listCandidateFilters: async () => ({\n filters: [{ id: 'devices', label: 'Devices', isDefault: true }],\n }),\n listCandidates: async ({ integrationId, page, pageSize }) => {\n const all = await candidates(integrationId)\n const start = (page - 1) * pageSize\n return {\n candidates: all.slice(start, start + pageSize),\n totalCount: all.length,\n page,\n pageSize,\n }\n },\n getCandidate: async ({ integrationId, childNativeId }) =>\n (await candidates(integrationId)).find((c) => c.childNativeId === childNativeId) ?? null,\n getStatus: async () => {\n try {\n let candidateCount = 0\n let adoptedCount = 0\n for (const integrationId of await deps.listIntegrations()) {\n const s = await status(integrationId)\n candidateCount += s.candidateCount\n adoptedCount += s.adoptedCount\n }\n return { lastDiscoveryAt: Date.now(), candidateCount, adoptedCount, lastError: null }\n } catch (err: unknown) {\n return { lastDiscoveryAt: null, candidateCount: 0, adoptedCount: 0, lastError: errMsg(err) }\n }\n },\n refresh: async ({ integrationId }) => status(integrationId),\n adopt: async ({ integrationId, childNativeIds, perCandidate }) => {\n if (!(await deps.hasIntegration(integrationId))) {\n throw new Error('<%= fileName %> adopt: integration ' + integrationId + ' not found')\n }\n const offered = await candidates(integrationId)\n const adopted: Array<{\n readonly childNativeId: string\n readonly parentDeviceId: number\n readonly accessoryDeviceIds: readonly number[]\n }> = []\n for (const childNativeId of childNativeIds) {\n const candidate = offered.find((c) => c.childNativeId === childNativeId)\n if (candidate === undefined) {\n deps.logger.warn('<%= fileName %> adopt: the remote reports nothing for this id', {\n meta: { childNativeId, integrationId },\n })\n continue\n }\n const deviceId = await deps.create({\n integrationId,\n equipment: childNativeId,\n type: candidate.type === DeviceType.Gateway ? DeviceType.Gateway : DeviceType.Sensor,\n name: perCandidate?.[childNativeId]?.name ?? candidate.name,\n })\n adopted.push({ childNativeId, parentDeviceId: deviceId, accessoryDeviceIds: [] })\n }\n if (adopted.length === 0) throw new Error('<%= fileName %> adopt: nothing was adopted')\n return { adopted }\n },\n release: async ({ camDeviceId }) => {\n await deps.remove(camDeviceId)\n },\n resync: async () => ({ changed: false, rebuiltChildren: 0 }),\n }\n}\n";
|
|
9
9
|
export declare const DEVICE_ADDON_TS = "/**\n * <%= displayName %> \u2014 a device integration (role `devices`, D996). An integration is one typed\n * connection record (secret + test) served through `integration-instances`; the devices it brings\n * are adopted from it and carry its `integrationId`. There is no addon-level settings page and no\n * legacy settings row: if the operator can configure it, it is an instance.\n *\n * Deleting a device is learned through `device-removal-hook` (a tombstone, D865), never from the\n * device missing from a list. A failed read of the remote changes nothing (D49).\n */\nimport {\n type AddonInitResult,\n BaseDeviceProvider,\n type ConfigUISchema,\n type CreateDeviceSpec,\n type DeviceConstructor,\n DeviceType,\n deviceAdoptionCapability,\n deviceRemovalHookCapability,\n type IDevice,\n type IntegrationTestConnectionResult,\n integrationInstancesCapability,\n type RecordIntegrationInstances,\n} from '@camstack/types'\nimport { build<%= className %>AdoptionProvider } from './<%= fileName %>-adoption.js'\nimport {\n <%= className %>_SYSTEM,\n <%= className %>GatewayDevice,\n <%= className %>SensorDevice,\n} from './<%= fileName %>-devices.js'\nimport {\n build<%= className %>Instances,\n <%= className %>RecordKinds,\n type <%= className %>ConnectionBody,\n} from './<%= fileName %>-instances.js'\n\nexport class <%= className %>Addon extends BaseDeviceProvider {\n protected readonly addonId = '<%= fileName %>'\n protected readonly providerName = '<%= displayName %>'\n // The Gateway and the sensors are siblings: both are restored as top-level devices.\n protected readonly deviceClasses: Partial<Record<DeviceType, DeviceConstructor<IDevice>>> = {\n [DeviceType.Gateway]: <%= className %>GatewayDevice,\n [DeviceType.Sensor]: <%= className %>SensorDevice,\n }\n\n constructor() {\n super({})\n }\n\n protected override async onInitialize(): Promise<AddonInitResult> {\n const regs = this.providerRegistrationsFromSuper(await super.onInitialize())\n const records = this.ctx.records\n if (records === undefined) {\n throw new Error('<%= fileName %>: ctx.records is required (hub-only addon)')\n }\n await records.declare(<%= className %>RecordKinds)\n const instances = build<%= className %>Instances(records, {\n onChanged: async () => {\n this.ctx.logger.info('<%= displayName %> integrations changed')\n },\n probe: (values) => this.probe(values),\n })\n return {\n providers: [\n ...regs,\n { capability: deviceAdoptionCapability, provider: this.buildAdoptionProvider(instances) },\n { capability: integrationInstancesCapability, provider: instances.toProvider() },\n {\n capability: deviceRemovalHookCapability,\n // Device DATA only (footage, history, rows). Settings are cleared centrally. Idempotent.\n provider: {\n onDeviceRemoved: async () => ({ counts: {} }),\n listDeviceData: async () => [],\n },\n },\n ],\n }\n }\n\n /** Replace with a real call to the remote; `rejected` is a definite no, `inconclusive` is \"could not tell\". */\n private async probe(\n values: Readonly<Record<string, unknown>>,\n ): Promise<IntegrationTestConnectionResult> {\n const host = values['host']\n if (typeof host !== 'string' || host.length === 0) {\n return { success: false, status: 'rejected', error: 'Host is required' }\n }\n return { success: true, status: 'validated' }\n }\n\n private buildAdoptionProvider(\n instances: RecordIntegrationInstances<<%= className %>ConnectionBody>,\n ) {\n return build<%= className %>AdoptionProvider({\n hasIntegration: async (integrationId) => (await instances.readResolved(integrationId)) !== null,\n listIntegrations: async () => (await instances.listResolved()).map((read) => read.id),\n discover: async (integrationId) => {\n const read = await instances.readResolved(integrationId)\n if (read === null) return null\n // Replace with a real read of the remote using read.body (host, token).\n return []\n },\n adopted: async (integrationId) => {\n const reg = this.ctx.kernel.deviceRegistry\n const devices = this.ctx.kernel.devices\n const out = new Map<string, number>()\n if (!reg || !devices) return out\n for (const d of reg.getAllForAddon(this.addonId)) {\n const config = await devices.loadConfig(d.id).catch((): Record<string, unknown> => ({}))\n if (config['integrationId'] !== integrationId) continue\n const equipment = config['equipment']\n if (typeof equipment === 'string') out.set(equipment, d.id)\n }\n return out\n },\n create: async ({ integrationId, equipment, type, name }) => {\n const devices = this.ctx.kernel.devices\n if (!devices) throw new Error('<%= fileName %> adopt: kernel.devices unavailable')\n const config = { equipment, integrationId, system: <%= className %>_SYSTEM }\n const stableId = this.generateStableId(type, config)\n const meta = { type, name, integrationId }\n const device =\n type === DeviceType.Gateway\n ? await devices.create(stableId, <%= className %>GatewayDevice, config, null, meta)\n : await devices.create(stableId, <%= className %>SensorDevice, config, null, meta)\n return device.id\n },\n remove: async (id) => {\n await this.ctx.kernel.devices?.remove(id)\n },\n logger: this.ctx.logger,\n })\n }\n\n protected override generateStableId(\n _type: DeviceType,\n config?: Record<string, unknown>,\n ): string {\n const integrationId = config?.['integrationId']\n const equipment = config?.['equipment']\n if (typeof integrationId !== 'string' || integrationId.length === 0) {\n throw new Error('<%= fileName %> generateStableId: integrationId required')\n }\n if (typeof equipment !== 'string' || equipment.length === 0) {\n throw new Error('<%= fileName %> generateStableId: equipment required')\n }\n return '<%= fileName %>:' + integrationId + ':' + equipment\n }\n\n override async supportsManualCreation(): Promise<boolean> {\n return false\n }\n\n protected async onGetCreationSchema(_type: DeviceType): Promise<ConfigUISchema | null> {\n return null\n }\n\n protected async onCreateDevice(\n _type: DeviceType,\n _config: Record<string, unknown>,\n ): Promise<CreateDeviceSpec> {\n throw new Error('<%= displayName %> devices are adopted from the integration')\n }\n}\n\nexport default <%= className %>Addon\n";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration-device.d.ts","sourceRoot":"","sources":["../../src/scaffold/integration-device.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,eAAO,MAAM,mBAAmB,
|
|
1
|
+
{"version":3,"file":"integration-device.d.ts","sourceRoot":"","sources":["../../src/scaffold/integration-device.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,eAAO,MAAM,mBAAmB,4iGA8E/B,CAAA;AAED,eAAO,MAAM,iBAAiB,wzDA2C7B,CAAA;AAED,eAAO,MAAM,kBAAkB,ikLAiJ9B,CAAA;AAED,eAAO,MAAM,eAAe,miNAqK3B,CAAA"}
|
|
@@ -70,6 +70,8 @@ export function build<%= className %>Instances(
|
|
|
70
70
|
instanceMode: 'multiple',
|
|
71
71
|
kind: 'server',
|
|
72
72
|
canTest: true,
|
|
73
|
+
// The one kind this provider serves; its functionCap is the cap an instance of it feeds.
|
|
74
|
+
kinds: [{ id: 'server', label: '<%= displayName %>', functionCap: 'device-provider', role: 'devices' }],
|
|
73
75
|
},
|
|
74
76
|
formSchema: () => build<%= className %>ConnectionForm(),
|
|
75
77
|
initialBody: (name): <%= className %>ConnectionBody => ({ name }),
|
|
@@ -4,6 +4,6 @@
|
|
|
4
4
|
* and what is exposed is keyed by that instance id. A target's actions are \`addon-action-button\`
|
|
5
5
|
* fields of its own form. Pattern: the Home Assistant export targets.
|
|
6
6
|
*/
|
|
7
|
-
export declare const EXPORTER_INSTANCES_TS = "/**\n * <%= displayName %> export targets as `integration-instances` (D1009): one `targets` record per\n * target, with a MINTED id (`<%= fileName %>_001`, ...). The devices exported to a target are the\n * `devices` list of ITS record, so deleting the target deletes the exposure and two targets never\n * share one.\n */\nimport {\n type ConfigUISchema,\n defineEntryKind,\n entryBody,\n type IntegrationTestConnectionResult,\n RecordIntegrationInstances,\n type RecordsAccess,\n isInstanceEnabled,\n} from '@camstack/types'\nimport { z } from 'zod'\n\nexport const <%= className %>_TARGET_KIND = '<%= fileName %>-target'\nexport const <%= className %>_ID_PREFIX = '<%= fileName %>_'\n\nexport const <%= className %>TargetsKind = defineEntryKind('targets', {\n title: '<%= displayName %> export targets',\n schema: entryBody({\n endpoint: z.string().optional(),\n token: z.string().optional().meta({ secret: true }),\n devices: z.array(z.string()).optional(),\n /** The target's own switch (D996). Absent means on. */\n enabled: z.boolean().optional(),\n }),\n writeTrigger: 'an operator adds, edits, switches or deletes a target, or exports a device to it',\n})\nexport type <%= className %>TargetBody = z.infer<typeof <%= className %>TargetsKind.schema>\n\n/** Every record kind this addon declares, keyed by its name. */\nexport const <%= className %>RecordKinds = { targets: <%= className %>TargetsKind } as const\n\n/** The next free minted id given the ids that exist (`<%= fileName %>_001`, `<%= fileName %>_002`, ...). */\nexport function next<%= className %>TargetId(existing: Iterable<string>): string {\n let highest = 0\n for (const id of existing) {\n if (!id.startsWith(<%= className %>_ID_PREFIX)) continue\n const n = Number(id.slice(<%= className %>_ID_PREFIX.length))\n if (Number.isInteger(n) && n > highest) highest = n\n }\n return <%= className %>_ID_PREFIX + String(highest + 1).padStart(3, '0')\n}\n\nexport function build<%= className %>TargetForm(addonId: string): ConfigUISchema {\n return {\n sections: [\n {\n id: 'target',\n title: 'Target',\n columns: 1,\n fields: [\n { type: 'text', key: 'name', label: 'Name' },\n { type: 'text', key: 'endpoint', label: 'Endpoint' },\n { type: 'password', key: 'token', label: 'Token', showToggle: true },\n {\n type: 'addon-action-button',\n addonId,\n key: '__resync',\n label: 'Re-announce',\n buttonLabel: 'Push every exposed device now',\n action: 'resync',\n paramsFromForm: { endpoint: 'endpoint' },\n },\n ],\n },\n ],\n }\n}\n\nexport interface <%= className %>TargetDeps {\n /** The ids of the targets that exist now; read per call, a minted id never reuses one. */\n readonly ids: () => readonly string[]\n /** Runs after every change; reload the exposure from the records. */\n readonly onChanged: (id: string) => Promise<void>\n readonly probe: (values: Readonly<Record<string, unknown>>) => Promise<IntegrationTestConnectionResult>\n}\n\nexport function open<%= className %>Targets(\n records: Pick<RecordsAccess, 'kind' | 'owner'>,\n deps: <%= className %>TargetDeps,\n): RecordIntegrationInstances<<%= className %>TargetBody> {\n return new RecordIntegrationInstances<<%= className %>TargetBody>(\n records,\n <%= className %>TargetsKind,\n {\n description: {\n role: 'services',\n instanceMode: 'multiple',\n kind: 'target',\n canTest: true,\n },\n formSchema: () => build<%= className %>TargetForm('<%= fileName %>'),\n initialBody: (name): <%= className %>TargetBody => ({ name, devices: [] }),\n mintId: () => next<%= className %>TargetId(deps.ids()),\n kindOf: () => <%= className %>_TARGET_KIND,\n // A target without an endpoint is unconfigured: it pushes nothing and KEEPS its devices.\n configured: (body) => (body.endpoint ?? '').length > 0,\n onChanged: (id) => deps.onChanged(id),\n test: ({ values }) => deps.probe(values),\n },\n )\n}\n";
|
|
7
|
+
export declare const EXPORTER_INSTANCES_TS = "/**\n * <%= displayName %> export targets as `integration-instances` (D1009): one `targets` record per\n * target, with a MINTED id (`<%= fileName %>_001`, ...). The devices exported to a target are the\n * `devices` list of ITS record, so deleting the target deletes the exposure and two targets never\n * share one.\n */\nimport {\n type ConfigUISchema,\n defineEntryKind,\n entryBody,\n type IntegrationTestConnectionResult,\n RecordIntegrationInstances,\n type RecordsAccess,\n isInstanceEnabled,\n} from '@camstack/types'\nimport { z } from 'zod'\n\nexport const <%= className %>_TARGET_KIND = '<%= fileName %>-target'\nexport const <%= className %>_ID_PREFIX = '<%= fileName %>_'\n\nexport const <%= className %>TargetsKind = defineEntryKind('targets', {\n title: '<%= displayName %> export targets',\n schema: entryBody({\n endpoint: z.string().optional(),\n token: z.string().optional().meta({ secret: true }),\n devices: z.array(z.string()).optional(),\n /** The target's own switch (D996). Absent means on. */\n enabled: z.boolean().optional(),\n }),\n writeTrigger: 'an operator adds, edits, switches or deletes a target, or exports a device to it',\n})\nexport type <%= className %>TargetBody = z.infer<typeof <%= className %>TargetsKind.schema>\n\n/** Every record kind this addon declares, keyed by its name. */\nexport const <%= className %>RecordKinds = { targets: <%= className %>TargetsKind } as const\n\n/** The next free minted id given the ids that exist (`<%= fileName %>_001`, `<%= fileName %>_002`, ...). */\nexport function next<%= className %>TargetId(existing: Iterable<string>): string {\n let highest = 0\n for (const id of existing) {\n if (!id.startsWith(<%= className %>_ID_PREFIX)) continue\n const n = Number(id.slice(<%= className %>_ID_PREFIX.length))\n if (Number.isInteger(n) && n > highest) highest = n\n }\n return <%= className %>_ID_PREFIX + String(highest + 1).padStart(3, '0')\n}\n\nexport function build<%= className %>TargetForm(addonId: string): ConfigUISchema {\n return {\n sections: [\n {\n id: 'target',\n title: 'Target',\n columns: 1,\n fields: [\n { type: 'text', key: 'name', label: 'Name' },\n { type: 'text', key: 'endpoint', label: 'Endpoint' },\n { type: 'password', key: 'token', label: 'Token', showToggle: true },\n {\n type: 'addon-action-button',\n addonId,\n key: '__resync',\n label: 'Re-announce',\n buttonLabel: 'Push every exposed device now',\n action: 'resync',\n paramsFromForm: { endpoint: 'endpoint' },\n },\n ],\n },\n ],\n }\n}\n\nexport interface <%= className %>TargetDeps {\n /** The ids of the targets that exist now; read per call, a minted id never reuses one. */\n readonly ids: () => readonly string[]\n /** Runs after every change; reload the exposure from the records. */\n readonly onChanged: (id: string) => Promise<void>\n readonly probe: (values: Readonly<Record<string, unknown>>) => Promise<IntegrationTestConnectionResult>\n}\n\nexport function open<%= className %>Targets(\n records: Pick<RecordsAccess, 'kind' | 'owner'>,\n deps: <%= className %>TargetDeps,\n): RecordIntegrationInstances<<%= className %>TargetBody> {\n return new RecordIntegrationInstances<<%= className %>TargetBody>(\n records,\n <%= className %>TargetsKind,\n {\n description: {\n role: 'services',\n instanceMode: 'multiple',\n kind: 'target',\n canTest: true,\n // The one kind this provider serves; kindOf below stamps it on every instance.\n kinds: [{ id: <%= className %>_TARGET_KIND, label: '<%= displayName %>', functionCap: 'device-export', role: 'services' }],\n },\n formSchema: () => build<%= className %>TargetForm('<%= fileName %>'),\n initialBody: (name): <%= className %>TargetBody => ({ name, devices: [] }),\n mintId: () => next<%= className %>TargetId(deps.ids()),\n kindOf: () => <%= className %>_TARGET_KIND,\n // A target without an endpoint is unconfigured: it pushes nothing and KEEPS its devices.\n configured: (body) => (body.endpoint ?? '').length > 0,\n onChanged: (id) => deps.onChanged(id),\n test: ({ values }) => deps.probe(values),\n },\n )\n}\n";
|
|
8
8
|
export declare const EXPORTER_ADDON_TS = "/**\n * <%= displayName %> - an exporter (`device-export` + `integration-instances`, D1009). Every\n * exporter is multi-instance: each target is an instance with a minted id, and a membership change\n * ALWAYS names the target it changes. Exposure is the `devices` list of the target's record, keyed\n * by the instance id; an id this addon does not serve is refused by name, never answered empty.\n */\nimport {\n type AddonInitResult,\n BaseAddon,\n customAction,\n defineCustomActions,\n deviceExportCapability,\n deviceExportStatusInstanceOf,\n ExportInstanceUnknownError,\n type IDeviceExportProvider,\n type IntegrationTestConnectionResult,\n integrationInstancesCapability,\n type RecordKindHandle,\n} from '@camstack/types'\nimport { z } from 'zod'\nimport {\n open<%= className %>Targets,\n <%= className %>_TARGET_KIND,\n <%= className %>RecordKinds,\n <%= className %>TargetsKind,\n type <%= className %>TargetBody,\n} from './<%= fileName %>-instances.js'\n\nconst <%= className %>Actions = defineCustomActions({\n resync: customAction(\n z.object({ endpoint: z.string().optional() }),\n z.object({ summary: z.string() }),\n { kind: 'mutation', auth: 'admin' },\n ),\n})\n\n/** The device kinds this exporter can carry; the device picker filters on it. */\nconst SUPPORTED_DEVICE_KINDS: readonly string[] = ['sensor', 'switch', 'light']\n\nexport class <%= className %>Addon extends BaseAddon<Readonly<Record<string, never>>> {\n private targets: RecordKindHandle<<%= className %>TargetBody> | null = null\n /** Target id to its record body; reloaded from the records after every change. */\n private book = new Map<string, <%= className %>TargetBody>()\n\n constructor() {\n super({})\n }\n\n protected override async onInitialize(): Promise<AddonInitResult> {\n const records = this.ctx.records\n if (records === undefined) {\n throw new Error('<%= fileName %>: ctx.records is required (hub-only addon)')\n }\n await records.declare(<%= className %>RecordKinds)\n this.targets = records.kind(<%= className %>TargetsKind)\n const instances = open<%= className %>Targets(records, {\n ids: () => [...this.book.keys()],\n onChanged: () => this.reload(),\n probe: (values) => this.probe(values),\n })\n await this.reload()\n return {\n providers: [\n { capability: deviceExportCapability, provider: this.buildExportProvider() },\n { capability: integrationInstancesCapability, provider: instances.toProvider() },\n ],\n customActions: <%= className %>Actions,\n actionHandlers: {\n resync: async () => {\n await this.reload()\n return { summary: 'Re-announced ' + this.book.size + ' target(s).' }\n },\n },\n }\n }\n\n /** Reload every target from the records; the synchronous read the event path needs. */\n private async reload(): Promise<void> {\n const targets = this.targets\n if (targets === null) return\n const page = await targets.query({ limit: 1000 })\n this.book = new Map(page.records.map((row) => [row.id, row.data]))\n }\n\n /** The body of a target this addon serves, or the named refusal. */\n private target(instanceId: string): <%= className %>TargetBody {\n const body = this.book.get(instanceId)\n if (body === undefined) throw new ExportInstanceUnknownError(this.ctx.id, instanceId)\n return body\n }\n\n private async setMembership(\n instanceId: string,\n deviceId: string,\n exposed: boolean,\n ): Promise<void> {\n const body = this.target(instanceId)\n const current = new Set(body.devices ?? [])\n if (exposed) current.add(deviceId)\n else current.delete(deviceId)\n await this.targets?.patch(instanceId, { devices: [...current] })\n await this.reload()\n }\n\n private buildExportProvider(): IDeviceExportProvider {\n return {\n getStatus: async (input) => {\n const instanceId = deviceExportStatusInstanceOf(input)\n const bodies =\n instanceId === undefined ? [...this.book.values()] : [this.target(instanceId)]\n return {\n linkState: bodies.some((b) => (b.endpoint ?? '').length > 0) ? 'linked' : 'unlinked',\n exposedDeviceCount: new Set(bodies.flatMap((b) => b.devices ?? [])).size,\n }\n },\n listInstances: async () =>\n [...this.book.entries()].map(([instanceId, body]) => ({\n instanceId,\n name: body.name,\n enabled: isInstanceEnabled(body),\n kind: <%= className %>_TARGET_KIND,\n })),\n listSupportedDeviceKinds: async ({ instanceId }) => {\n if (instanceId !== undefined) this.target(instanceId)\n return [...SUPPORTED_DEVICE_KINDS]\n },\n listExposedDevices: async ({ instanceId }) => {\n const bodies =\n instanceId === undefined ? [...this.book.values()] : [this.target(instanceId)]\n return bodies.flatMap((b) => (b.devices ?? []).map((deviceId) => ({ deviceId })))\n },\n exposeDevice: async ({ instanceId, deviceId }) =>\n this.setMembership(instanceId, deviceId, true),\n unexposeDevice: async ({ instanceId, deviceId }) =>\n this.setMembership(instanceId, deviceId, false),\n }\n }\n\n /** Replace with a real call to the remote; `rejected` is a definite no, `inconclusive` is \"could not tell\". */\n private async probe(\n values: Readonly<Record<string, unknown>>,\n ): Promise<IntegrationTestConnectionResult> {\n const endpoint = values['endpoint']\n if (typeof endpoint !== 'string' || endpoint.length === 0) {\n return { success: false, status: 'rejected', error: 'Endpoint is required' }\n }\n return { success: true, status: 'validated' }\n }\n}\n\nexport default <%= className %>Addon\n";
|
|
9
9
|
//# sourceMappingURL=integration-exporter.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration-exporter.d.ts","sourceRoot":"","sources":["../../src/scaffold/integration-exporter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAO,MAAM,qBAAqB,
|
|
1
|
+
{"version":3,"file":"integration-exporter.d.ts","sourceRoot":"","sources":["../../src/scaffold/integration-exporter.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,eAAO,MAAM,qBAAqB,wxIA4GjC,CAAA;AAED,eAAO,MAAM,iBAAiB,mrLAuJ7B,CAAA"}
|
|
@@ -98,6 +98,8 @@ export function open<%= className %>Targets(
|
|
|
98
98
|
instanceMode: 'multiple',
|
|
99
99
|
kind: 'target',
|
|
100
100
|
canTest: true,
|
|
101
|
+
// The one kind this provider serves; kindOf below stamps it on every instance.
|
|
102
|
+
kinds: [{ id: <%= className %>_TARGET_KIND, label: '<%= displayName %>', functionCap: 'device-export', role: 'services' }],
|
|
101
103
|
},
|
|
102
104
|
formSchema: () => build<%= className %>TargetForm('<%= fileName %>'),
|
|
103
105
|
initialBody: (name): <%= className %>TargetBody => ({ name, devices: [] }),
|
|
@@ -2,6 +2,6 @@
|
|
|
2
2
|
* Templates of the `service-integration` scaffold (D1007, D996): an addon whose integration is a
|
|
3
3
|
* typed connection plus a secret, with a test, and no devices of its own (role `services`).
|
|
4
4
|
*/
|
|
5
|
-
export declare const SERVICE_INSTANCES_TS = "/**\n * <%= displayName %> integrations as `integration-instances` (D1007): one `connections` record per\n * integration, keyed by the registry id. The API key is a secret by TYPE (`.meta({ secret: true })`),\n * so the records door keeps it in the keychain and deleting the row deletes the secret.\n * There is no addon-level settings page: everything an operator configures is an instance.\n */\nimport {\n type ConfigUISchema,\n defineEntryKind,\n entryBody,\n type IntegrationTestConnectionResult,\n RecordIntegrationInstances,\n type RecordsAccess,\n} from '@camstack/types'\nimport { z } from 'zod'\n\nexport const <%= className %>ConnectionsKind = defineEntryKind('connections', {\n title: '<%= displayName %> integrations',\n schema: entryBody({\n baseUrl: z.string().optional(),\n apiKey: z.string().optional().meta({ secret: true }),\n }),\n writeTrigger: 'an operator adds, edits or removes a <%= displayName %> integration',\n})\nexport type <%= className %>ConnectionBody = z.infer<typeof <%= className %>ConnectionsKind.schema>\n\n/** Every record kind this addon declares, keyed by its name. */\nexport const <%= className %>RecordKinds = { connections: <%= className %>ConnectionsKind } as const\n\nexport function build<%= className %>ConnectionForm(): ConfigUISchema {\n return {\n sections: [\n {\n id: 'connection',\n title: 'Connection',\n columns: 1,\n fields: [\n { type: 'text', key: 'name', label: 'Name' },\n { type: 'text', key: 'baseUrl', label: 'Base URL' },\n { type: 'password', key: 'apiKey', label: 'API key', showToggle: true },\n ],\n },\n ],\n }\n}\n\nexport interface <%= className %>InstanceDeps {\n /** Re-apply the runtime from the records after a create, update, enable or delete. */\n readonly onChanged: () => Promise<void>\n /** Probe the remote with the (possibly unsaved) values; a failed probe is not a pass. */\n readonly probe: (values: Readonly<Record<string, unknown>>) => Promise<IntegrationTestConnectionResult>\n}\n\nexport function build<%= className %>Instances(\n records: Pick<RecordsAccess, 'kind' | 'owner'>,\n deps: <%= className %>InstanceDeps,\n): RecordIntegrationInstances<<%= className %>ConnectionBody> {\n return new RecordIntegrationInstances<<%= className %>ConnectionBody>(\n records,\n <%= className %>ConnectionsKind,\n {\n description: {\n role: 'services',\n instanceMode: 'multiple',\n kind: 'server',\n canTest: true,\n },\n formSchema: () => build<%= className %>ConnectionForm(),\n initialBody: (name): <%= className %>ConnectionBody => ({ name }),\n configured: (body) => (body.baseUrl ?? '').length > 0,\n onChanged: () => deps.onChanged(),\n test: ({ values }) => deps.probe(values),\n },\n )\n}\n";
|
|
5
|
+
export declare const SERVICE_INSTANCES_TS = "/**\n * <%= displayName %> integrations as `integration-instances` (D1007): one `connections` record per\n * integration, keyed by the registry id. The API key is a secret by TYPE (`.meta({ secret: true })`),\n * so the records door keeps it in the keychain and deleting the row deletes the secret.\n * There is no addon-level settings page: everything an operator configures is an instance.\n */\nimport {\n type ConfigUISchema,\n defineEntryKind,\n entryBody,\n type IntegrationTestConnectionResult,\n RecordIntegrationInstances,\n type RecordsAccess,\n} from '@camstack/types'\nimport { z } from 'zod'\n\nexport const <%= className %>ConnectionsKind = defineEntryKind('connections', {\n title: '<%= displayName %> integrations',\n schema: entryBody({\n baseUrl: z.string().optional(),\n apiKey: z.string().optional().meta({ secret: true }),\n }),\n writeTrigger: 'an operator adds, edits or removes a <%= displayName %> integration',\n})\nexport type <%= className %>ConnectionBody = z.infer<typeof <%= className %>ConnectionsKind.schema>\n\n/** Every record kind this addon declares, keyed by its name. */\nexport const <%= className %>RecordKinds = { connections: <%= className %>ConnectionsKind } as const\n\nexport function build<%= className %>ConnectionForm(): ConfigUISchema {\n return {\n sections: [\n {\n id: 'connection',\n title: 'Connection',\n columns: 1,\n fields: [\n { type: 'text', key: 'name', label: 'Name' },\n { type: 'text', key: 'baseUrl', label: 'Base URL' },\n { type: 'password', key: 'apiKey', label: 'API key', showToggle: true },\n ],\n },\n ],\n }\n}\n\nexport interface <%= className %>InstanceDeps {\n /** Re-apply the runtime from the records after a create, update, enable or delete. */\n readonly onChanged: () => Promise<void>\n /** Probe the remote with the (possibly unsaved) values; a failed probe is not a pass. */\n readonly probe: (values: Readonly<Record<string, unknown>>) => Promise<IntegrationTestConnectionResult>\n}\n\nexport function build<%= className %>Instances(\n records: Pick<RecordsAccess, 'kind' | 'owner'>,\n deps: <%= className %>InstanceDeps,\n): RecordIntegrationInstances<<%= className %>ConnectionBody> {\n return new RecordIntegrationInstances<<%= className %>ConnectionBody>(\n records,\n <%= className %>ConnectionsKind,\n {\n description: {\n role: 'services',\n instanceMode: 'multiple',\n kind: 'server',\n canTest: true,\n // The one kind this provider serves; its functionCap is the cap an instance of it feeds.\n kinds: [{ id: 'server', label: '<%= displayName %>', functionCap: 'integration-instances', role: 'services' }],\n },\n formSchema: () => build<%= className %>ConnectionForm(),\n initialBody: (name): <%= className %>ConnectionBody => ({ name }),\n configured: (body) => (body.baseUrl ?? '').length > 0,\n onChanged: () => deps.onChanged(),\n test: ({ values }) => deps.probe(values),\n },\n )\n}\n";
|
|
6
6
|
export declare const SERVICE_ADDON_TS = "/**\n * <%= displayName %> \u2014 a service integration (role `services`, D996). It brings no devices: an\n * integration is one typed connection record, listed on the Integrations page, with a secret and a\n * Test button. Read the connection per use with `instances.readResolved(id)`; never keep a second\n * copy of it.\n */\nimport {\n type AddonInitResult,\n BaseAddon,\n errMsg,\n type IntegrationTestConnectionResult,\n integrationInstancesCapability,\n type RecordIntegrationInstances,\n} from '@camstack/types'\nimport {\n build<%= className %>Instances,\n <%= className %>RecordKinds,\n type <%= className %>ConnectionBody,\n} from './<%= fileName %>-instances.js'\n\nexport class <%= className %>Addon extends BaseAddon<Readonly<Record<string, never>>> {\n private instances: RecordIntegrationInstances<<%= className %>ConnectionBody> | null = null\n\n constructor() {\n super({})\n }\n\n protected override async onInitialize(): Promise<AddonInitResult> {\n const records = this.ctx.records\n if (records === undefined) {\n throw new Error('<%= fileName %>: ctx.records is required (hub-only addon)')\n }\n await records.declare(<%= className %>RecordKinds)\n const instances = build<%= className %>Instances(records, {\n onChanged: () => this.applyInstances(),\n probe: (values) => this.probe(values),\n })\n this.instances = instances\n await this.applyInstances()\n return {\n providers: [\n { capability: integrationInstancesCapability, provider: instances.toProvider() },\n ],\n }\n }\n\n /** Re-apply the runtime from the records; called at boot and after every instance change. */\n private async applyInstances(): Promise<void> {\n const all = (await this.instances?.listResolved()) ?? []\n this.ctx.logger.info('<%= displayName %> integrations applied', {\n meta: { count: all.length },\n })\n }\n\n /** Replace with a real call to the remote; `rejected` is a definite no, `inconclusive` is \"could not tell\". */\n private async probe(\n values: Readonly<Record<string, unknown>>,\n ): Promise<IntegrationTestConnectionResult> {\n const baseUrl = values['baseUrl']\n if (typeof baseUrl !== 'string' || baseUrl.length === 0) {\n return { success: false, status: 'rejected', error: 'Base URL is required' }\n }\n try {\n new URL(baseUrl)\n return { success: true, status: 'validated' }\n } catch (err: unknown) {\n return { success: false, status: 'rejected', error: errMsg(err) }\n }\n }\n}\n\nexport default <%= className %>Addon\n";
|
|
7
7
|
//# sourceMappingURL=integration-service.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"integration-service.d.ts","sourceRoot":"","sources":["../../src/scaffold/integration-service.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,eAAO,MAAM,oBAAoB
|
|
1
|
+
{"version":3,"file":"integration-service.d.ts","sourceRoot":"","sources":["../../src/scaffold/integration-service.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,eAAO,MAAM,oBAAoB,2gGA6EhC,CAAA;AAED,eAAO,MAAM,gBAAgB,uiFAwE5B,CAAA"}
|
|
@@ -68,6 +68,8 @@ export function build<%= className %>Instances(
|
|
|
68
68
|
instanceMode: 'multiple',
|
|
69
69
|
kind: 'server',
|
|
70
70
|
canTest: true,
|
|
71
|
+
// The one kind this provider serves; its functionCap is the cap an instance of it feeds.
|
|
72
|
+
kinds: [{ id: 'server', label: '<%= displayName %>', functionCap: 'integration-instances', role: 'services' }],
|
|
71
73
|
},
|
|
72
74
|
formSchema: () => build<%= className %>ConnectionForm(),
|
|
73
75
|
initialBody: (name): <%= className %>ConnectionBody => ({ name }),
|
package/package.json
CHANGED