@cloudcare/hvigor-ohos-plugin 0.1.0-alpha.1

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 ADDED
@@ -0,0 +1,11 @@
1
+ # Changelog
2
+
3
+ ## [0.1.0-alpha.1] - 2026-09-11
4
+
5
+ - Prepared the initial npm prerelease of the console/HiLog and cold-launch instrumentation plugin.
6
+
7
+ ## [0.1.0] - 2026-09-05
8
+
9
+ - Added compiler instrumentation for automatic console/HiLog collection.
10
+ - Added compiler instrumentation for cold-launch tracking.
11
+ - Fixed cold-launch instrumentation to retry first-frame observation after `WindowStage.loadContent(...)` completes successfully.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2025 Changzhou Guance Information Technology Co., Ltd.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # Guance HarmonyOS Hvigor Plugin
2
+
3
+ `@cloudcare/hvigor-ohos-plugin` is the build-time companion for `@guancecloud/ft_sdk`. It instruments direct `console.*` and `hilog.*` calls and injects cold-launch lifecycle tracking into a HAP module's `src/main/ets` sources. Runtime log collection remains controlled by `FTLoggerConfig.setEnableConsoleLog(true)` in `@guancecloud/ft_sdk`.
4
+
5
+ ## Install
6
+
7
+ This is a Hvigor tool package, so declare it in the project-level `hvigor/hvigor-config.json5` rather than a module `oh-package.json5`:
8
+
9
+ ```json5
10
+ {
11
+ "dependencies": {
12
+ "@cloudcare/hvigor-ohos-plugin": "0.1.0-alpha.1"
13
+ }
14
+ }
15
+ ```
16
+
17
+ For local development, a filesystem dependency is also supported:
18
+
19
+ ```json5
20
+ {
21
+ "dependencies": {
22
+ "@cloudcare/hvigor-ohos-plugin": "file:../ft_hvigor_plugin"
23
+ }
24
+ }
25
+ ```
26
+
27
+ ## Enable in a HAP module
28
+
29
+ ```ts
30
+ import { hapTasks } from '@ohos/hvigor-ohos-plugin'
31
+ import { ftConsoleLogPlugin } from '@cloudcare/hvigor-ohos-plugin'
32
+
33
+ export default {
34
+ system: hapTasks,
35
+ plugins: [ftConsoleLogPlugin()]
36
+ }
37
+ ```
38
+
39
+ The plugin preserves the original console/HiLog output and does not modify application files on disk. It injects cold-launch application initialization into Ability `onCreate()` methods, first-UIAbility creation into `UIAbility.onCreate()`, and first-frame observation into `UIAbility.onWindowStageCreate()`. Do not add manual cold-launch timing calls to application code.
40
+
41
+ ## Compatibility
42
+
43
+ The `0.1.0-alpha.1` prerelease is verified with Node.js 18 or newer, Hvigor and `@ohos/hvigor-ohos-plugin` 6.23.5, and HarmonyOS SDK 6.0.2 (API 22). It supports `@guancecloud/ft_sdk` `0.1.17` and later releases.
44
+
45
+ `@ohos/hvigor-ohos-plugin` is supplied by DevEco Studio's Hvigor runtime. `@guancecloud/ft_sdk` must still be declared as the application's runtime HAR dependency because the generated imports target that package.
@@ -0,0 +1,368 @@
1
+ /**
2
+ * Guance cold-launch compiler plugin.
3
+ *
4
+ * The plugin injects cold-launch boundaries into Ability lifecycle methods in
5
+ * the compiler's in-memory source. Application files are never modified.
6
+ */
7
+
8
+ declare const require: {
9
+ main: {
10
+ require(moduleName: string): any;
11
+ };
12
+ };
13
+
14
+ type TypeScriptApi = any;
15
+ type AbilityClassKind = 'stage' | 'ui' | 'other';
16
+
17
+ interface CompilePluginContext {
18
+ share: {
19
+ projectConfig: {
20
+ etsLoaderPath: string;
21
+ };
22
+ };
23
+ }
24
+
25
+ interface SharedSourceTransformRegistry {
26
+ originalReadFile: (fileName: string, options?: any) => any;
27
+ buffer: any;
28
+ transforms: Map<string, (fileName: string, code: string) => string>;
29
+ }
30
+
31
+ interface ColdLaunchInjection {
32
+ position: number;
33
+ content: string;
34
+ }
35
+
36
+ const COLD_LAUNCH_BRIDGE_IMPORT = '@guancecloud/ft_sdk/Index';
37
+ const COLD_LAUNCH_TRANSFORM_MARKER = '/* guance-cold-launch-transform:instrumented */';
38
+ const SOURCE_TRANSFORM_REGISTRY_KEY = '__guanceHvigorSourceTransformRegistry';
39
+ const TRANSFORM_ID = 'guance-cold-launch-transform';
40
+
41
+ let registeredFileSystem: any = null;
42
+
43
+ export function isApplicationArkTsSource(id: string): boolean {
44
+ const normalizedId = id.replace(/\\/g, '/');
45
+ return (normalizedId.endsWith('.ets') || normalizedId.endsWith('.ts')) &&
46
+ normalizedId.includes('/src/main/ets/') && !normalizedId.includes('/oh_modules/') &&
47
+ !normalizedId.includes('/ft_sdk/src/main/ets/');
48
+ }
49
+
50
+ function visit(ts: TypeScriptApi, node: any, visitor: (current: any) => void): void {
51
+ visitor(node);
52
+ ts.forEachChild(node, (child: any) => visit(ts, child, visitor));
53
+ }
54
+
55
+ function collectIdentifierNames(ts: TypeScriptApi, sourceFile: any): Set<string> {
56
+ const identifiers = new Set<string>();
57
+ visit(ts, sourceFile, (node: any) => {
58
+ if (ts.isIdentifier(node)) {
59
+ identifiers.add(node.text);
60
+ }
61
+ });
62
+ return identifiers;
63
+ }
64
+
65
+ function selectBridgeName(identifiers: Set<string>): string {
66
+ const baseName = '__ftColdLaunchBridge';
67
+ let bridgeName = baseName;
68
+ let suffix = 1;
69
+ while (identifiers.has(bridgeName)) {
70
+ bridgeName = `${baseName}${suffix}`;
71
+ suffix++;
72
+ }
73
+ return bridgeName;
74
+ }
75
+
76
+ function findImportInsertionOffset(ts: TypeScriptApi, sourceFile: any): number {
77
+ let offset = 0;
78
+ sourceFile.statements.forEach((statement: any) => {
79
+ if (ts.isImportDeclaration(statement)) {
80
+ offset = statement.end;
81
+ }
82
+ });
83
+ return offset;
84
+ }
85
+
86
+ function classifyAbilityBaseName(name: string): AbilityClassKind | null {
87
+ if (name === 'AbilityStage') {
88
+ return 'stage';
89
+ }
90
+ if (name === 'UIAbility') {
91
+ return 'ui';
92
+ }
93
+ if (name.endsWith('Ability') || name.endsWith('ExtensionAbility')) {
94
+ return 'other';
95
+ }
96
+ return null;
97
+ }
98
+
99
+ function collectAbilityBindings(ts: TypeScriptApi, sourceFile: any): Map<string, AbilityClassKind> {
100
+ const bindings = new Map<string, AbilityClassKind>();
101
+ sourceFile.statements.forEach((statement: any) => {
102
+ if (!ts.isImportDeclaration(statement) || !statement.moduleSpecifier ||
103
+ !ts.isStringLiteral(statement.moduleSpecifier) || !statement.importClause) {
104
+ return;
105
+ }
106
+ const moduleName = statement.moduleSpecifier.text;
107
+ if (!moduleName.startsWith('@ohos.app.ability/') && moduleName !== '@kit.AbilityKit') {
108
+ return;
109
+ }
110
+ const importClause = statement.importClause;
111
+ if (importClause.name) {
112
+ const defaultKind = classifyAbilityBaseName(moduleName.substring(moduleName.lastIndexOf('.') + 1));
113
+ if (defaultKind) {
114
+ bindings.set(importClause.name.text, defaultKind);
115
+ }
116
+ }
117
+ if (!importClause.namedBindings || !ts.isNamedImports(importClause.namedBindings)) {
118
+ return;
119
+ }
120
+ importClause.namedBindings.elements.forEach((element: any) => {
121
+ const importedName = element.propertyName ? element.propertyName.text : element.name.text;
122
+ const kind = classifyAbilityBaseName(importedName);
123
+ if (kind) {
124
+ bindings.set(element.name.text, kind);
125
+ }
126
+ });
127
+ });
128
+ return bindings;
129
+ }
130
+
131
+ function classAbilityKind(ts: TypeScriptApi, classDeclaration: any,
132
+ abilityBindings: Map<string, AbilityClassKind>): AbilityClassKind | null {
133
+ if (!classDeclaration.heritageClauses) {
134
+ return null;
135
+ }
136
+ for (const clause of classDeclaration.heritageClauses) {
137
+ if (clause.token !== ts.SyntaxKind.ExtendsKeyword || clause.types.length === 0) {
138
+ continue;
139
+ }
140
+ const expression = clause.types[0].expression;
141
+ if (!ts.isIdentifier(expression)) {
142
+ continue;
143
+ }
144
+ return abilityBindings.get(expression.text) || classifyAbilityBaseName(expression.text);
145
+ }
146
+ return null;
147
+ }
148
+
149
+ function methodIndentation(code: string, method: any): string {
150
+ const methodStart = method.getStart();
151
+ const lineStart = code.lastIndexOf('\n', methodStart) + 1;
152
+ const match = code.slice(lineStart, methodStart).match(/^\s*/);
153
+ return (match ? match[0] : '') + ' ';
154
+ }
155
+
156
+ function classIndentation(code: string, classDeclaration: any): string {
157
+ const classStart = classDeclaration.getStart();
158
+ const lineStart = code.lastIndexOf('\n', classStart) + 1;
159
+ const match = code.slice(lineStart, classStart).match(/^\s*/);
160
+ return match ? match[0] : '';
161
+ }
162
+
163
+ function blockIndentation(code: string, block: any): string {
164
+ const blockStart = block.getStart();
165
+ const lineStart = code.lastIndexOf('\n', blockStart) + 1;
166
+ const match = code.slice(lineStart, blockStart).match(/^\s*/);
167
+ return (match ? match[0] : '') + ' ';
168
+ }
169
+
170
+ function collectWindowStageParameterNames(ts: TypeScriptApi, sourceFile: any, method: any): Set<string> {
171
+ const names = new Set<string>();
172
+ method.parameters.forEach((parameter: any) => {
173
+ if (!ts.isIdentifier(parameter.name)) {
174
+ return;
175
+ }
176
+ const typeText = parameter.type ? parameter.type.getText(sourceFile) : '';
177
+ if (parameter.name.text === 'windowStage' || typeText.includes('WindowStage')) {
178
+ names.add(parameter.name.text);
179
+ }
180
+ });
181
+ return names;
182
+ }
183
+
184
+ function createFirstFrameRetryInjections(ts: TypeScriptApi, sourceFile: any, code: string,
185
+ method: any, bridgeName: string, windowStageNames: Set<string>): ColdLaunchInjection[] {
186
+ const injections: ColdLaunchInjection[] = [];
187
+ visit(ts, method.body, (node: any) => {
188
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) {
189
+ return;
190
+ }
191
+ const delegate = node.expression.expression;
192
+ if (!ts.isIdentifier(delegate) || !windowStageNames.has(delegate.text) ||
193
+ node.expression.name.text !== 'loadContent' || node.arguments.length === 0) {
194
+ return;
195
+ }
196
+ const windowStageName = delegate.text;
197
+ const callback = node.arguments[node.arguments.length - 1];
198
+ if ((!ts.isArrowFunction(callback) && !ts.isFunctionExpression(callback)) || !ts.isBlock(callback.body)) {
199
+ return;
200
+ }
201
+ const indentation = blockIndentation(code, callback.body);
202
+ const errorParameter = callback.parameters.length > 0 && ts.isIdentifier(callback.parameters[0].name)
203
+ ? callback.parameters[0].name.text : null;
204
+ const retry = `${bridgeName}.observeFirstFrame(${windowStageName});`;
205
+ const content = errorParameter === null
206
+ ? `\n${indentation}${retry}`
207
+ : `\n${indentation}if (!${errorParameter} || !${errorParameter}.code) {\n` +
208
+ `${indentation} ${retry}\n${indentation}}`;
209
+ injections.push({ position: callback.body.getStart(sourceFile) + 1, content });
210
+ });
211
+ return injections;
212
+ }
213
+
214
+ function createColdLaunchInjections(ts: TypeScriptApi, sourceFile: any, code: string,
215
+ bridgeName: string): ColdLaunchInjection[] {
216
+ const injections: ColdLaunchInjection[] = [];
217
+ const abilityBindings = collectAbilityBindings(ts, sourceFile);
218
+ visit(ts, sourceFile, (node: any) => {
219
+ if (!ts.isClassDeclaration(node)) {
220
+ return;
221
+ }
222
+ const kind = classAbilityKind(ts, node, abilityBindings);
223
+ if (!kind) {
224
+ return;
225
+ }
226
+ let hasOnCreate = false;
227
+ node.members.forEach((member: any) => {
228
+ if (!ts.isMethodDeclaration(member) || !member.body || !member.name || !ts.isIdentifier(member.name)) {
229
+ return;
230
+ }
231
+ const indentation = methodIndentation(code, member);
232
+ const position = member.body.getStart(sourceFile) + 1;
233
+ if (member.name.text === 'onCreate') {
234
+ hasOnCreate = true;
235
+ let content = `\n${indentation}${bridgeName}.recordApplicationInit(this.context);`;
236
+ if (kind === 'ui') {
237
+ content += `\n${indentation}${bridgeName}.recordFirstUIAbilityCreate();`;
238
+ }
239
+ injections.push({ position, content });
240
+ return;
241
+ }
242
+ if (kind !== 'ui' || member.name.text !== 'onWindowStageCreate' || member.parameters.length === 0) {
243
+ return;
244
+ }
245
+ const windowStageParameter = member.parameters[0];
246
+ if (!ts.isIdentifier(windowStageParameter.name)) {
247
+ return;
248
+ }
249
+ const windowStageName = windowStageParameter.name.text;
250
+ injections.push({
251
+ position,
252
+ content: `\n${indentation}${bridgeName}.observeFirstFrame(${windowStageName});`
253
+ });
254
+ });
255
+ if (kind === 'ui') {
256
+ node.members.forEach((member: any) => {
257
+ if (!ts.isMethodDeclaration(member) || !member.body) {
258
+ return;
259
+ }
260
+ const windowStageNames = collectWindowStageParameterNames(ts, sourceFile, member);
261
+ if (windowStageNames.size > 0) {
262
+ injections.push(...createFirstFrameRetryInjections(
263
+ ts, sourceFile, code, member, bridgeName, windowStageNames));
264
+ }
265
+ });
266
+ }
267
+ if (kind === 'stage' && !hasOnCreate) {
268
+ const indentation = classIndentation(code, node);
269
+ injections.push({
270
+ position: node.end - 1,
271
+ content: `\n${indentation} onCreate(): void {\n` +
272
+ `${indentation} ${bridgeName}.recordApplicationInit(this.context);\n` +
273
+ `${indentation} }\n`
274
+ });
275
+ }
276
+ });
277
+ return injections;
278
+ }
279
+
280
+ function applyColdLaunchInjections(code: string, injections: ColdLaunchInjection[]): string {
281
+ const contentsByPosition = new Map<number, string[]>();
282
+ injections.forEach((injection: ColdLaunchInjection) => {
283
+ const contents = contentsByPosition.get(injection.position) || [];
284
+ contents.push(injection.content);
285
+ contentsByPosition.set(injection.position, contents);
286
+ });
287
+ const positions = Array.from(contentsByPosition.keys()).sort((left: number, right: number) => right - left);
288
+ let transformedCode = code;
289
+ positions.forEach((position: number) => {
290
+ const content = (contentsByPosition.get(position) || []).join('');
291
+ transformedCode = transformedCode.slice(0, position) + content + transformedCode.slice(position);
292
+ });
293
+ return transformedCode;
294
+ }
295
+
296
+ function rewriteSource(ts: TypeScriptApi, id: string, code: string): string {
297
+ if (!isApplicationArkTsSource(id) || code.includes(COLD_LAUNCH_TRANSFORM_MARKER)) {
298
+ return code;
299
+ }
300
+ const sourceFile = ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
301
+ const bridgeName = selectBridgeName(collectIdentifierNames(ts, sourceFile));
302
+ const injections = createColdLaunchInjections(ts, sourceFile, code, bridgeName);
303
+ if (injections.length === 0) {
304
+ return code;
305
+ }
306
+ const insertionOffset = findImportInsertionOffset(ts, sourceFile);
307
+ const bridgeImport = `\n${COLD_LAUNCH_TRANSFORM_MARKER}\n` +
308
+ `import { FTColdLaunchBridge as ${bridgeName} } from '${COLD_LAUNCH_BRIDGE_IMPORT}';\n`;
309
+ const transformedCode = applyColdLaunchInjections(code, injections);
310
+ return transformedCode.slice(0, insertionOffset) + bridgeImport + transformedCode.slice(insertionOffset);
311
+ }
312
+
313
+ function installSourceReader(context: CompilePluginContext): void {
314
+ if (registeredFileSystem !== null) {
315
+ return;
316
+ }
317
+ const typeScriptPath = `${context.share.projectConfig.etsLoaderPath}/node_modules/typescript`;
318
+ const ts = require.main.require(typeScriptPath);
319
+ const fileSystem = require.main.require('fs');
320
+ let registry = fileSystem[SOURCE_TRANSFORM_REGISTRY_KEY] as SharedSourceTransformRegistry | undefined;
321
+ if (!registry) {
322
+ registry = {
323
+ originalReadFile: fileSystem.readFileSync as (fileName: string, options?: any) => any,
324
+ buffer: require.main.require('buffer'),
325
+ transforms: new Map<string, (fileName: string, code: string) => string>()
326
+ };
327
+ fileSystem[SOURCE_TRANSFORM_REGISTRY_KEY] = registry;
328
+ fileSystem.readFileSync = (fileName: string, options?: any): any => {
329
+ const content = registry!.originalReadFile(fileName, options);
330
+ if (typeof fileName !== 'string' || !isApplicationArkTsSource(fileName)) {
331
+ return content;
332
+ }
333
+ let transformedCode = typeof content === 'string' ? content : content.toString();
334
+ registry!.transforms.forEach((transform: (id: string, code: string) => string) => {
335
+ transformedCode = transform(fileName, transformedCode);
336
+ });
337
+ return typeof content === 'string' ? transformedCode : registry!.buffer.Buffer.from(transformedCode);
338
+ };
339
+ }
340
+ registry.transforms.set(TRANSFORM_ID, (fileName: string, code: string) => rewriteSource(ts, fileName, code));
341
+ registeredFileSystem = fileSystem;
342
+ }
343
+
344
+ function restoreSourceReader(): void {
345
+ if (registeredFileSystem === null) {
346
+ return;
347
+ }
348
+ const registry = registeredFileSystem[SOURCE_TRANSFORM_REGISTRY_KEY] as SharedSourceTransformRegistry | undefined;
349
+ if (registry) {
350
+ registry.transforms.delete(TRANSFORM_ID);
351
+ if (registry.transforms.size === 0) {
352
+ registeredFileSystem.readFileSync = registry.originalReadFile;
353
+ delete registeredFileSystem[SOURCE_TRANSFORM_REGISTRY_KEY];
354
+ }
355
+ }
356
+ registeredFileSystem = null;
357
+ }
358
+
359
+ export default {
360
+ name: 'guance-cold-launch-transform',
361
+ order: 'first',
362
+ buildStart(this: CompilePluginContext): void {
363
+ installSourceReader(this);
364
+ },
365
+ buildEnd(): void {
366
+ restoreSourceReader();
367
+ }
368
+ };
@@ -0,0 +1,339 @@
1
+ /**
2
+ * Guance console-log compiler plugin.
3
+ *
4
+ * Hvigor creates the ArkTS type-checking program before normal Rollup
5
+ * transform hooks run. This plugin therefore rewrites only the in-memory
6
+ * application source read by that program. Application files on disk are
7
+ * never changed.
8
+ */
9
+
10
+ declare const require: {
11
+ main: {
12
+ require(moduleName: string): any;
13
+ };
14
+ };
15
+
16
+ type TypeScriptApi = any;
17
+
18
+ interface CompilePluginContext {
19
+ share: {
20
+ projectConfig: {
21
+ etsLoaderPath: string;
22
+ };
23
+ };
24
+ }
25
+
26
+ interface SharedSourceTransformRegistry {
27
+ originalReadFile: (fileName: string, options?: any) => any;
28
+ buffer: any;
29
+ transforms: Map<string, (fileName: string, code: string) => string>;
30
+ }
31
+
32
+ interface TransformCandidate {
33
+ start: number;
34
+ end: number;
35
+ calleeEnd: number;
36
+ delegate: string;
37
+ level: string;
38
+ source: 'console' | 'hilog';
39
+ callArguments: SourceRange[];
40
+ }
41
+
42
+ interface SourceRange {
43
+ start: number;
44
+ end: number;
45
+ }
46
+
47
+ const HILOG_MODULES: string[] = ['@ohos.hilog', '@kit.PerformanceAnalysisKit'];
48
+ const CONSOLE_LEVELS: string[] = ['log', 'debug', 'info', 'warn', 'error', 'trace'];
49
+ const HILOG_LEVELS: string[] = ['debug', 'info', 'warn', 'error', 'fatal'];
50
+ const BRIDGE_IMPORT = '@guancecloud/ft_sdk/Index';
51
+ // Hvigor can read a source file through more than one compiler layer in an
52
+ // incremental/daemon build. Keep a marker in the in-memory result so a later
53
+ // reader does not wrap the original console/HiLog call a second time.
54
+ const TRANSFORM_MARKER = '/* guance-console-log-transform:instrumented */';
55
+ const SOURCE_TRANSFORM_REGISTRY_KEY = '__guanceHvigorSourceTransformRegistry';
56
+ const TRANSFORM_ID = 'guance-console-log-transform';
57
+
58
+ let registeredFileSystem: any = null;
59
+
60
+ export function isApplicationArkTsSource(id: string): boolean {
61
+ const normalizedId = id.replace(/\\/g, '/');
62
+ return (normalizedId.endsWith('.ets') || normalizedId.endsWith('.ts')) &&
63
+ normalizedId.includes('/src/main/ets/') && !normalizedId.includes('/oh_modules/') &&
64
+ !normalizedId.includes('/ft_sdk/src/main/ets/');
65
+ }
66
+
67
+ function visit(ts: TypeScriptApi, node: any, visitor: (current: any) => void): void {
68
+ visitor(node);
69
+ ts.forEachChild(node, (child: any) => visit(ts, child, visitor));
70
+ }
71
+
72
+ function collectIdentifierNames(ts: TypeScriptApi, sourceFile: any): Set<string> {
73
+ const identifiers = new Set<string>();
74
+ visit(ts, sourceFile, (node: any) => {
75
+ if (ts.isIdentifier(node)) {
76
+ identifiers.add(node.text);
77
+ }
78
+ });
79
+ return identifiers;
80
+ }
81
+
82
+ function isNameDeclaredOutsideImports(ts: TypeScriptApi, sourceFile: any, name: string): boolean {
83
+ let declared = false;
84
+ visit(ts, sourceFile, (node: any) => {
85
+ if (declared || ts.isImportDeclaration(node)) {
86
+ return;
87
+ }
88
+ if (ts.isVariableDeclaration(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) ||
89
+ ts.isParameter(node) || ts.isEnumDeclaration(node) || ts.isInterfaceDeclaration(node) ||
90
+ ts.isTypeAliasDeclaration(node)) {
91
+ const declarationName = node.name;
92
+ if (declarationName && ts.isIdentifier(declarationName) && declarationName.text === name) {
93
+ declared = true;
94
+ }
95
+ }
96
+ });
97
+ return declared;
98
+ }
99
+
100
+ function collectHiLogBindings(ts: TypeScriptApi, sourceFile: any): Set<string> {
101
+ const bindings = new Set<string>();
102
+ sourceFile.statements.forEach((statement: any) => {
103
+ if (!ts.isImportDeclaration(statement) || !statement.moduleSpecifier ||
104
+ !ts.isStringLiteral(statement.moduleSpecifier) ||
105
+ !HILOG_MODULES.includes(statement.moduleSpecifier.text) || !statement.importClause) {
106
+ return;
107
+ }
108
+
109
+ const importClause = statement.importClause;
110
+ if (importClause.name) {
111
+ bindings.add(importClause.name.text);
112
+ }
113
+ if (!importClause.namedBindings) {
114
+ return;
115
+ }
116
+ if (ts.isNamespaceImport(importClause.namedBindings)) {
117
+ bindings.add(importClause.namedBindings.name.text);
118
+ return;
119
+ }
120
+ importClause.namedBindings.elements.forEach((element: any) => {
121
+ const importedName = element.propertyName ? element.propertyName.text : element.name.text;
122
+ if (importedName === 'hilog') {
123
+ bindings.add(element.name.text);
124
+ }
125
+ });
126
+ });
127
+ return bindings;
128
+ }
129
+
130
+ function collectCandidates(ts: TypeScriptApi, sourceFile: any, code: string): TransformCandidate[] {
131
+ const candidates: TransformCandidate[] = [];
132
+ const hiLogBindings = collectHiLogBindings(ts, sourceFile);
133
+ const consoleIsShadowed = isNameDeclaredOutsideImports(ts, sourceFile, 'console');
134
+ const shadowedHiLogBindings = new Set<string>();
135
+ hiLogBindings.forEach((binding: string) => {
136
+ if (isNameDeclaredOutsideImports(ts, sourceFile, binding)) {
137
+ shadowedHiLogBindings.add(binding);
138
+ }
139
+ });
140
+
141
+ visit(ts, sourceFile, (node: any) => {
142
+ if (!ts.isCallExpression(node) || !ts.isPropertyAccessExpression(node.expression)) {
143
+ return;
144
+ }
145
+ const delegate = node.expression.expression;
146
+ if (!ts.isIdentifier(delegate)) {
147
+ return;
148
+ }
149
+ const delegateName = delegate.text;
150
+ const level = node.expression.name.text;
151
+ const start = node.getStart(sourceFile);
152
+ const end = node.end;
153
+ const calleeEnd = node.expression.end;
154
+ if (start < 0 || end > code.length || calleeEnd < start || calleeEnd > end) {
155
+ return;
156
+ }
157
+
158
+ const callArguments: SourceRange[] = node.arguments.map((argument: any) => ({
159
+ start: argument.getStart(sourceFile),
160
+ end: argument.end
161
+ }));
162
+ if (delegateName === 'console' && !consoleIsShadowed && CONSOLE_LEVELS.includes(level)) {
163
+ candidates.push({ start, end, calleeEnd, delegate: delegateName, level, source: 'console', callArguments });
164
+ return;
165
+ }
166
+ if (hiLogBindings.has(delegateName) && !shadowedHiLogBindings.has(delegateName) &&
167
+ HILOG_LEVELS.includes(level) && callArguments.length >= 3) {
168
+ candidates.push({ start, end, calleeEnd, delegate: delegateName, level, source: 'hilog', callArguments });
169
+ }
170
+ });
171
+ return candidates;
172
+ }
173
+
174
+ function selectBridgeName(identifiers: Set<string>): string {
175
+ const baseName = '__ftConsoleLogBridge';
176
+ let bridgeName = baseName;
177
+ let suffix = 1;
178
+ while (identifiers.has(bridgeName)) {
179
+ bridgeName = `${baseName}${suffix}`;
180
+ suffix++;
181
+ }
182
+ return bridgeName;
183
+ }
184
+
185
+ function isNestedIn(candidate: TransformCandidate, parent: TransformCandidate): boolean {
186
+ return parent !== candidate && parent.start <= candidate.start && parent.end >= candidate.end;
187
+ }
188
+
189
+ function renderCandidates(code: string, candidates: TransformCandidate[], bridgeName: string,
190
+ rangeStart: number, rangeEnd: number): string {
191
+ const inRange = candidates.filter((candidate: TransformCandidate) =>
192
+ candidate.start >= rangeStart && candidate.end <= rangeEnd);
193
+ const directCandidates = inRange.filter((candidate: TransformCandidate) =>
194
+ !inRange.some((parent: TransformCandidate) => isNestedIn(candidate, parent)));
195
+ if (directCandidates.length === 0) {
196
+ return code.slice(rangeStart, rangeEnd);
197
+ }
198
+
199
+ const descending = directCandidates.sort((left: TransformCandidate, right: TransformCandidate) =>
200
+ right.start - left.start);
201
+ let cursor = rangeEnd;
202
+ let output = '';
203
+ for (const candidate of descending) {
204
+ output = renderCandidate(code, candidates, bridgeName, candidate) + code.slice(candidate.end, cursor) + output;
205
+ cursor = candidate.start;
206
+ }
207
+ return code.slice(rangeStart, cursor) + output;
208
+ }
209
+
210
+ function renderCandidate(code: string, candidates: TransformCandidate[], bridgeName: string,
211
+ candidate: TransformCandidate): string {
212
+ const renderedArguments = candidate.callArguments.map((argument: SourceRange) =>
213
+ renderCandidates(code, candidates, bridgeName, argument.start, argument.end));
214
+ if (candidate.source === 'console') {
215
+ const argumentNames = renderedArguments.map((_argument: string, index: number) => `__ftConsoleArg${index}`);
216
+ const parameterDeclarations = argumentNames.map((name: string) => `${name}: Object`).join(', ');
217
+ const originalCallArguments = argumentNames.map((name: string) => `${name} as string`);
218
+ const originalCall = `${candidate.delegate}.${candidate.level}(${originalCallArguments.join(', ')})`;
219
+ const captureArguments = argumentNames.length > 0 ? `, ${argumentNames.join(', ')}` : '';
220
+ return `((${parameterDeclarations}): void => ${bridgeName}.console('${candidate.level}', ` +
221
+ `(): void => ${originalCall}${captureArguments}))(${renderedArguments.join(', ')})`;
222
+ }
223
+
224
+ const argumentNames = renderedArguments.map((_argument: string, index: number) => {
225
+ if (index === 0) {
226
+ return '__ftHiLogDomain';
227
+ }
228
+ if (index === 1) {
229
+ return '__ftHiLogTag';
230
+ }
231
+ if (index === 2) {
232
+ return '__ftHiLogFormat';
233
+ }
234
+ return `__ftHiLogArg${index - 3}`;
235
+ });
236
+ const parameterDeclarations = argumentNames.map((name: string, index: number) => {
237
+ if (index === 0) {
238
+ return `${name}: number`;
239
+ }
240
+ if (index === 1 || index === 2) {
241
+ return `${name}: string`;
242
+ }
243
+ return `${name}: Object`;
244
+ }).join(', ');
245
+ const originalCall = `${candidate.delegate}.${candidate.level}(${argumentNames.join(', ')})`;
246
+ const captureArguments = argumentNames.length > 3 ? `, ${argumentNames.slice(3).join(', ')}` : '';
247
+ return `((${parameterDeclarations}): void => ${bridgeName}.hilog('${candidate.level}', ` +
248
+ `${argumentNames[0]}, ${argumentNames[1]}, ${argumentNames[2]}, (): void => ${originalCall}` +
249
+ `${captureArguments}))(${renderedArguments.join(', ')})`;
250
+ }
251
+
252
+ function findImportInsertionOffset(ts: TypeScriptApi, sourceFile: any): number {
253
+ let offset = 0;
254
+ sourceFile.statements.forEach((statement: any) => {
255
+ if (ts.isImportDeclaration(statement)) {
256
+ offset = statement.end;
257
+ }
258
+ });
259
+ return offset;
260
+ }
261
+
262
+ function rewriteSource(ts: TypeScriptApi, id: string, code: string): string {
263
+ if (!isApplicationArkTsSource(id) || code.includes(TRANSFORM_MARKER)) {
264
+ return code;
265
+ }
266
+ const sourceFile = ts.createSourceFile(id, code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
267
+ const candidates = collectCandidates(ts, sourceFile, code);
268
+ if (candidates.length === 0) {
269
+ return code;
270
+ }
271
+
272
+ const bridgeName = selectBridgeName(collectIdentifierNames(ts, sourceFile));
273
+ const transformedCode = renderCandidates(code, candidates, bridgeName, 0, code.length);
274
+ const insertionOffset = findImportInsertionOffset(ts, sourceFile);
275
+ const transformedInsertionOffset = renderCandidates(code, candidates, bridgeName, 0, insertionOffset).length;
276
+ const bridgeImport = `\n${TRANSFORM_MARKER}\n` +
277
+ `import { FTConsoleLogBridge as ${bridgeName} } from '${BRIDGE_IMPORT}';\n` +
278
+ `${bridgeName}.markCompilerPluginInstalled();\n`;
279
+ return transformedCode.slice(0, transformedInsertionOffset) + bridgeImport +
280
+ transformedCode.slice(transformedInsertionOffset);
281
+ }
282
+
283
+ function installSourceReader(context: CompilePluginContext): void {
284
+ if (registeredFileSystem !== null) {
285
+ return;
286
+ }
287
+
288
+ const typeScriptPath = `${context.share.projectConfig.etsLoaderPath}/node_modules/typescript`;
289
+ const ts = require.main.require(typeScriptPath);
290
+ const fileSystem = require.main.require('fs');
291
+ let registry = fileSystem[SOURCE_TRANSFORM_REGISTRY_KEY] as SharedSourceTransformRegistry | undefined;
292
+ if (!registry) {
293
+ registry = {
294
+ originalReadFile: fileSystem.readFileSync as (fileName: string, options?: any) => any,
295
+ buffer: require.main.require('buffer'),
296
+ transforms: new Map<string, (fileName: string, code: string) => string>()
297
+ };
298
+ fileSystem[SOURCE_TRANSFORM_REGISTRY_KEY] = registry;
299
+ fileSystem.readFileSync = (fileName: string, options?: any): any => {
300
+ const content = registry!.originalReadFile(fileName, options);
301
+ if (typeof fileName !== 'string' || !isApplicationArkTsSource(fileName)) {
302
+ return content;
303
+ }
304
+ let transformedCode = typeof content === 'string' ? content : content.toString();
305
+ registry!.transforms.forEach((transform: (id: string, code: string) => string) => {
306
+ transformedCode = transform(fileName, transformedCode);
307
+ });
308
+ return typeof content === 'string' ? transformedCode : registry!.buffer.Buffer.from(transformedCode);
309
+ };
310
+ }
311
+ registry.transforms.set(TRANSFORM_ID, (fileName: string, code: string) => rewriteSource(ts, fileName, code));
312
+ registeredFileSystem = fileSystem;
313
+ }
314
+
315
+ function restoreSourceReader(): void {
316
+ if (registeredFileSystem === null) {
317
+ return;
318
+ }
319
+ const registry = registeredFileSystem[SOURCE_TRANSFORM_REGISTRY_KEY] as SharedSourceTransformRegistry | undefined;
320
+ if (registry) {
321
+ registry.transforms.delete(TRANSFORM_ID);
322
+ if (registry.transforms.size === 0) {
323
+ registeredFileSystem.readFileSync = registry.originalReadFile;
324
+ delete registeredFileSystem[SOURCE_TRANSFORM_REGISTRY_KEY];
325
+ }
326
+ }
327
+ registeredFileSystem = null;
328
+ }
329
+
330
+ export default {
331
+ name: 'guance-console-log-transform',
332
+ order: 'first',
333
+ buildStart(this: CompilePluginContext): void {
334
+ installSourceReader(this);
335
+ },
336
+ buildEnd(): void {
337
+ restoreSourceReader();
338
+ }
339
+ };
package/index.js ADDED
@@ -0,0 +1,28 @@
1
+ 'use strict';
2
+
3
+ const path = require('path');
4
+ const { OhosPluginId } = require('@ohos/hvigor-ohos-plugin');
5
+
6
+ /**
7
+ * Returns the HAP-level Hvigor plugin used to instrument console/HiLog calls
8
+ * and cold-launch lifecycle boundaries before ArkTS compilation.
9
+ *
10
+ * This package intentionally contains build tooling only. Applications still
11
+ * need @guancecloud/ft_sdk at runtime to receive the instrumented log calls.
12
+ */
13
+ function ftConsoleLogPlugin() {
14
+ return {
15
+ pluginId: 'guance-console-log-compiler',
16
+ apply(node) {
17
+ const hapContext = node.getContext(OhosPluginId.OHOS_HAP_PLUGIN);
18
+ const consoleLogTransformPath = path.join(__dirname, 'hvigorCompile', 'ft-console-log-transform.ts');
19
+ const coldLaunchTransformPath = path.join(__dirname, 'hvigorCompile', 'ft-cold-launch-transform.ts');
20
+ hapContext.loadCompilePlugin(consoleLogTransformPath);
21
+ hapContext.loadCompilePlugin(coldLaunchTransformPath);
22
+ }
23
+ };
24
+ }
25
+
26
+ module.exports = {
27
+ ftConsoleLogPlugin
28
+ };
package/package.json ADDED
@@ -0,0 +1,27 @@
1
+ {
2
+ "name": "@cloudcare/hvigor-ohos-plugin",
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "Guance HarmonyOS Hvigor plugin for automatic console, HiLog, and cold-launch collection.",
5
+ "main": "index.js",
6
+ "files": [
7
+ "index.js",
8
+ "hvigorCompile/ft-console-log-transform.ts",
9
+ "hvigorCompile/ft-cold-launch-transform.ts",
10
+ "README.md",
11
+ "CHANGELOG.md",
12
+ "LICENSE"
13
+ ],
14
+ "author": "Guance",
15
+ "license": "Apache-2.0",
16
+ "engines": {
17
+ "node": ">=18"
18
+ },
19
+ "peerDependencies": {
20
+ "@guancecloud/ft_sdk": ">=0.1.17"
21
+ },
22
+ "peerDependenciesMeta": {
23
+ "@guancecloud/ft_sdk": {
24
+ "optional": true
25
+ }
26
+ }
27
+ }