Skip to content
Open
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
35 changes: 35 additions & 0 deletions docs/man_pages/project/hooks/hooks.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<% if (isJekyll) { %>---
title: ns hooks
position: 1
---<% } %>

# ns create

### Description

Manages lifecycle hooks from installed plugins.

### Commands

Usage | Synopsis
---------|---------
Install | `$ ns hooks install`
List | `$ ns hooks list`
Lock | `$ ns hooks lock`
Verify | `$ ns hooks verify`

#### Install

Installs hooks from each installed plugin dependency.

#### List

Lists the plugins which have hooks and which scripts they install

#### Lock

Generates a `hooks-lock.json` containing the hooks that are in the current versions of the plugins.

#### Verify

Verifies that the hooks contained in the installed plugins match those listed in the `hooks-lock.json` file.
1 change: 1 addition & 0 deletions docs/man_pages/start.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ Command | Description
[plugin](lib-management/plugin.html) | Lets you manage the plugins for your project.
[open](project/configuration/open.md) | Opens the native project in Xcode/Android Studio.
[widget ios](project/configuration/widget.md) | Adds a new iOS widget to the project.
[hooks](project/hooks/hooks.html) | Installs lifecycle hooks from plugins.
## Publishing Commands
Command | Description
---|---
Expand Down
9 changes: 9 additions & 0 deletions lib/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,15 @@ injector.requireCommand("plugin|update", "./commands/plugin/update-plugin");
injector.requireCommand("plugin|build", "./commands/plugin/build-plugin");
injector.requireCommand("plugin|create", "./commands/plugin/create-plugin");

injector.requireCommand(
["hooks|*list", "hooks|install"],
"./commands/hooks/hooks",
);
injector.requireCommand(
["hooks|lock", "hooks|verify"],
"./commands/hooks/hooks-lock",
);

injector.require("doctorService", "./services/doctor-service");
injector.require("xcprojService", "./services/xcproj-service");
injector.require("versionsService", "./services/versions-service");
Expand Down
118 changes: 118 additions & 0 deletions lib/commands/hooks/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
import * as _ from "lodash";
import { IProjectData } from "../../definitions/project";
import { IPluginData } from "../../definitions/plugins";
import { ICommandParameter } from "../../common/definitions/commands";
import { IErrors, IFileSystem } from "../../common/declarations";
import path = require("path");
import * as crypto from "crypto";

export const LOCK_FILE_NAME = "nativescript-lock.json";
export interface OutputHook {
type: string;
hash: string;
}

export interface OutputPlugin {
name: string;
hooks: OutputHook[];
}

export class HooksVerify {
public allowedParameters: ICommandParameter[] = [];

constructor(
protected $projectData: IProjectData,
protected $errors: IErrors,
protected $fs: IFileSystem,
protected $logger: ILogger,
) {
this.$projectData.initializeProjectData();
}

protected async verifyHooksLock(
plugins: IPluginData[],
hooksLockPath: string,
): Promise<void> {
let lockFileContent: string;
let hooksLock: OutputPlugin[];

try {
lockFileContent = this.$fs.readText(hooksLockPath, "utf8");
hooksLock = JSON.parse(lockFileContent);
} catch (err) {
this.$errors.fail(
`❌ Failed to read or parse ${LOCK_FILE_NAME} at ${hooksLockPath}`,
);
}

const lockMap = new Map<string, Map<string, string>>(); // pluginName -> hookType -> hash

for (const plugin of hooksLock) {
const hookMap = new Map<string, string>();
for (const hook of plugin.hooks) {
hookMap.set(hook.type, hook.hash);
}
lockMap.set(plugin.name, hookMap);
}

let isValid = true;

for (const plugin of plugins) {
const pluginLockHooks = lockMap.get(plugin.name);

if (!pluginLockHooks) {
this.$logger.error(
`❌ Plugin '${plugin.name}' not found in ${LOCK_FILE_NAME}`,
);
isValid = false;
continue;
}

for (const hook of plugin.nativescript?.hooks || []) {
const expectedHash = pluginLockHooks.get(hook.type);

if (!expectedHash) {
this.$logger.error(
`❌ Missing hook '${hook.type}' for plugin '${plugin.name}' in ${LOCK_FILE_NAME}`,
);
isValid = false;
continue;
}

let fileContent: string | Buffer<ArrayBufferLike>;

try {
fileContent = this.$fs.readFile(
path.join(plugin.fullPath, hook.script),
);
} catch (err) {
this.$logger.error(
`❌ Cannot read script file '${hook.script}' for hook '${hook.type}' in plugin '${plugin.name}'`,
);
isValid = false;
continue;
}

const actualHash = crypto
.createHash("sha256")
.update(fileContent)
.digest("hex");

if (actualHash !== expectedHash) {
this.$logger.error(
`❌ Hash mismatch for '${hook.script}' (${hook.type} in ${plugin.name}):`,
);
this.$logger.error(` Expected: ${expectedHash}`);
this.$logger.error(` Actual: ${actualHash}`);
isValid = false;
}
}
}

if (isValid) {
this.$logger.info("✅ All hooks verified successfully. No issues found.");
} else {
this.$errors.fail("❌ One or more hooks failed verification.");
}
}
}
135 changes: 135 additions & 0 deletions lib/commands/hooks/hooks-lock.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { IProjectData } from "../../definitions/project";
import { IPluginsService, IPluginData } from "../../definitions/plugins";
import { ICommand, ICommandParameter } from "../../common/definitions/commands";
import { IErrors, IFileSystem } from "../../common/declarations";
import { injector } from "../../common/yok";
import path = require("path");
import * as crypto from "crypto";
import {
HooksVerify,
LOCK_FILE_NAME,
OutputHook,
OutputPlugin,
} from "./common";

