Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Platform type support #21

Merged
merged 7 commits into from
Apr 30, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"dir": false,
"i": false,
"params": false,
"doc": false,
"props": false,
"ref": false,
"temp": false
Expand All @@ -73,6 +74,7 @@
"unicorn/no-array-for-each": "off",
"unicorn/import-style": "off",
"sort-keys-fix/sort-keys-fix": "warn",
"unicorn/consistent-function-scoping": "off",
"unicorn/prefer-event-target": "off",
"simple-import-sort/imports": "warn",
"simple-import-sort/exports": "warn",
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ apps/**/yarn.lock
# dependencies
**/node_modules
config.json
test.d.ts

# IDEs and editors
/.idea
Expand Down
18 changes: 9 additions & 9 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@
"name": "@digital-alchemy/type-writer",
"repository": "https://github.com/Digital-Alchemy-TS/type-writer",
"homepage": "https://docs.digital-alchemy.app/Type-Writer",
"version": "0.3.10",
"version": "0.3.11",
"scripts": {
"build": "rm -rf dist/; tsc",
"lint": "eslint src",
"test": "./scripts/test.sh",
"prepublishOnly": "npm run build",
"upgrade": "ncu -u; npm i"
"upgrade": "ncu -u -f '@digital-alchemy/*'; npm i"
},
"author": {
"url": "https://github.com/zoe-codez",
Expand All @@ -25,8 +25,8 @@
},
"license": "MIT",
"dependencies": {
"@digital-alchemy/core": "^0.3.11",
"@digital-alchemy/hass": "^0.3.17",
"@digital-alchemy/core": "^0.3.12",
"@digital-alchemy/hass": "^0.3.21",
"js-yaml": "^4.1.0"
},
"devDependencies": {
Expand Down
10 changes: 10 additions & 0 deletions src/build.extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,11 @@ import { existsSync, writeFileSync } from "fs";
import { join } from "path";
import { exit } from "process";

const PICK_FROM_PLATFORM = `type PICK_FROM_PLATFORM<
ID extends TPlatformId,
DOMAIN extends ALL_DOMAINS = ALL_DOMAINS,
> = Extract<REGISTRY_SETUP["platform"][\`_\${ID}\`], PICK_ENTITY<DOMAIN>>;`;

export function BuildTypes({
logger,
lifecycle,
Expand Down Expand Up @@ -53,6 +58,8 @@ export function BuildTypes({
"// Do not edit this file, it will only affect type definitions, not functional code",
`import { PICK_ENTITY } from "./helpers";`,
``,
PICK_FROM_PLATFORM,
``,
`// #MARK: ENTITY_SETUP`,
`export const ENTITY_SETUP = ${JSON.stringify(entitySetup, undefined, " ")};`,
``,
Expand Down Expand Up @@ -80,6 +87,9 @@ export function BuildTypes({
`// #MARK: TRawEntityIds`,
type_writer.identifiers.entityIds(entities),
``,
`// #MARK: TPlatformId`,
type_writer.identifiers.platforms(),
``,
`// #MARK: TRawDomains`,
type_writer.identifiers.domains(entities),
].join(`\n`);
Expand Down
134 changes: 134 additions & 0 deletions src/entity-reference.extension.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
/* eslint-disable unicorn/consistent-function-scoping */
import { FIRST, is, TServiceParams } from "@digital-alchemy/core";
import {
ALL_DOMAINS,
ServiceListSelector,
ServiceListServiceTarget,
TPlatformId,
} from "@digital-alchemy/hass";
import { dump } from "js-yaml";
import { addSyntheticLeadingComment, factory, SyntaxKind } from "typescript";

// * asdf
type TargetReference = {
domain?: ALL_DOMAINS[];
platform?: TPlatformId;
};

export function EntityReference({ logger }: TServiceParams) {
function buildTargetReference(data: TargetReference) {
if (!is.empty(data.platform)) {
if (!is.empty(data.domain)) {
// * PICK_FROM_PLATFORM<"platform", ..."domain"> | PICK_FROM_PLATFORM<"platform", ..."domain">[]
return factory.createParenthesizedType(
factory.createUnionTypeNode([
factory.createTypeReferenceNode(factory.createIdentifier("PICK_FROM_PLATFORM"), [
factory.createLiteralTypeNode(factory.createStringLiteral(data.platform)),
...data.domain.map(domain =>
factory.createLiteralTypeNode(factory.createStringLiteral(domain)),
),
]),
factory.createArrayTypeNode(
factory.createTypeReferenceNode(factory.createIdentifier("PICK_FROM_PLATFORM"), [
factory.createLiteralTypeNode(factory.createStringLiteral(data.platform)),
...data.domain.map(domain =>
factory.createLiteralTypeNode(factory.createStringLiteral(domain)),
),
]),
),
]),
);
}
// * PICK_FROM_PLATFORM<"platform"> | PICK_FROM_PLATFORM<"platform">[]
return factory.createParenthesizedType(
factory.createUnionTypeNode([
factory.createTypeReferenceNode(factory.createIdentifier("PICK_FROM_PLATFORM"), [
factory.createLiteralTypeNode(factory.createStringLiteral(data.platform)),
]),
factory.createArrayTypeNode(
factory.createTypeReferenceNode(factory.createIdentifier("PICK_FROM_PLATFORM"), [
factory.createLiteralTypeNode(factory.createStringLiteral(data.platform)),
]),
),
]),
);
}
// * PICK_ENTITY<..."domain"> | PICK_ENTITY<..."domain">[]
return factory.createParenthesizedType(
factory.createUnionTypeNode([
factory.createTypeReferenceNode(
factory.createIdentifier("PICK_ENTITY"),
data?.domain?.map(domain =>
factory.createLiteralTypeNode(factory.createStringLiteral(domain)),
),
),
factory.createArrayTypeNode(
factory.createTypeReferenceNode(
factory.createIdentifier("PICK_ENTITY"),
data?.domain?.map(domain =>
factory.createLiteralTypeNode(factory.createStringLiteral(domain)),
),
),
),
]),
);
}

// #MARK: buildEntityReference
function buildEntityReference(selector: ServiceListSelector) {
const entity = selector.entity;
return buildTargetReference({
domain: is.empty(entity?.domain) ? [] : [entity.domain],
platform: entity?.integration,
});
}

// #MARK: generateEntityList
function generateEntityList(target: ServiceListServiceTarget) {
return buildTargetReference({
domain: target?.entity?.[FIRST]?.domain,
platform: target?.entity?.[FIRST]?.integration,
});
}
// #MARK: createTarget
function createTarget(target: ServiceListServiceTarget) {
if (is.empty(target)) {
return undefined;
}
if (target.entity) {
const property = factory.createPropertySignature(
undefined,
factory.createIdentifier("entity_id"),
undefined,
generateEntityList(target),
);
return addSyntheticLeadingComment(
property,
SyntaxKind.MultiLineCommentTrivia,
"*\n" +
[
"Assisted definition",
"> ```yaml",
...dump(target)
.trim()
.split("\n")
.map(i => `> ${i}`),
]
.map(i => ` * ${i}`)
.join(`\n`) +
"\n * > ```\n ",
true,
);
}
if (target.integration) {
return undefined;
}
if (target.device) {
return undefined;
}
logger.error({ target }, `createTarget doesn't know what to do with target`);
return undefined;
}

return { buildEntityReference, createTarget };
}
93 changes: 93 additions & 0 deletions src/field-builder.extension.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { is, TServiceParams } from "@digital-alchemy/core";
import { ServiceListFieldDescription } from "@digital-alchemy/hass";
import { factory, SyntaxKind, TypeNode } from "typescript";

export function FieldBuilder({ type_writer }: TServiceParams) {
// #MARK: handleSelectors
function handleSelectors(
serviceDomain: string,
serviceName: string,
{ selector }: ServiceListFieldDescription,
) {
if ("object" in selector && selector.object === null) {
// if (serviceDomain === "conversation") {
// console.log({ serviceDomain, serviceName }, selector, options);
// }
return factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
}

return factory.createUnionTypeNode([
serviceDomain === "scene" && serviceName === "apply"
? factory.createTypeReferenceNode(factory.createIdentifier("Partial"), [
factory.createTypeReferenceNode(factory.createIdentifier("Record"), [
factory.createTypeReferenceNode(factory.createIdentifier("PICK_ENTITY"), undefined),
factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword),
]),
])
: factory.createTypeReferenceNode(factory.createIdentifier("Record"), [
factory.createKeywordTypeNode(SyntaxKind.StringKeyword),
factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword),
]),
factory.createParenthesizedType(
factory.createArrayTypeNode(factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword)),
),
]);
}

// #MARK: fieldPropertySignature
function fieldPropertySignature(
parameterName: string,
{ selector, ...details }: ServiceListFieldDescription,
serviceDomain: string,
serviceName: string,
) {
let node: TypeNode;
// : boolean
if (!is.undefined(selector?.boolean))
node = factory.createKeywordTypeNode(SyntaxKind.BooleanKeyword);
// : number
else if (!is.undefined(selector?.number))
node = factory.createKeywordTypeNode(SyntaxKind.NumberKeyword);
// : string
else if (!is.undefined(selector?.text) || !is.undefined(selector?.time))
node = factory.createKeywordTypeNode(SyntaxKind.StringKeyword);
// string | `domain.${keyof typeof ENTITY_SETUP.domain}`
else if (!is.undefined(selector?.entity))
// some combination of: PICK_ENTITY | PICK_ENTITY[] | PICK_ENTITY<"domain"> | PICK_ENTITY<"domain">[]
node = type_writer.entity.buildEntityReference(selector);
// : "option" | "option" | "option" | "option"
else if (!is.undefined(selector?.select))
node = factory.createUnionTypeNode(
selector?.select.options.map((i: string | Record<"label" | "value", string>) =>
factory.createLiteralTypeNode(factory.createStringLiteral(is.string(i) ? i : i.value)),
),
);
// : Record<string, unknown> | (unknown[]);
else if (is.undefined(selector?.object)) {
node = factory.createKeywordTypeNode(SyntaxKind.UnknownKeyword);
}
// else if (!is.undefined(selector?.))
// : unknown
else {
node = handleSelectors(serviceDomain, serviceName, {
selector,
...details,
});
}

return type_writer.tsdoc.parameterComment(
factory.createPropertySignature(
undefined,
factory.createIdentifier(parameterName),
details.required ? undefined : factory.createToken(SyntaxKind.QuestionToken),
node,
),
parameterName,
{ selector, ...details },
);
}

return {
fieldPropertySignature,
};
}
Loading
Loading