Fresh start (#110)

* Fresh start

* Create an xml include plugin (#111)

* Restructure and add testing (#114)

* rooibos setup

* Restructure and add testing

* docs

* Restore manifestpipi

* Description in tools

* A bit of docs

* Auto bind feature (#115)

* Auto bind feature

* Fix children merge

* bs plugin fix

* Feature/app controller (#120)

* Initial layout

* Restructuring and plugin work

* A couple of tweaks in binding stuff

* tweaks

* basic stack

* Add basic app controller

* Support json5/yaml in playlet config files (#123)

* Support json5 in playlet config files

* Add yaml to the mix

* Delete old lib project

* plugin fix

* plugin tweak

* verbose logging

* Revert "verbose logging"

This reverts commit 25867f4226703d83102519a0d48d1cc46a9876de.

* One idea to fix the include plugin

* Fix instability in plugins

* Feature/navbar (#126)

* Navbar

* typo

* comment

* Single content node, and tests

* Remove unused field

* tweaks

* update dependencies command

* tweak formatting

* Add web app screen

* Set id in created screens

* Search screen

* Tests

* Show playlists and channels in search results

* Move screen stuff to app controller

* Home screen (wip)

* Add preferences node

* README.md copyedits (#130)

* README.md: Fix typos

* README.md: Standardize capitalization and punctuation

* Update docs/README.md

---------

Co-authored-by: Brahim Hadriche <brahim.hadriche@gmail.com>

* Web server: round 1 (#131)

* web server object

* Logging

* Web server round 1

* Lint fix

* Small tweaks

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>

* Logging to file

* Leftover

* Add logs file to web server

* Fix for timeout

* Disable keepalive connection

* add openapi spec file

* Lint fix

* add prefs version in api

* Add ecp api definition

* Lint fix

* Settings rework (#135)

* Settings rework

* Standard OnFocusChange event

* Video player stuff (#136)

* Video player stuff

* Restructure things so that focus is better handled

* Lint fix

---------

Co-authored-by: github-action linter <githubaction@githubaction.com>

* Exit dialog

* A bunch of changes

* New http client

* Set TODO priorities

* picture in picture

* mark video watched

* Video player stuff mostly there

* update spec file

* Sponsorblock

* FuncName

* SponsorBlock notifications

* Lint fix

* misc

* remove basic auth feature flag (until we start using it)

* Play queue part 1

* type fix

* handle unicode in request body

* SponsorBlock chapter label

* modal base

* remove a hack

* Invidious settings

* web server reduce timeout

* Test for captions

* Lint fix

* remove rpc stuff

* small change

* Solve focus management

* a couple of fixes

* Remove a bunch of todos

* feed error handling wip

* Lint fix

* navigation in instance settings

* home screen pagination support

* Refactor feed to support pagination on search page

* cell loading animation

* Tweak caching

* delete test screen

* playlist support part 1

* Basic playlist view

* Restore playlist/channel handler

* Refactor some content node stuff, and add an auth popup dialog

* A bad implementation of a playqueue

* Lint fix

* playlist cast fix

* Feature/web app catch up (#139)

* playlist cast fix

* Move things around

* support playlists in web app

* update api

* Bump deps

* Downgrade todo

---------

Co-authored-by: Bryce Harrington <bryce@bryceharrington.org>
Co-authored-by: github-action linter <githubaction@githubaction.com>
This commit is contained in:
authored and GitHub committed 2023-09-07 17:18:25 -04:00
1 parent 79f74141c5
commit 43166fb43b
349 files changed
+12784 -7660

No files matched your search

@@ -0,0 +1,41 @@
// https://github.com/georgejecook/rooibos/blob/c7d900deed69d109c9bf6a82ff15c190c22fb81c/bsc-plugin/src/lib/rooibos/RawCodeStatement.ts
import type {
BscFile,
WalkOptions,
WalkVisitor
} from 'brighterscript';
import {
Range,
Statement
} from 'brighterscript';
import { SourceNode } from 'source-map';
import type { BrsTranspileState } from 'brighterscript/dist/parser/BrsTranspileState';
export class RawCodeStatement extends Statement {
constructor(
public source: string,
public sourceFile?: BscFile,
public range: Range = Range.create(1, 1, 1, 99999)
) {
super();
}
public transpile(state: BrsTranspileState) {
//indent every line with the current transpile indent level (except the first line, because that's pre-indented by bsc)
let source = this.source.replace(/\r?\n/g, (match, newline) => {
return state.newline + state.indent();
});
return [new SourceNode(
this.range.start.line + 1,
this.range.start.character,
this.sourceFile ? this.sourceFile.pathAbsolute : state.srcPath,
source
)];
}
public walk(visitor: WalkVisitor, options: WalkOptions) {
//nothing to walk
}
}
+19 -1
View File
@@ -1,3 +1,5 @@
// This plugin generates a task component for each function annotated with @asynctask
import {
CompilerPlugin,
BscFile,
@@ -17,7 +19,7 @@ declare type FunctionInFile = {
}
export class AsyncTaskPlugin implements CompilerPlugin {
public name = 'asyncTaskPlugin';
public name = 'AsyncTaskPlugin';
private asyncTaskFunctions: FunctionInFile[] = []
private duplicatesReporeted: FunctionInFile[] = []
@@ -157,9 +159,15 @@ export class AsyncTaskPlugin implements CompilerPlugin {
generateBsTask(functionName: string, hasInput: boolean, file: BscFile): string {
return `
import "pkg:/${file.pkgPath}"
import "pkg:/source/utils/ErrorUtils.bs"
function Init()
m.top.functionName = "TaskMain"
m.top.cancellation = {
node: m.top,
field: "cancel",
value: true
}
end function
function TaskMain()
@@ -167,11 +175,19 @@ function TaskMain()
result = ${functionName}(${(hasInput ? "m.top.input" : "")})
m.top.setField("output", {
success: true,
task: m.top,
cancelled: m.top.cancel,
result: result
})
catch e
#if DEBUG
print "ERROR in ${functionName}: "
print ErrorUtils.Format(e)
#end if
m.top.setField("output", {
success: false,
task: m.top,
cancelled: m.top.cancel,
error: e
})
end try
@@ -187,6 +203,8 @@ end function
<interface>
<field id="input" type="assocarray" />
<field id="output" type="assocarray" />
<field id="cancel" type="boolean" alwaysNotify="true" />
<field id="cancellation" type="assocarray" />
</interface>
<script type="text/brightscript" uri="pkg:/${bsFile}" />
</component>`
+202
View File
@@ -0,0 +1,202 @@
// Plugin to generate node bindings for AutoBind components
import {
BeforeFileTranspileEvent,
BscFile,
CompilerPlugin,
XmlFile,
isBrsFile,
isXmlFile,
isXmlScope,
util
} from "brighterscript";
import path from "path";
import { SGNode, SGScript } from "brighterscript/dist/parser/SGTypes";
import { RawCodeStatement } from "./Classes/RawCodeStatement";
const bindings_function_name = 'InitializeBindings';
const bindings_script_template = `
' This method is auto-generated!
@oninit(-1)
function ${bindings_function_name}()
throw "This method was not populated by the BindingsPlugin!"
end function
`;
type ChildProps = {
[key: string]: { [key: string]: string }
}
type Bindings = {
isAutoBindComponent: boolean,
fields: { [key: string]: string },
childProps: ChildProps
}
export class BindingsPlugin implements CompilerPlugin {
public name = 'BindingsPlugin';
private bindingsForFile: { [key: string]: Bindings } = {};
afterFileParse(file: BscFile) {
if (!isXmlFile(file)) {
return;
}
const program = file.program;
const bindings = this.getBindingsForXmlFile(file)
if (!bindings.isAutoBindComponent) {
return;
}
this.bindingsForFile[file.pkgPath] = bindings;
const bindingsFilePath = this.getBindingScriptPathForXmlFile(file.pkgPath);
if (!program.hasFile(bindingsFilePath)) {
program.setFile(bindingsFilePath, bindings_script_template);
}
const scriptTag = new SGScript();
scriptTag.type = "text/brightscript"
scriptTag.uri = util.getRokuPkgPath(bindingsFilePath);
if (!file.ast.component!.scripts) {
file.ast.component!.scripts = [];
}
file.ast.component!.scripts.push(scriptTag);
this.deleteBindingsInFields(file);
this.deleteBindingsInChildPropsNode(file.ast.component!.children);
file.parser.invalidateReferences();
}
beforeFileTranspile(event: BeforeFileTranspileEvent) {
if (!isBrsFile(event.file) || !event.file.pkgPath.endsWith('_bindings.bs')) {
return
}
const program = event.program;
const scope = program.getFirstScopeForFile(event.file);
if (!isXmlScope(scope)) {
return;
}
const bindings = this.bindingsForFile[scope.xmlFile.pkgPath];
if (!bindings) {
return;
}
if (event.file.callables.length !== 1) {
throw new Error(`Bindings file ${event.file.pkgPath} should have exactly one callable`);
}
const bindingsFunction = event.file.callables[0];
if (bindingsFunction.functionStatement.name.text !== bindings_function_name) {
throw new Error(`Bindings file ${event.file.pkgPath} should have exactly one function named ${bindings_function_name}`);
}
let bindingFields = "{\n" + Object.keys(bindings.fields || {}).map((fieldId) => {
return ` "${fieldId}": "${bindings.fields![fieldId]}"`;
}).join(', \n') + "\n }";
let bindingChildProps = "{\n" + Object.keys(bindings.childProps).map((childId) => {
return ` "${childId}": {\n${Object.keys(bindings.childProps[childId]).map((prop) => {
return ` "${prop}": "${bindings.childProps[childId][prop]}"`;
}).join(', \n')}\n }`;
}).join(', \n') + "\n }";
const statements = [
new RawCodeStatement(
`m.top.bindings = {
fields: ${bindingFields},
childProps: ${bindingChildProps}
}`)
];
event.editor.setProperty(bindingsFunction.functionStatement.func.body, 'statements', statements);
}
getBindingScriptPathForXmlFile(xmlFilePath: string) {
const xmlFileDir = path.dirname(xmlFilePath);
const xmlFileName = path.basename(xmlFilePath);
const bindingScriptName = xmlFileName.replace('.xml', '_bindings.bs');
const bindingScriptPath = path.join(xmlFileDir, bindingScriptName);
return bindingScriptPath;
}
getBindingsForXmlFile(xmlFile: XmlFile): Bindings {
const isAutoBindComponent = !!xmlFile.ast.component?.api?.fields?.find((field) => {
return field.id === 'binding_done';
}) && xmlFile.componentName.text !== 'AutoBind';
if (!isAutoBindComponent) {
return { isAutoBindComponent, fields: {}, childProps: {} };
}
const fields = xmlFile.ast.component?.api?.fields?.filter((field) => {
return field.attributes.find((attr) => attr.key.text === 'bind');
});
const childProps: ChildProps = {};
this.getChildBindings(childProps, xmlFile.ast.component?.children);
const bindingFields = fields?.reduce((acc, field) => {
const bindAttr = field.attributes.find((attr) => attr.key.text === 'bind');
acc[field.id] = bindAttr!.value.text;
return acc;
}, {} as { [key: string]: string }) || {};
return { isAutoBindComponent, fields: bindingFields, childProps: childProps };
}
getChildBindings(bindings: ChildProps, node: SGNode | undefined) {
if (!node) {
return;
}
if (node.id) {
const props = node.attributes.filter((attr) => attr.value.text.startsWith('bind:'));
if (props.length) {
if (!bindings[node.id]) {
bindings[node.id] = {};
}
for (let i = 0; i < props.length; i++) {
const prop = props[i];
bindings[node.id][prop.key.text] = prop.value.text.replace('bind:', '');
}
}
}
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
this.getChildBindings(bindings, child);
}
}
}
deleteBindingsInFields(xmlFile: XmlFile) {
xmlFile.ast.component!.api!.fields.forEach((field) => {
field.attributes = field.attributes.filter((attr) => {
return attr.key.text !== 'bind';
});
});
}
deleteBindingsInChildPropsNode(node: SGNode) {
if (!node) {
return;
}
node.attributes = node.attributes.filter((attr) => {
return !attr.value.text.startsWith('bind:');
});
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
this.deleteBindingsInChildPropsNode(child);
}
}
}
}
export default () => {
return new BindingsPlugin();
};
@@ -0,0 +1,164 @@
// Plugin to allow including other components in a component
import {
BscFile,
CompilerPlugin,
DiagnosticSeverity,
Program,
XmlFile,
isXmlFile,
util,
} from 'brighterscript';
import { SGChildren, SGComponent, SGInterface, SGScript } from 'brighterscript/dist/parser/SGTypes';
import { globSync } from 'glob';
import fs from 'fs-extra'
import path from 'path';
export class ComponentIncludesPlugin implements CompilerPlugin {
public name = 'ComponentIncludesPlugin';
afterFileParse(file: BscFile) {
if (!isXmlFile(file)) {
return;
}
const program = file.program;
const component = file.parser.ast.component;
if (!component) {
return;
}
const includes = this.getIncludes(component);
if (includes.length === 0) {
return;
}
includes.forEach((include) => {
const rootDir = program.options.rootDir!;
const includePaths = globSync(`**/${include.name}.part.xml`, { cwd: rootDir });
if (includePaths.length === 0) {
file.addDiagnostics([{
file: file,
range: include.range!,
message: `Could not find include: ${include.name}`,
severity: DiagnosticSeverity.Error,
code: 'INCLUDE_NOT_FOUND',
}]);
return;
}
if (includePaths.length > 1) {
file.addDiagnostics([{
file: file,
range: include.range!,
message: `Found multiple include files for include: ${include}`,
severity: DiagnosticSeverity.Error,
code: 'MULTIPLE_INCLUDES_FOUND',
}]);
return;
}
const includePath = includePaths[0];
const srcPath = path.join(rootDir, includePath);
const xmlFile = new XmlFile(srcPath, includePath, program);
const includeFileContents = fs.readFileSync(srcPath, 'utf8');
xmlFile.parse(includeFileContents);
const includeComponent = xmlFile.ast.component;
if (!includeComponent) {
return;
}
this.addScripts(component, includeComponent, includePath, program);
this.addFields(component, includeComponent);
this.addFunctions(component, includeComponent);
this.addChildren(component, includeComponent);
});
component.attributes = component.attributes.filter((attr) => {
return attr.key.text !== 'includes';
});
file.parser.invalidateReferences();
}
addScripts(component: SGComponent, includeComponent: SGComponent, includePath: string, program: Program) {
component.scripts.push(...includeComponent.scripts);
if (program.options.autoImportComponentScript) {
const possibleCodeBehindPkgPaths = [
includePath.replace('.xml', '.bs'),
includePath.replace('.xml', '.brs')
];
possibleCodeBehindPkgPaths.forEach((scriptPkgPath) => {
const scriptFilePath = path.join(program.options.rootDir!, scriptPkgPath);
if (fs.existsSync(scriptFilePath)) {
const scriptTag = new SGScript();
scriptTag.type = "text/brightscript"
scriptTag.uri = util.getRokuPkgPath(scriptPkgPath);
component.scripts.push(scriptTag);
}
});
}
}
addFields(component: SGComponent, includeComponent: SGComponent) {
if (!includeComponent.api) {
return;
}
if (!includeComponent.api.fields || includeComponent.api.fields.length === 0) {
return;
}
if (!component.api) {
component.api = new SGInterface({ text: 'interface' }, [])
}
component.api.fields.push(...includeComponent.api.fields);
}
addFunctions(component: SGComponent, includeComponent: SGComponent) {
if (!includeComponent.api) {
return;
}
if (!includeComponent.api.functions || includeComponent.api.functions.length === 0) {
return;
}
if (!component.api) {
component.api = new SGInterface({ text: 'interface' }, [])
}
component.api.functions.push(...includeComponent.api.functions);
}
addChildren(component: SGComponent, includeComponent: SGComponent) {
if (!includeComponent.children) {
return;
}
if (!includeComponent.children.children || includeComponent.children.children.length === 0) {
return;
}
if (!component.children) {
component.children = new SGChildren({ text: 'children' }, [])
}
component.children.children.push(...includeComponent.children.children);
}
getIncludes(component?: SGComponent) {
if (!component || !component.attributes) {
return [];
}
return component.attributes.filter((attr) => {
return attr.key.text === 'includes';
}).map((attr) => {
return attr.value.text.split(',').map((item) => {
return {
name: item.trim(),
range: attr.value.range,
}
});
}).flat();
}
}
export default () => {
return new ComponentIncludesPlugin();
};
+44
View File
@@ -0,0 +1,44 @@
// This plugin converts json5 and yaml files to json files
import {
CompilerPlugin, FileObj, ProgramBuilder, util,
} from 'brighterscript';
import path from 'path';
import fs from 'fs-extra'
import json5 from 'json5';
import YAML from "yaml";
const jsonExtensions = ['.json', '.jsonc', '.json5'];
const yamlExtensions = ['.yaml', '.yml'];
export class JsonYamlPlugin implements CompilerPlugin {
public name = 'JsonYamlPlugin';
afterPrepublish(builder: ProgramBuilder, files: FileObj[]) {
const jsonFiles = files
.filter((file) => jsonExtensions.includes(path.extname(file.dest)))
.map((file) => path.join(builder.options.stagingDir!, file.dest));
const yamlFiles = files
.filter((file) => yamlExtensions.includes(path.extname(file.dest)))
.map((file) => path.join(builder.options.stagingDir!, file.dest));
jsonFiles.forEach((filePath) => {
let contents = fs.readFileSync(filePath, 'utf8');
const json = json5.parse(contents);
contents = JSON.stringify(json);
fs.writeFileSync(filePath, contents);
});
yamlFiles.forEach((filePath) => {
let contents = fs.readFileSync(filePath, 'utf8');
const yaml = YAML.parse(contents);
contents = JSON.stringify(yaml);
fs.writeFileSync(filePath, contents);
});
}
}
export default () => {
return new JsonYamlPlugin();
};
@@ -1,39 +0,0 @@
import {
CompilerPlugin,
ProgramBuilder
} from 'brighterscript';
import path from 'path';
import fs from 'fs';
const ip = require('ip');
export class ManifestBsConstDebugPlugin implements CompilerPlugin {
public name = 'manifestBsConstDebugPlugin';
private originalManifestContent?: string;
beforeProgramCreate(builder: ProgramBuilder) {
const debugFlag = process.argv.find(arg => /--debug=(true|false)/i.test(arg))
if (!debugFlag) {
return;
}
const value = /--debug=(true|false)/i.exec(debugFlag)![1].toLowerCase()
builder.logger.log(`Setting bs_const DEBUG to ${value}`)
const manifestPath = path.join(builder.options.rootDir!, "manifest")
this.originalManifestContent = fs.readFileSync(manifestPath, { encoding: 'utf8', flag: 'r' })
let manifestContent = this.originalManifestContent.replace(/DEBUG=(true|false)/i, `DEBUG=${value}`);
manifestContent = manifestContent.replace(/DEBUG_HOST_IP_ADDRESS/i, `${ip.address()}`)
fs.writeFileSync(manifestPath, manifestContent)
}
afterPublish(builder: ProgramBuilder) {
if (!this.originalManifestContent) {
return
}
const manifestPath = path.join(builder.options.rootDir!, "manifest")
fs.writeFileSync(manifestPath, this.originalManifestContent!)
}
}
export default () => {
return new ManifestBsConstDebugPlugin();
};
+83
View File
@@ -0,0 +1,83 @@
// Plugin to edit the manifest file before the build, and restore it after publishing
// - --debug would set the DEBUG flag to true in the manifest file (otherwise false)
// - This is to make sure stuff in #IF DEBUG would not get stripped out by brighterscript
// - --test-mode would comment out the sg_component_libs_provided line in the manifest file
// - This allows Playlet-lib to be tested independently
// - DEBUG_HOST_IP_ADDRESS would be replaced with the host IP address in the manifest file
// - This is to playlet app to pull playlet lib from the locally hosted server
// - This is only done when --debug is set
import {
BeforeProgramDisposeEvent,
CompilerPlugin,
Program,
ProgramBuilder
} from 'brighterscript';
import path from 'path';
import fs from 'fs';
const ip = require('ip');
export class ManifestEditPlugin implements CompilerPlugin {
public name = 'ManifestEditPlugin';
private originalManifestContent?: string;
beforeProgramCreate(builder: ProgramBuilder) {
const manifestPath = path.join(builder.options.rootDir!, "manifest")
let originalManifestContent = fs.readFileSync(manifestPath, { encoding: 'utf8', flag: 'r' })
let manifestContent = originalManifestContent;
// Debug flag
// @ts-ignore
const debug = !!builder.options.debug;
builder.logger.log(`Setting bs_const DEBUG to ${debug}`)
manifestContent = manifestContent.replace(/DEBUG=(true|false)/i, `DEBUG=${debug}`);
if (debug) {
// Host IP address
manifestContent = manifestContent.replace(/DEBUG_HOST_IP_ADDRESS/i, `${ip.address()}`)
// Run as process to use the Roku Resource Monitor
if (manifestContent.indexOf('run_as_process=1') < 0) {
manifestContent += '\nrun_as_process=1';
}
}
// Test flag
// @ts-ignore
const testMode = !!builder.options.testMode;
if (testMode) {
builder.logger.log(`Commenting out "sg_component_libs_provided"`)
manifestContent = manifestContent.replace(/sg_component_libs_provided=/i, `# sg_component_libs_provided=`);
}
this.originalManifestContent = originalManifestContent;
builder.logger.info(this.name, 'Writing manifest file: ' + manifestPath);
fs.writeFileSync(manifestPath, manifestContent)
}
afterPublish(builder: ProgramBuilder) {
this.restoreManifest(builder.program);
}
beforeProgramDispose(event: BeforeProgramDisposeEvent) {
this.restoreManifest(event.program);
}
restoreManifest(program: Program) {
if (!this.originalManifestContent) {
return
}
const manifestPath = path.join(program.options.rootDir!, "manifest")
program.logger.info(this.name, 'Restoring manifest: ' + manifestPath);
fs.writeFileSync(manifestPath, this.originalManifestContent)
this.originalManifestContent = undefined;
}
}
export default () => {
return new ManifestEditPlugin();
};
+216
View File
@@ -0,0 +1,216 @@
// This plugin takes functions annotated with @oninit and adds them to the component's Init function
import {
AnnotationExpression,
BeforeFileTranspileEvent,
BrsFile,
BscFile,
Callable,
CallableContainerMap,
CompilerPlugin,
DiagnosticSeverity,
FunctionStatement,
Scope,
XmlScope,
isBrsFile,
isXmlScope,
} from 'brighterscript';
import { RawCodeStatement } from './Classes/RawCodeStatement';
// The plugin processes the file that includes the Init function, not the file that includes the @oninit functions
// This is because the modifications will be made to the Init function.
// The rules are:
// 1. If the scope inclues @oninit functions, the scope must include an Init function
// 2. An Init function that will be calling @oninit functions must be included in only one scope
// 3. @oninit functions must have a name
export class OnInitPlugin implements CompilerPlugin {
public name = 'OnInitPlugin';
afterScopeValidate(scope: Scope, files: BscFile[], callables: CallableContainerMap) {
if (!isXmlScope(scope)) {
return;
}
const onInitCallables = this.getOnInitCallables(scope);
if (onInitCallables.length === 0) {
return;
}
const initFunction = this.getInitCallableInScope(scope);
if (!initFunction) {
onInitCallables.forEach((onInitCallable) => {
// TODO:P2 we currently add diagnostics to the xml file, but we should add them to the brs file
// The reasons is, when we add to a generated file (like Component_bindings.brs), the errors
// Are stuck, and won't be fixed until the file is changed, which we can't do since it's not a real file.
scope.xmlFile.addDiagnostics([{
file: scope.xmlFile,
range: onInitCallable.annotation!.range,
message: `function ${onInitCallable.callable.functionStatement.name.text} with @oninit annotation is included in ${scope.name}, but no Init function was found in the component.`,
severity: DiagnosticSeverity.Error,
code: 1818
}]);
});
}
}
afterFileValidate(file: BscFile) {
if (!isBrsFile(file)) {
return
}
const program = file.program;
const scopes = this.getScopes(file);
if (scopes.length === 0) {
return;
}
const scope = scopes[0];
const onInitCallables = this.getOnInitCallables(scope);
if (onInitCallables.length === 0) {
program.logger.info(this.name, `No Init processing: No @oninit functions found in scope ${scope.name}`)
return;
}
const initFunction = this.getInitCallableInFile(file);
if (initFunction && scopes.length > 1 && onInitCallables.length > 0) {
file.addDiagnostics([{
file,
range: initFunction.functionStatement!.func.range,
message: `Init function will call @oninit functions, but is included in multiple scopes.`,
severity: DiagnosticSeverity.Error,
code: 1819
}]);
}
for (let i = 0; i < onInitCallables.length; i++) {
const onInitCallable = onInitCallables[i];
const functionName = onInitCallable.callable.functionStatement?.name.text;
if (!functionName) {
file.addDiagnostics([{
file: onInitCallable.callable.file,
range: onInitCallable.annotation!.range,
message: `function with @oninit annotation must have a name`,
severity: DiagnosticSeverity.Error,
code: 1820
}]);
}
}
}
beforeFileTranspile(event: BeforeFileTranspileEvent) {
if (!isBrsFile(event.file)) {
return
}
const program = event.program;
const file = event.file;
const scopes = this.getScopes(file);
if (scopes.length === 0) {
program.logger.info(this.name, `No Init processing: No scopes found in ${file.pkgPath}`)
return;
}
const initFunction = this.getInitCallableInFile(file);
if (!initFunction) {
program.logger.info(this.name, `No Init processing: No Init function found in ${file.pkgPath}`)
return;
}
if (scopes.length > 1) {
program.logger.info(this.name, `No Init processing: Init function included in more than one scope`)
return;
}
const scope = scopes[0];
const onInitCallables = this.getOnInitCallables(scope);
if (onInitCallables.length === 0) {
program.logger.info(this.name, `No Init processing: No @oninit functions found in scope ${scope.name}`)
return;
}
const orderedStatements = initFunction.functionStatement.func.body.statements.map((statement) => {
return { order: 0, statement: statement }
});
for (let i = 0; i < onInitCallables.length; i++) {
const onInitCallable = onInitCallables[i];
const functionName = onInitCallable.callable.functionStatement?.name.text;
if (!functionName) {
continue;
}
const callSource = `${functionName}() ' auto-generated!`
const callStatement = new RawCodeStatement(callSource, file);
const order = this.getOnInitOrder(onInitCallable.annotation!);
orderedStatements.push({ order, statement: callStatement });
program.logger.info(this.name, `Added call to ${functionName} in Init function of ${scope.name} (${file.pkgPath})`)
}
const statements = orderedStatements.sort((a, b) => {
return a.order - b.order;
}).map((orderedStatement) => {
return orderedStatement.statement;
});
event.editor.setProperty(initFunction.functionStatement.func.body, 'statements', statements);
}
getScopes(file: BrsFile): XmlScope[] {
return file.program.getScopesForFile(file).filter((scope) => {
return isXmlScope(scope);
}) as XmlScope[];
}
getInitCallableInFile(file: BrsFile): Callable | undefined {
return file.callables.find((callable) => {
return callable.functionStatement?.name.text === "Init";
});
}
getInitCallableInScope(scope: XmlScope): Callable | undefined {
return scope.getOwnCallables().find((callable) => {
return callable.callable.functionStatement?.name.text === "Init";
})?.callable;
}
getOnInitCallables(scope: XmlScope) {
return scope.getOwnCallables().map((callable) => {
return {
callable: callable.callable,
annotation: this.getOnInitAnnotation(callable.callable.functionStatement)
}
}).filter((callable) => {
return callable.annotation;
});
}
getOnInitAnnotation(functionStatement: FunctionStatement | undefined) {
return functionStatement?.annotations?.find((annotation) => {
return annotation.name === "oninit";
});
}
getOnInitOrder(annotation: AnnotationExpression): number {
const args = annotation.getArguments();
if (!args || args.length === 0) {
return 0;
}
return args[0].valueOf() as number;
}
}
export default () => {
return new OnInitPlugin();
};
@@ -0,0 +1,68 @@
// This plugin keeps track of transpiled files and keeps them in the src files, for testing purposes
// This plugin only runs when the --test-mode flag
//
// - Any folder ending in .transpiled will contain the transpiled files. .map files are ignored.
// - Example: src/components/tests.transpiled will contain transpiled files for src/components/tests
// - Any file ending in .transpiled.* will contain the transpiled file
// - Example: src/components/tests.transpiled.brs will contain the transpiled file for src/components/tests.bs
// - Example: src/components/tests.transpiled.xml will contain the transpiled file for src/components/tests.xml
//
// Tracking transpilied files acts as living tests for plugins. When plugins are modified, unexpected changes
// Can be caught by inspecting the diff in the transpiled files.
import {
CompilerPlugin, FileObj, ProgramBuilder,
} from 'brighterscript';
import { globSync } from "glob";
import path from 'path';
import fs from 'fs-extra'
export class TrackTranspiledPlugin implements CompilerPlugin {
public name = 'TrackTranspiledPlugin';
afterPublish(builder: ProgramBuilder, files: FileObj[]) {
// @ts-ignore
if (!builder.options.testMode) {
return;
}
const stagingDir = builder.options.stagingDir!;
const rootDir = builder.rootDir;
const transpiledFolders = globSync('**/*.transpiled', { cwd: rootDir });
for (let i = 0; i < transpiledFolders.length; i++) {
const folder = transpiledFolders[i];
const srcFolder = path.join(rootDir, folder);
fs.emptyDirSync(srcFolder);
const stagingFolder = path.join(stagingDir, folder).replace(".transpiled", "");
if (fs.existsSync(stagingFolder)) {
const files = globSync('**', { cwd: stagingFolder, nodir: true }).filter(file => !file.endsWith('.map'));
files.forEach(file => {
const stagingFile = path.join(stagingFolder, file);
const srcFile = path.join(srcFolder, file);
fs.copySync(stagingFile, srcFile)
});
}
}
const transpiledFiles = globSync('**/*.transpiled.*', { cwd: rootDir });
for (let i = 0; i < transpiledFiles.length; i++) {
const file = transpiledFiles[i];
const srcFile = path.join(rootDir, file);
fs.rmSync(srcFile, { force: true });
const stagingFile = path.join(stagingDir, file)
.replace(".transpiled", "")
.replace(".bs", ".brs");
if (fs.existsSync(stagingFile)) {
fs.copySync(stagingFile, srcFile)
}
}
}
}
export default () => {
return new TrackTranspiledPlugin();
};
+58
View File
@@ -0,0 +1,58 @@
// This plugin enforces regex based validation rules on BrightScript files.
// Rules are defined in the `validation` property of the `bsconfig.json` file.
import {
BscFile,
CompilerPlugin,
OnFileValidateEvent,
Program,
Range,
isBrsFile
} from 'brighterscript';
type Validation = {
code: number | string | undefined;
regex: string;
regexFlags?: string;
message: string;
}
export class ValidationPlugin implements CompilerPlugin {
public name = 'ValidationPlugin';
private validation?: Validation[];
beforeProgramValidate(program: Program) {
// @ts-ignore
this.validation = program.options.validation as Validation[] | undefined;
}
onFileValidate(event: OnFileValidateEvent<BscFile>) {
const file = event.file;
if (!this.validation || !isBrsFile(file)) {
return;
}
this.validation.forEach((validation) => {
const regex = new RegExp(validation.regex, validation.regexFlags);
const fileContents = file.fileContents;
let match: RegExpExecArray | null;
while ((match = regex.exec(fileContents)) !== null) {
const line = fileContents.substring(0, match.index).split('\n').length - 1;
const column = match.index - fileContents.lastIndexOf('\n', match.index) - 1;
file.diagnostics.push({
code: validation.code,
message: validation.message,
file: file,
range: Range.create(line, column, line, column + match[0].length)
});
}
});
}
}
export default () => {
return new ValidationPlugin();
};