export class HooksLockPluginCommand implements ICommand {
public allowedParameters: ICommandParameter[] = [];

constructor(
private $pluginsService: IPluginsService,
private $projectData: IProjectData,
private $errors: IErrors,
private $fs: IFileSystem,
private $logger: ILogger,
) {
this.$projectData.initializeProjectData();
}

public async execute(): Promise<void> {
const plugins: IPluginData[] =
await this.$pluginsService.getAllInstalledPlugins(this.$projectData);
if (plugins && plugins.length > 0) {
const pluginsWithHooks: IPluginData[] = [];
for (const plugin of plugins) {
if (plugin.nativescript?.hooks?.length > 0) {
pluginsWithHooks.push(plugin);
}
}

await this.writeHooksLockFile(
pluginsWithHooks,
this.$projectData.projectDir,
);
} else {
this.$logger.info("No plugins with hooks found.");
}
}

public async canExecute(args: string[]): Promise<boolean> {
return true;
}

private async writeHooksLockFile(
plugins: IPluginData[],
outputDir: string,
): Promise<void> {
const output: OutputPlugin[] = [];

for (const plugin of plugins) {
const hooks: OutputHook[] = [];

for (const hook of plugin.nativescript?.hooks || []) {
try {
const fileContent = this.$fs.readFile(
path.join(plugin.fullPath, hook.script),
);
const hash = crypto
.createHash("sha256")
.update(fileContent)
.digest("hex");

hooks.push({
type: hook.type,
hash,
});
} catch (err) {
this.$logger.warn(
`Warning: Failed to read script '${hook.script}' for plugin '${plugin.name}'. Skipping this hook.`,
);
continue;
}
}

output.push({ name: plugin.name, hooks });
}

const filePath = path.resolve(outputDir, LOCK_FILE_NAME);

try {
this.$fs.writeFile(filePath, JSON.stringify(output, null, 2), "utf8");
this.$logger.info(`✅ ${LOCK_FILE_NAME} written to: ${filePath}`);
} catch (err) {
this.$errors.fail(`❌ Failed to write ${LOCK_FILE_NAME}: ${err}`);
}
}
}

export class HooksVerifyPluginCommand extends HooksVerify implements ICommand {
public allowedParameters: ICommandParameter[] = [];

constructor(
private $pluginsService: IPluginsService,
$projectData: IProjectData,
$errors: IErrors,
$fs: IFileSystem,
$logger: ILogger,
) {
super($projectData, $errors, $fs, $logger);
}

public async execute(): Promise<void> {
const plugins: IPluginData[] =
await this.$pluginsService.getAllInstalledPlugins(this.$projectData);
if (plugins && plugins.length > 0) {
const pluginsWithHooks: IPluginData[] = [];
for (const plugin of plugins) {
if (plugin.nativescript?.hooks?.length > 0) {
pluginsWithHooks.push(plugin);
}
}
await this.verifyHooksLock(
pluginsWithHooks,
path.join(this.$projectData.projectDir, LOCK_FILE_NAME),
);
} else {
this.$logger.info("No plugins with hooks found.");
}
}

public async canExecute(args: string[]): Promise<boolean> {
return true;
}
}

injector.registerCommand(["hooks|lock"], HooksLockPluginCommand);
injector.registerCommand(["hooks|verify"], HooksVerifyPluginCommand);
Loading