@trackunit/iris-app 1.4.48 → 1.4.49

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 CHANGED
@@ -1,3 +1,7 @@
1
+ ## 1.4.49 (2025-08-14)
2
+
3
+ This was a version bump only for iris-app to align it with other projects, there were no code changes.
4
+
1
5
  ## 1.4.48 (2025-08-14)
2
6
 
3
7
  ### 🧱 Updated Dependencies
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trackunit/iris-app",
3
- "version": "1.4.48",
3
+ "version": "1.4.49",
4
4
  "license": "SEE LICENSE IN LICENSE.txt",
5
5
  "main": "src/index.js",
6
6
  "generators": "./generators.json",
@@ -1,5 +1,10 @@
1
1
  import { Tree } from "@nx/devkit";
2
2
  import { IrisAppExtensionGeneratorSchema } from "./schema";
3
+ /**
4
+ * Ensures that jest.preset.js exists and includes the required @trackunit/react-test-setup preset.
5
+ * If the file doesn't exist, creates it. If it exists but doesn't include the preset, updates it.
6
+ */
7
+ export declare function ensureJestPresetConfiguration(tree: Tree, templateOptions?: object): void;
3
8
  /**
4
9
  * Iris App Extension Generator.
5
10
  *
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.IrisAppExtensionGenerator = void 0;
4
+ exports.ensureJestPresetConfiguration = ensureJestPresetConfiguration;
4
5
  const tslib_1 = require("tslib");
5
6
  const devkit_1 = require("@nx/devkit");
6
7
  const eslint_1 = require("@nx/eslint");
@@ -13,6 +14,7 @@ const fs = tslib_1.__importStar(require("fs"));
13
14
  const path = tslib_1.__importStar(require("path"));
14
15
  const string_ts_1 = require("string-ts");
15
16
  const ts_morph_1 = require("ts-morph");
17
+ const astUtils_1 = require("../../utils/ast/astUtils");
16
18
  const dependencies_1 = require("./dependencies");
17
19
  function normalizeOptions(tree, options) {
18
20
  const name = (0, devkit_1.names)(options.name).fileName;
@@ -39,6 +41,35 @@ function normalizeOptions(tree, options) {
39
41
  dependencyDefinitionFile,
40
42
  };
41
43
  }
44
+ /**
45
+ * Ensures that jest.preset.js exists and includes the required @trackunit/react-test-setup preset.
46
+ * If the file doesn't exist, creates it. If it exists but doesn't include the preset, updates it.
47
+ */
48
+ function ensureJestPresetConfiguration(tree, templateOptions) {
49
+ const jestPresetPath = "jest.preset.js";
50
+ if (!tree.exists(jestPresetPath)) {
51
+ // File doesn't exist, generate it using the template
52
+ (0, devkit_1.generateFiles)(tree, path.join(__dirname, "files", "preset"), "/", templateOptions || {});
53
+ return;
54
+ }
55
+ // File exists, use AST utilities for reliable manipulation
56
+ let currentContent = tree.read(jestPresetPath, "utf-8");
57
+ if (!currentContent) {
58
+ throw new Error(`Could not read ${jestPresetPath}`);
59
+ }
60
+ // Extract variable name from existing import if it exists
61
+ let presetVariableName = "irisPreset"; // default name
62
+ const existingImportMatch = currentContent.match(/const\s+(\w+)\s*=\s*require\(["']@trackunit\/react-test-setup\/preset["']\)/);
63
+ if (existingImportMatch && existingImportMatch[1]) {
64
+ presetVariableName = existingImportMatch[1];
65
+ }
66
+ // Add the require statement if it doesn't exist
67
+ currentContent = (0, astUtils_1.addRequireStatement)(currentContent, presetVariableName, "@trackunit/react-test-setup/preset");
68
+ // Add the spread assignment to the module.exports object
69
+ currentContent = (0, astUtils_1.addSpreadAssignment)(currentContent, presetVariableName);
70
+ // Write the updated content back to the tree
71
+ tree.write(jestPresetPath, currentContent);
72
+ }
42
73
  /**
43
74
  * Iris App Extension Generator.
44
75
  *
@@ -85,7 +116,9 @@ const IrisAppExtensionGenerator = async function (tree, options) {
85
116
  (0, devkit_1.generateFiles)(tree, path.join(__dirname, "files", irisAppExtensionType), normalizedOptions.projectRoot, templateOptions);
86
117
  if (!iris_app_api_1.nonUiExtensionTypes.includes(irisAppExtensionType)) {
87
118
  (0, devkit_1.generateFiles)(tree, path.join(__dirname, "files", "react-app"), normalizedOptions.projectRoot, templateOptions);
88
- (0, devkit_1.generateFiles)(tree, path.join(__dirname, "files", "preset"), "/", templateOptions);
119
+ if (normalizedOptions.extendJestPreset) {
120
+ ensureJestPresetConfiguration(tree, templateOptions);
121
+ }
89
122
  }
90
123
  const rootTsConfigPath = (0, js_1.getRootTsConfigPathInTree)(tree);
91
124
  if (!rootTsConfigPath) {
@@ -1 +1 @@
1
- {"version":3,"file":"generator.js","sourceRoot":"","sources":["../../../../../../../libs/iris-app-sdk/iris-app/src/generators/extend/generator.ts"],"names":[],"mappings":";;;;AAAA,uCAWoB;AACpB,uCAAoC;AACpC,+BAAmD;AACnD,+EAA0E;AAC1E,qCAA6C;AAE7C,0DAAwF;AACxF,uCAAkC;AAClC,+CAAyB;AACzB,mDAA6B;AAC7B,yCAAsC;AACtC,uCAAoE;AACpE,iDAAmE;AAanE,SAAS,gBAAgB,CAAC,IAAU,EAAE,OAAwC;IAC5E,MAAM,IAAI,GAAG,IAAA,cAAK,EAAC,OAAO,CAAC,IAAI,CAAC,CAAC,QAAQ,CAAC;IAC1C,MAAM,gBAAgB,GAAG,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,IAAA,cAAK,EAAC,OAAO,CAAC,SAAS,CAAC,CAAC,QAAQ,IAAI,IAAI,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC;IACnG,MAAM,WAAW,GAAG,gBAAgB,CAAC,OAAO,CAAC,IAAI,MAAM,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,GAAG,CAAC,CAAC;IACxE,MAAM,gBAAgB,GAAG,IAAA,qBAAS,EAAC,WAAW,CAAC,CAAC;IAChD,MAAM,QAAQ,GAAG,IAAA,2BAAkB,EAAC,IAAI,CAAC,CAAC;IAC1C,MAAM,WAAW,GAAG,GAAG,QAAQ,CAAC,OAAO,IAAI,gBAAgB,EAAE,CAAC;IAC9D,MAAM,UAAU,GAAG,GAAG,QAAQ,CAAC,OAAO,IAAI,gBAAgB,MAAM,CAAC;IACjE,MAAM,wBAAwB,GAAG,GAAG,QA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ACpC,CAAC;YACF,MAAM,IAAA,iBAAM,EAAC,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC,MAAc,EAAE,EAAE;gBACjD,8CAA8C;gBAC9C,2DAA2D;gBAC3D,OAAO,CAAC,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;YAC9B,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AAEF,kBAAe,iCAAyB,CAAC","sourcesContent":["import {\n addDependenciesToPackageJson,\n formatFiles,\n generateFiles,\n getWorkspaceLayout,\n installPackagesTask,\n joinPathFragments,\n names,\n offsetFromRoot,\n Tree,\n updateJson,\n} from \"@nx/devkit\";\nimport { Linter } from \"@nx/eslint\";\nimport { getRootTsConfigPathInTree } from \"@nx/js\";\nimport { getNpmScope } from \"@nx/js/src/utils/package-json/get-npm-scope\";\nimport { libraryGenerator } from \"@nx/react\";\nimport { Schema } from \"@nx/react/src/generators/library/schema\";\nimport { nonUiExtensionTypes, serverSideExtensionTypes } from \"@trackunit/iris-app-api\";\nimport { prompt } from \"enquirer\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { camelCase } from \"string-ts\";\nimport { Project, SyntaxKind, VariableDeclaration } from \"ts-morph\";\nimport { spaDependencies, testDependencies } from \"./dependencies\";\nimport { IrisAppExtensionGeneratorSchema } from \"./schema\";\n\ninterface NormalizedSchema extends IrisAppExtensionGeneratorSchema {\n projectName: string;\n projectRoot: string;\n projectDirectory: string;\n projectCamelcase: string;\n importPath: string;\n sourceRoot: string;\n dependencyDefinitionFile: string;\n}\n\nfunction normalizeOptions(tree: Tree, options: IrisAppExtensionGeneratorSchema): NormalizedSchema {\n const name = names(options.name).fileName;\n const projectDirectory = options.directory ? `${names(options.directory).fileName}/${name}` : name;\n const projectName = projectDirectory.replace(new RegExp(\"/\", \"g\"), \"-\");\n const projectCamelcase = camelCase(projectName);\n const wsLayout = getWorkspaceLayout(tree);\n const projectRoot = `${wsLayout.libsDir}/${projectDirectory}`;\n const sourceRoot = `${wsLayout.libsDir}/${projectDirectory}/src`;\n const dependencyDefinitionFile = `${wsLayout.libsDir}/${projectDirectory}/package.json`;\n\n const npmScope = getNpmScope(tree);\n if (!npmScope) {\n throw new Error(\"Could not find npm scope in package.json\");\n }\n const importPath = `@${npmScope}/${projectName}`;\n\n return {\n ...options,\n projectName,\n projectRoot,\n projectDirectory,\n projectCamelcase,\n importPath,\n sourceRoot,\n dependencyDefinitionFile,\n };\n}\n\n/**\n * Iris App Extension Generator.\n *\n * @param tree the nx tree\n * @param options the generator options\n * @returns { Promise<void> } void\n */\nexport const IrisAppExtensionGenerator = async function (tree: Tree, options: IrisAppExtensionGeneratorSchema) {\n const adjustedOptions = await updateAppName(tree, options);\n\n const normalizedOptions = normalizeOptions(tree, adjustedOptions);\n\n const templateOptions = {\n ...normalizedOptions,\n ...names(normalizedOptions.name),\n offsetFromRoot: offsetFromRoot(normalizedOptions.projectRoot),\n template: \"\",\n };\n const irisAppExtensionType = normalizedOptions.type;\n\n if (!tree.exists(`${getWorkspaceLayout(tree).appsDir}/${normalizedOptions.app}`)) {\n throw new Error(\n `The app does not exist: ${getWorkspaceLayout(tree).appsDir}/${\n normalizedOptions.app\n } make sure you enter the right app name`\n );\n }\n\n const manifestPath = `${getWorkspaceLayout(tree).appsDir}/${normalizedOptions.app}/iris-app-manifest.ts`;\n if (!tree.exists(manifestPath)) {\n throw new Error(\n `The app does not have an iris-app-manifest.ts: ${manifestPath} make sure you enter the right app name, which has an iris-app-manifest.ts`\n );\n }\n\n if (normalizedOptions.updatePackageJson) {\n addDependenciesToPackageJson(\n tree,\n {},\n {\n ...spaDependencies,\n ...testDependencies,\n }\n );\n }\n\n const schema: Schema = {\n name: normalizedOptions.projectName,\n style: \"none\",\n skipFormat: false,\n strict: true,\n unitTestRunner: \"jest\",\n linter: Linter.EsLint,\n routing: false,\n directory: normalizedOptions.projectRoot,\n skipTsConfig: false,\n skipPackageJson: true,\n };\n\n await libraryGenerator(tree, schema);\n\n generateFiles(\n tree,\n path.join(__dirname, \"files\", irisAppExtensionType),\n normalizedOptions.projectRoot,\n templateOptions\n );\n\n if (!nonUiExtensionTypes.includes(irisAppExtensionType)) {\n generateFiles(tree, path.join(__dirname, \"files\", \"react-app\"), normalizedOptions.projectRoot, templateOptions);\n generateFiles(tree, path.join(__dirname, \"files\", \"preset\"), \"/\", templateOptions);\n }\n\n const rootTsConfigPath = getRootTsConfigPathInTree(tree);\n if (!rootTsConfigPath) {\n throw new Error(\"Could not find root tsconfig.json\");\n }\n updateJson(tree, rootTsConfigPath, tsConfigBase => {\n // For server side extension types, we need to add deno types to the tsconfig and make Typescript accept Deno import syntax\n if (serverSideExtensionTypes.includes(irisAppExtensionType)) {\n tsConfigBase.compilerOptions = {\n ...tsConfigBase.compilerOptions,\n types: [\"node\"],\n esModuleInterop: true,\n };\n }\n\n tsConfigBase.compilerOptions.paths[normalizedOptions.importPath] = [\n path.join(normalizedOptions.projectRoot, \"extension-manifest.ts\"),\n ];\n return tsConfigBase;\n });\n\n // Add working serve target to the project.json for DENO extensions\n if (serverSideExtensionTypes.includes(irisAppExtensionType)) {\n updateJson(tree, joinPathFragments(normalizedOptions.projectRoot, \"project.json\"), projectJson => {\n projectJson.targets.serve = {\n executor: \"@nx/js:node\",\n options: {\n buildTarget: `${normalizedOptions.projectName}:build`,\n inspect: true,\n },\n configurations: {\n breakOnStart: {\n inspect: \"inspect-brk\",\n },\n },\n };\n projectJson.targets.build = {\n executor: \"@nx/esbuild:esbuild\",\n outputs: [\"{options.outputPath}\"],\n defaultConfiguration: \"production\",\n options: {\n platform: \"node\",\n outputPath: `dist/${normalizedOptions.projectRoot}`,\n format: [\"cjs\"],\n bundle: true,\n thirdParty: true,\n external: [],\n main: `${normalizedOptions.sourceRoot}/index.ts`,\n tsConfig: `libs/${normalizedOptions.projectDirectory}/tsconfig.lib.json`,\n esbuildOptions: {\n sourcemap: true,\n outExtension: {\n \".js\": \".js\",\n },\n },\n configurations: {\n development: {},\n production: {\n esbuildOptions: {\n sourcemap: false,\n outExtension: {\n \".js\": \".js\",\n },\n },\n },\n },\n },\n };\n return projectJson;\n });\n }\n\n //TODO: Change the following to update the manifest in the virtual Tree - not on the file system.\n const project = new Project({\n tsConfigFilePath: `${getWorkspaceLayout(tree).appsDir}/${normalizedOptions.app}/tsconfig.app.json`,\n });\n\n const manifest = project.getSourceFileOrThrow(manifestPath);\n\n manifest.addImportDeclaration({\n moduleSpecifier: normalizedOptions.importPath,\n defaultImport: normalizedOptions.projectCamelcase,\n });\n\n // Get the default export symbol from the manifest\n const defaultExportSymbol = manifest.getDefaultExportSymbolOrThrow();\n\n // Get the aliased symbol if the default export is an alias\n const aliasedSymbol = defaultExportSymbol.getAliasedSymbol() || defaultExportSymbol;\n\n // Get the declaration of the aliased symbol\n const declaration = aliasedSymbol.getDeclarations()[0];\n\n if (!VariableDeclaration.isVariableDeclaration(declaration)) {\n throw new Error(\"Expected variable declaration\");\n }\n const irisAppManifestObject = declaration.getInitializer()?.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n if (!irisAppManifestObject) {\n throw new Error(`irisAppManifest not exported from the file: ${manifestPath}`);\n }\n // Find the extensions property within the irisAppManifest object\n const extensionsProperty = irisAppManifestObject.getPropertyOrThrow(\"extensions\");\n\n if (extensionsProperty.getKind() === SyntaxKind.PropertyAssignment) {\n const extensionsArray = extensionsProperty.getFirstChildByKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n extensionsArray.addElement(`${normalizedOptions.projectCamelcase}`);\n }\n\n await manifest.save();\n\n if (!serverSideExtensionTypes.includes(irisAppExtensionType)) {\n tree.delete(joinPathFragments(normalizedOptions.projectRoot, \"src\", \"index.ts\"));\n }\n\n updateJson(tree, joinPathFragments(normalizedOptions.projectRoot, \"tsconfig.spec.json\"), tsConfigSpec => {\n // extension-manifest.ts is a build time file, so we only need to include it in the spec file for type/lint checking\n tsConfigSpec.include = [...tsConfigSpec.include, \"**/jest.setup.ts*\", \"extension-manifest.ts\"];\n return tsConfigSpec;\n });\n\n await formatFiles(tree);\n installPackagesTask(tree, true);\n return () => {\n // eslint-disable-next-line no-console\n console.log(\"🥳 Successfully created an app extensions and it is already added to the Iris App!\");\n };\n};\nconst updateAppName = async (tree: Tree, options: IrisAppExtensionGeneratorSchema) => {\n if (!options.app) {\n const folders = fs\n .readdirSync(getWorkspaceLayout(tree).appsDir, { withFileTypes: true })\n .filter(item => item.isDirectory());\n\n const tileApps: Array<string> = [];\n\n folders.forEach(folder => {\n const irisAppManifest = fs\n .readdirSync(`${getWorkspaceLayout(tree).appsDir}/${folder.name}`, { withFileTypes: true })\n .find(item => item.name === \"iris-app-manifest.ts\");\n\n if (irisAppManifest) {\n tileApps.push(folder.name);\n } else {\n const subFolders = fs\n .readdirSync(path.join(getWorkspaceLayout(tree).appsDir, folder.name), { withFileTypes: true })\n .filter(item => item.isDirectory());\n subFolders.forEach(subFolder => {\n const subDirIrisAppManifest = fs\n .readdirSync(`${getWorkspaceLayout(tree).appsDir}/${folder.name}/${subFolder.name}`, {\n withFileTypes: true,\n })\n .find(item => item.name === \"iris-app-manifest.ts\");\n\n if (subDirIrisAppManifest) {\n tileApps.push(path.join(folder.name, subFolder.name));\n }\n });\n }\n });\n\n if (tileApps.length === 1) {\n options.app = tileApps[0] || \"<Missing iris app name>\";\n } else if (tileApps.length === 0) {\n throw new Error(\"Please add an iris-app using: nx g @trackunit/iris-app:create \");\n } else {\n const promptObject = {\n name: \"app\",\n message: \"Select the iris app that this extension should belong to:\",\n type: \"autocomplete\",\n choices: tileApps.map(item => item),\n };\n await prompt(promptObject).then((values: object) => {\n // @ts-ignore - suppressImplicitAnyIndexErrors\n // eslint-disable-next-line @typescript-eslint/dot-notation\n options.app = values[\"app\"];\n });\n }\n }\n return options;\n};\n\nexport default IrisAppExtensionGenerator;\n"]}
1
+ {"version":3,"file":"generator.js","sourceRoot":"","sources":["../../../../../../../libs/iris-app-sdk/iris-app/src/generators/ext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AAE;wBACnF,aAAa,EAAE,IAAI;qBACpB,CAAC;yBACD,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC,IAAI,KAAK,sBAAsB,CAAC,CAAC;oBAEtD,IAAI,qBAAqB,EAAE,CAAC;wBAC1B,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,EAAE,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC;oBACxD,CAAC;gBACH,CAAC,CAAC,CAAC;YACL,CAAC;QACH,CAAC,CAAC,CAAC;QAEH,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC1B,OAAO,CAAC,GAAG,GAAG,QAAQ,CAAC,CAAC,CAAC,IAAI,yBAAyB,CAAC;QACzD,CAAC;aAAM,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACjC,MAAM,IAAI,KAAK,CAAC,gEAAgE,CAAC,CAAC;QACpF,CAAC;aAAM,CAAC;YACN,MAAM,YAAY,GAAG;gBACnB,IAAI,EAAE,KAAK;gBACX,OAAO,EAAE,2DAA2D;gBACpE,IAAI,EAAE,cAAc;gBACpB,OAAO,EAAE,QAAQ,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,IAAI,CAAC;aACpC,CAAC;YACF,MAAM,IAAA,iBAAM,EAAC,YAAY,CAAC,CAAC,IAAI,CAAC,CAAC,MAAc,EAAE,EAAE;gBACjD,8CAA8C;gBAC9C,2DAA2D;gBAC3D,OAAO,CAAC,GAAG,GAAG,MAAM,CAAC,KAAK,CAAC,CAAC;YAC9B,CAAC,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AAEF,kBAAe,iCAAyB,CAAC","sourcesContent":["import {\n addDependenciesToPackageJson,\n formatFiles,\n generateFiles,\n getWorkspaceLayout,\n installPackagesTask,\n joinPathFragments,\n names,\n offsetFromRoot,\n Tree,\n updateJson,\n} from \"@nx/devkit\";\nimport { Linter } from \"@nx/eslint\";\nimport { getRootTsConfigPathInTree } from \"@nx/js\";\nimport { getNpmScope } from \"@nx/js/src/utils/package-json/get-npm-scope\";\nimport { libraryGenerator } from \"@nx/react\";\nimport { Schema } from \"@nx/react/src/generators/library/schema\";\nimport { nonUiExtensionTypes, serverSideExtensionTypes } from \"@trackunit/iris-app-api\";\nimport { prompt } from \"enquirer\";\nimport * as fs from \"fs\";\nimport * as path from \"path\";\nimport { camelCase } from \"string-ts\";\nimport { Project, SyntaxKind, VariableDeclaration } from \"ts-morph\";\nimport { addRequireStatement, addSpreadAssignment } from \"../../utils/ast/astUtils\";\nimport { spaDependencies, testDependencies } from \"./dependencies\";\nimport { IrisAppExtensionGeneratorSchema } from \"./schema\";\n\ninterface NormalizedSchema extends IrisAppExtensionGeneratorSchema {\n projectName: string;\n projectRoot: string;\n projectDirectory: string;\n projectCamelcase: string;\n importPath: string;\n sourceRoot: string;\n dependencyDefinitionFile: string;\n}\n\nfunction normalizeOptions(tree: Tree, options: IrisAppExtensionGeneratorSchema): NormalizedSchema {\n const name = names(options.name).fileName;\n const projectDirectory = options.directory ? `${names(options.directory).fileName}/${name}` : name;\n const projectName = projectDirectory.replace(new RegExp(\"/\", \"g\"), \"-\");\n const projectCamelcase = camelCase(projectName);\n const wsLayout = getWorkspaceLayout(tree);\n const projectRoot = `${wsLayout.libsDir}/${projectDirectory}`;\n const sourceRoot = `${wsLayout.libsDir}/${projectDirectory}/src`;\n const dependencyDefinitionFile = `${wsLayout.libsDir}/${projectDirectory}/package.json`;\n\n const npmScope = getNpmScope(tree);\n if (!npmScope) {\n throw new Error(\"Could not find npm scope in package.json\");\n }\n const importPath = `@${npmScope}/${projectName}`;\n\n return {\n ...options,\n projectName,\n projectRoot,\n projectDirectory,\n projectCamelcase,\n importPath,\n sourceRoot,\n dependencyDefinitionFile,\n };\n}\n\n/**\n * Ensures that jest.preset.js exists and includes the required @trackunit/react-test-setup preset.\n * If the file doesn't exist, creates it. If it exists but doesn't include the preset, updates it.\n */\nexport function ensureJestPresetConfiguration(tree: Tree, templateOptions?: object): void {\n const jestPresetPath = \"jest.preset.js\";\n\n if (!tree.exists(jestPresetPath)) {\n // File doesn't exist, generate it using the template\n generateFiles(tree, path.join(__dirname, \"files\", \"preset\"), \"/\", templateOptions || {});\n return;\n }\n\n // File exists, use AST utilities for reliable manipulation\n let currentContent = tree.read(jestPresetPath, \"utf-8\");\n if (!currentContent) {\n throw new Error(`Could not read ${jestPresetPath}`);\n }\n\n // Extract variable name from existing import if it exists\n let presetVariableName = \"irisPreset\"; // default name\n const existingImportMatch = currentContent.match(\n /const\\s+(\\w+)\\s*=\\s*require\\([\"']@trackunit\\/react-test-setup\\/preset[\"']\\)/\n );\n if (existingImportMatch && existingImportMatch[1]) {\n presetVariableName = existingImportMatch[1];\n }\n\n // Add the require statement if it doesn't exist\n currentContent = addRequireStatement(currentContent, presetVariableName, \"@trackunit/react-test-setup/preset\");\n\n // Add the spread assignment to the module.exports object\n currentContent = addSpreadAssignment(currentContent, presetVariableName);\n\n // Write the updated content back to the tree\n tree.write(jestPresetPath, currentContent);\n}\n\n/**\n * Iris App Extension Generator.\n *\n * @param tree the nx tree\n * @param options the generator options\n * @returns { Promise<void> } void\n */\nexport const IrisAppExtensionGenerator = async function (tree: Tree, options: IrisAppExtensionGeneratorSchema) {\n const adjustedOptions = await updateAppName(tree, options);\n\n const normalizedOptions = normalizeOptions(tree, adjustedOptions);\n\n const templateOptions = {\n ...normalizedOptions,\n ...names(normalizedOptions.name),\n offsetFromRoot: offsetFromRoot(normalizedOptions.projectRoot),\n template: \"\",\n };\n const irisAppExtensionType = normalizedOptions.type;\n\n if (!tree.exists(`${getWorkspaceLayout(tree).appsDir}/${normalizedOptions.app}`)) {\n throw new Error(\n `The app does not exist: ${getWorkspaceLayout(tree).appsDir}/${\n normalizedOptions.app\n } make sure you enter the right app name`\n );\n }\n\n const manifestPath = `${getWorkspaceLayout(tree).appsDir}/${normalizedOptions.app}/iris-app-manifest.ts`;\n if (!tree.exists(manifestPath)) {\n throw new Error(\n `The app does not have an iris-app-manifest.ts: ${manifestPath} make sure you enter the right app name, which has an iris-app-manifest.ts`\n );\n }\n\n if (normalizedOptions.updatePackageJson) {\n addDependenciesToPackageJson(\n tree,\n {},\n {\n ...spaDependencies,\n ...testDependencies,\n }\n );\n }\n\n const schema: Schema = {\n name: normalizedOptions.projectName,\n style: \"none\",\n skipFormat: false,\n strict: true,\n unitTestRunner: \"jest\",\n linter: Linter.EsLint,\n routing: false,\n directory: normalizedOptions.projectRoot,\n skipTsConfig: false,\n skipPackageJson: true,\n };\n\n await libraryGenerator(tree, schema);\n\n generateFiles(\n tree,\n path.join(__dirname, \"files\", irisAppExtensionType),\n normalizedOptions.projectRoot,\n templateOptions\n );\n\n if (!nonUiExtensionTypes.includes(irisAppExtensionType)) {\n generateFiles(tree, path.join(__dirname, \"files\", \"react-app\"), normalizedOptions.projectRoot, templateOptions);\n if (normalizedOptions.extendJestPreset) {\n ensureJestPresetConfiguration(tree, templateOptions);\n }\n }\n\n const rootTsConfigPath = getRootTsConfigPathInTree(tree);\n if (!rootTsConfigPath) {\n throw new Error(\"Could not find root tsconfig.json\");\n }\n updateJson(tree, rootTsConfigPath, tsConfigBase => {\n // For server side extension types, we need to add deno types to the tsconfig and make Typescript accept Deno import syntax\n if (serverSideExtensionTypes.includes(irisAppExtensionType)) {\n tsConfigBase.compilerOptions = {\n ...tsConfigBase.compilerOptions,\n types: [\"node\"],\n esModuleInterop: true,\n };\n }\n\n tsConfigBase.compilerOptions.paths[normalizedOptions.importPath] = [\n path.join(normalizedOptions.projectRoot, \"extension-manifest.ts\"),\n ];\n return tsConfigBase;\n });\n\n // Add working serve target to the project.json for DENO extensions\n if (serverSideExtensionTypes.includes(irisAppExtensionType)) {\n updateJson(tree, joinPathFragments(normalizedOptions.projectRoot, \"project.json\"), projectJson => {\n projectJson.targets.serve = {\n executor: \"@nx/js:node\",\n options: {\n buildTarget: `${normalizedOptions.projectName}:build`,\n inspect: true,\n },\n configurations: {\n breakOnStart: {\n inspect: \"inspect-brk\",\n },\n },\n };\n projectJson.targets.build = {\n executor: \"@nx/esbuild:esbuild\",\n outputs: [\"{options.outputPath}\"],\n defaultConfiguration: \"production\",\n options: {\n platform: \"node\",\n outputPath: `dist/${normalizedOptions.projectRoot}`,\n format: [\"cjs\"],\n bundle: true,\n thirdParty: true,\n external: [],\n main: `${normalizedOptions.sourceRoot}/index.ts`,\n tsConfig: `libs/${normalizedOptions.projectDirectory}/tsconfig.lib.json`,\n esbuildOptions: {\n sourcemap: true,\n outExtension: {\n \".js\": \".js\",\n },\n },\n configurations: {\n development: {},\n production: {\n esbuildOptions: {\n sourcemap: false,\n outExtension: {\n \".js\": \".js\",\n },\n },\n },\n },\n },\n };\n return projectJson;\n });\n }\n\n //TODO: Change the following to update the manifest in the virtual Tree - not on the file system.\n const project = new Project({\n tsConfigFilePath: `${getWorkspaceLayout(tree).appsDir}/${normalizedOptions.app}/tsconfig.app.json`,\n });\n\n const manifest = project.getSourceFileOrThrow(manifestPath);\n\n manifest.addImportDeclaration({\n moduleSpecifier: normalizedOptions.importPath,\n defaultImport: normalizedOptions.projectCamelcase,\n });\n\n // Get the default export symbol from the manifest\n const defaultExportSymbol = manifest.getDefaultExportSymbolOrThrow();\n\n // Get the aliased symbol if the default export is an alias\n const aliasedSymbol = defaultExportSymbol.getAliasedSymbol() || defaultExportSymbol;\n\n // Get the declaration of the aliased symbol\n const declaration = aliasedSymbol.getDeclarations()[0];\n\n if (!VariableDeclaration.isVariableDeclaration(declaration)) {\n throw new Error(\"Expected variable declaration\");\n }\n const irisAppManifestObject = declaration.getInitializer()?.asKindOrThrow(SyntaxKind.ObjectLiteralExpression);\n\n if (!irisAppManifestObject) {\n throw new Error(`irisAppManifest not exported from the file: ${manifestPath}`);\n }\n // Find the extensions property within the irisAppManifest object\n const extensionsProperty = irisAppManifestObject.getPropertyOrThrow(\"extensions\");\n\n if (extensionsProperty.getKind() === SyntaxKind.PropertyAssignment) {\n const extensionsArray = extensionsProperty.getFirstChildByKindOrThrow(SyntaxKind.ArrayLiteralExpression);\n extensionsArray.addElement(`${normalizedOptions.projectCamelcase}`);\n }\n\n await manifest.save();\n\n if (!serverSideExtensionTypes.includes(irisAppExtensionType)) {\n tree.delete(joinPathFragments(normalizedOptions.projectRoot, \"src\", \"index.ts\"));\n }\n\n updateJson(tree, joinPathFragments(normalizedOptions.projectRoot, \"tsconfig.spec.json\"), tsConfigSpec => {\n // extension-manifest.ts is a build time file, so we only need to include it in the spec file for type/lint checking\n tsConfigSpec.include = [...tsConfigSpec.include, \"**/jest.setup.ts*\", \"extension-manifest.ts\"];\n return tsConfigSpec;\n });\n\n await formatFiles(tree);\n installPackagesTask(tree, true);\n return () => {\n // eslint-disable-next-line no-console\n console.log(\"🥳 Successfully created an app extensions and it is already added to the Iris App!\");\n };\n};\nconst updateAppName = async (tree: Tree, options: IrisAppExtensionGeneratorSchema) => {\n if (!options.app) {\n const folders = fs\n .readdirSync(getWorkspaceLayout(tree).appsDir, { withFileTypes: true })\n .filter(item => item.isDirectory());\n\n const tileApps: Array<string> = [];\n\n folders.forEach(folder => {\n const irisAppManifest = fs\n .readdirSync(`${getWorkspaceLayout(tree).appsDir}/${folder.name}`, { withFileTypes: true })\n .find(item => item.name === \"iris-app-manifest.ts\");\n\n if (irisAppManifest) {\n tileApps.push(folder.name);\n } else {\n const subFolders = fs\n .readdirSync(path.join(getWorkspaceLayout(tree).appsDir, folder.name), { withFileTypes: true })\n .filter(item => item.isDirectory());\n subFolders.forEach(subFolder => {\n const subDirIrisAppManifest = fs\n .readdirSync(`${getWorkspaceLayout(tree).appsDir}/${folder.name}/${subFolder.name}`, {\n withFileTypes: true,\n })\n .find(item => item.name === \"iris-app-manifest.ts\");\n\n if (subDirIrisAppManifest) {\n tileApps.push(path.join(folder.name, subFolder.name));\n }\n });\n }\n });\n\n if (tileApps.length === 1) {\n options.app = tileApps[0] || \"<Missing iris app name>\";\n } else if (tileApps.length === 0) {\n throw new Error(\"Please add an iris-app using: nx g @trackunit/iris-app:create \");\n } else {\n const promptObject = {\n name: \"app\",\n message: \"Select the iris app that this extension should belong to:\",\n type: \"autocomplete\",\n choices: tileApps.map(item => item),\n };\n await prompt(promptObject).then((values: object) => {\n // @ts-ignore - suppressImplicitAnyIndexErrors\n // eslint-disable-next-line @typescript-eslint/dot-notation\n options.app = values[\"app\"];\n });\n }\n }\n return options;\n};\n\nexport default IrisAppExtensionGenerator;\n"]}
@@ -16,4 +16,5 @@ export interface IrisAppExtensionGeneratorSchema {
16
16
  | "LIFECYCLE_EXTENSION"
17
17
  | "SERVERLESS_FUNCTION_EXTENSION"
18
18
  | "AI_AGENT_EXTENSION";
19
+ extendJestPreset?: boolean;
19
20
  }
@@ -59,6 +59,11 @@
59
59
  "SERVERLESS_FUNCTION_EXTENSION"
60
60
  ]
61
61
  }
62
+ },
63
+ "extendJestPreset": {
64
+ "type": "boolean",
65
+ "description": "If the root jest.preset.js should be extended with the Iris app preset",
66
+ "default": true
62
67
  }
63
68
  },
64
69
  "required": ["name", "directory", "type"]
@@ -15,3 +15,18 @@ export declare function removePropertyWithName(fileContent: string, ...propertyN
15
15
  * @param {string | string[]} propertyValue - the value of the property to add
16
16
  */
17
17
  export declare function addPropertyWithName(fileContent: string, propertyName: string, propertyValue: string | Array<string> | Record<string, string>): string;
18
+ /**
19
+ * This function adds a spread assignment to an object literal.
20
+ *
21
+ * @param {string} fileContent - the source code as text
22
+ * @param {string} variableName - the name of the variable to spread
23
+ */
24
+ export declare function addSpreadAssignment(fileContent: string, variableName: string): string;
25
+ /**
26
+ * This function adds a require statement to a file after existing require statements.
27
+ *
28
+ * @param {string} fileContent - the source code as text
29
+ * @param {string} variableName - the name of the variable to assign to
30
+ * @param {string} modulePath - the module path to require
31
+ */
32
+ export declare function addRequireStatement(fileContent: string, variableName: string, modulePath: string): string;
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.removePropertyWithName = removePropertyWithName;
4
4
  exports.addPropertyWithName = addPropertyWithName;
5
+ exports.addSpreadAssignment = addSpreadAssignment;
6
+ exports.addRequireStatement = addRequireStatement;
5
7
  const tslib_1 = require("tslib");
6
8
  const shared_utils_1 = require("@trackunit/shared-utils");
7
9
  const tsquery_1 = require("@phenomnomnominal/tsquery");
@@ -68,6 +70,77 @@ function addPropertyWithName(fileContent, propertyName, propertyValue) {
68
70
  });
69
71
  return ts.createPrinter().printFile(updatedSourceFile);
70
72
  }
73
+ /**
74
+ * This function adds a spread assignment to an object literal.
75
+ *
76
+ * @param {string} fileContent - the source code as text
77
+ * @param {string} variableName - the name of the variable to spread
78
+ */
79
+ function addSpreadAssignment(fileContent, variableName) {
80
+ const sourceFile = tsquery_1.tsquery.ast(fileContent);
81
+ // First check if the spread already exists
82
+ const existingSpreads = (0, tsquery_1.tsquery)(sourceFile, "SpreadAssignment");
83
+ const hasExistingSpread = existingSpreads.some(spread => {
84
+ if (ts.isSpreadAssignment(spread)) {
85
+ return spread.expression.getText() === variableName;
86
+ }
87
+ return false;
88
+ });
89
+ if (hasExistingSpread) {
90
+ return fileContent; // Already has the spread, no changes needed
91
+ }
92
+ const updatedSourceFile = tsquery_1.tsquery.map(sourceFile, "ObjectLiteralExpression", node => {
93
+ if (ts.isObjectLiteralExpression(node)) {
94
+ // Add the spread assignment to the object literal
95
+ const spreadAssignment = ts.factory.createSpreadAssignment(ts.factory.createIdentifier(variableName));
96
+ const updatedProperties = [...node.properties, spreadAssignment];
97
+ return ts.factory.createObjectLiteralExpression(updatedProperties, true);
98
+ }
99
+ return node;
100
+ });
101
+ return ts.createPrinter().printFile(updatedSourceFile);
102
+ }
103
+ /**
104
+ * This function adds a require statement to a file after existing require statements.
105
+ *
106
+ * @param {string} fileContent - the source code as text
107
+ * @param {string} variableName - the name of the variable to assign to
108
+ * @param {string} modulePath - the module path to require
109
+ */
110
+ function addRequireStatement(fileContent, variableName, modulePath) {
111
+ const sourceFile = tsquery_1.tsquery.ast(fileContent);
112
+ // Check if the require statement already exists
113
+ const existingRequires = (0, tsquery_1.tsquery)(sourceFile, "CallExpression");
114
+ const hasExistingRequire = existingRequires.some(call => {
115
+ if (ts.isCallExpression(call) &&
116
+ ts.isIdentifier(call.expression) &&
117
+ call.expression.text === "require" &&
118
+ call.arguments.length > 0) {
119
+ const firstArg = call.arguments[0];
120
+ if (firstArg && ts.isStringLiteral(firstArg)) {
121
+ return firstArg.text === modulePath;
122
+ }
123
+ }
124
+ return false;
125
+ });
126
+ if (hasExistingRequire) {
127
+ return fileContent; // Already has the require, no changes needed
128
+ }
129
+ // Find all variable statements with require calls
130
+ const requireStatements = (0, tsquery_1.tsquery)(sourceFile, "VariableStatement")
131
+ .filter(stmt => stmt.getText().includes("require("));
132
+ const requireStatement = `const ${variableName} = require("${modulePath}").default;`;
133
+ if (requireStatements.length > 0) {
134
+ // Add after the last require statement
135
+ const lastRequire = requireStatements[requireStatements.length - 1];
136
+ if (lastRequire) {
137
+ const lastRequireEnd = lastRequire.getEnd();
138
+ return fileContent.slice(0, lastRequireEnd) + '\n' + requireStatement + fileContent.slice(lastRequireEnd);
139
+ }
140
+ }
141
+ // Add at the beginning if no require statements found
142
+ return requireStatement + '\n' + fileContent;
143
+ }
71
144
  function createObjectLiteralElementLike(obj) {
72
145
  const properties = [];
73
146
  for (const [key, value] of (0, shared_utils_1.objectEntries)(obj)) {
@@ -1 +1 @@
1
- {"version":3,"file":"astUtils.js","sourceRoot":"","sources":["../../../../../../../libs/iris-app-sdk/iris-app/src/utils/ast/astUtils.ts"],"names":[],"mappings":";;AAWA,wDAiBC;AAUD,kDAwCC;;AA9ED,0DAAwD;AACxD,uDAAoD;AACpD,uDAAiC;AAEjC;;;;;;GAMG;AACH,SAAgB,sBAAsB,CAAC,WAAmB,EAAE,GAAG,aAA4B;IACzF,MAAM,UAAU,GAAG,iBAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC5C,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C,EAAE,CAAC;QAC9C,UAAU,CAAC,IAAI,CACb,EAAE,CAAC,OAAO,CAAC,wBAAwB,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC,CAChH,CAAC;IACJ,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { objectEntries } from \"@trackunit/shared-utils\";\nimport { tsquery } from \"@phenomnomnominal/tsquery\";\nimport * as ts from \"typescript\";\n\n/**\n * This function removes a property with a given name from an object literal\n * provided as a text string.\n *\n * @param {string} fileContent The source code as text\n * @param {string} propertyNames The properties to remove from the object\n */\nexport function removePropertyWithName(fileContent: string, ...propertyNames: Array<string>) {\n const sourceFile = tsquery.ast(fileContent);\n const updatedSourceFile = tsquery.map(sourceFile, \"ObjectLiteralExpression\", node => {\n if (ts.isObjectLiteralExpression(node)) {\n // Filter out the given property\n const updatedProperties = node.properties.filter(property => {\n return !(\n ts.isPropertyAssignment(property) &&\n ts.isIdentifier(property.name) &&\n propertyNames.includes(property.name.text)\n );\n });\n return ts.factory.createObjectLiteralExpression(updatedProperties, true);\n }\n return node;\n });\n return ts.createPrinter().printFile(updatedSourceFile);\n}\n\n/**\n * This function adds a new property with a given name and value to an object literal\n * provided as a text string.\n *\n * @param {string} fileContent - the source code as text\n * @param {string} propertyName - the name of the property to add\n * @param {string | string[]} propertyValue - the value of the property to add\n */\nexport function addPropertyWithName(\n fileContent: string,\n propertyName: string,\n propertyValue: string | Array<string> | Record<string, string>\n) {\n const sourceFile = tsquery.ast(fileContent);\n const updatedSourceFile = tsquery.map(sourceFile, \"ObjectLiteralExpression\", node => {\n if (ts.isObjectLiteralExpression(node)) {\n // Add a new property to the object literal\n let updatedProperties;\n if (typeof propertyValue === \"string\") {\n updatedProperties = [\n ...node.properties,\n ts.factory.createPropertyAssignment(\n ts.factory.createIdentifier(propertyName),\n ts.factory.createStringLiteral(propertyValue)\n ),\n ];\n } else if (Array.isArray(propertyValue)) {\n const arrayLiteral = ts.factory.createArrayLiteralExpression(\n propertyValue.map(value => ts.factory.createStringLiteral(value))\n );\n updatedProperties = [\n ...node.properties,\n ts.factory.createPropertyAssignment(ts.factory.createIdentifier(propertyName), arrayLiteral),\n ];\n } else if (typeof propertyValue === \"object\") {\n updatedProperties = [\n ...node.properties,\n ts.factory.createPropertyAssignment(\n ts.factory.createIdentifier(propertyName),\n ts.factory.createObjectLiteralExpression(createObjectLiteralElementLike(propertyValue))\n ),\n ];\n }\n return ts.factory.createObjectLiteralExpression(updatedProperties, true);\n }\n return node;\n });\n return ts.createPrinter().printFile(updatedSourceFile);\n}\n\nfunction createObjectLiteralElementLike(obj: Record<string, string>): Array<ts.ObjectLiteralElementLike> {\n const properties: Array<ts.ObjectLiteralElementLike> = [];\n for (const [key, value] of objectEntries(obj)) {\n properties.push(\n ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(key), ts.factory.createStringLiteral(value))\n );\n }\n return properties;\n}\n"]}
1
+ {"version":3,"file":"astUtils.js","sourceRoot":"","sources":["../../../../../../../libs/iris-app-sdk/iris-app/src/utils/ast/astUtils.ts"],"names":[],"mappings":";;AAWA,wDAiBC;AAUD,kDAwCC;AAQD,kDA4BC;AASD,kDAwCC;;AAnKD,0DAAwD;AACxD,uDAAoD;AACpD,uDAAiC;AAEjC;;;;;;GAMG;AACH,SAAgB,sBAAsB,CAAC,WAAmB,EAAE,GAAG,aAA4B;IACzF,MAAM,UAAU,GAAG,iBAAO,CAAC,GAAG,CAAC,WAAW,CAAC,CAAC;IAC5C,MAAM,iBAAiB,GAAG,iBAAO,CAAC,GAAG,CAAC,UAAU,EAAE,yBAAyB,EAAE,IAAI,CAAC,EAAE;QAClF,IAAI,EAAE,CAAC,yBAAyB,CAAC,IAAI,CAAC,EAAE,CAAC;YACvC,gCAAgC;YAChC,MAAM,iBAAiB,GAAG,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,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IAC1D,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,IAAA,4BAAa,EAAC,GAAG,CAAC,EAAE,CAAC;QAC9C,UAAU,CAAC,IAAI,CACb,EAAE,CAAC,OAAO,CAAC,wBAAwB,CAAC,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,mBAAmB,CAAC,KAAK,CAAC,CAAC,CAChH,CAAC;IACJ,CAAC;IACD,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["import { objectEntries } from \"@trackunit/shared-utils\";\nimport { tsquery } from \"@phenomnomnominal/tsquery\";\nimport * as ts from \"typescript\";\n\n/**\n * This function removes a property with a given name from an object literal\n * provided as a text string.\n *\n * @param {string} fileContent The source code as text\n * @param {string} propertyNames The properties to remove from the object\n */\nexport function removePropertyWithName(fileContent: string, ...propertyNames: Array<string>) {\n const sourceFile = tsquery.ast(fileContent);\n const updatedSourceFile = tsquery.map(sourceFile, \"ObjectLiteralExpression\", node => {\n if (ts.isObjectLiteralExpression(node)) {\n // Filter out the given property\n const updatedProperties = node.properties.filter(property => {\n return !(\n ts.isPropertyAssignment(property) &&\n ts.isIdentifier(property.name) &&\n propertyNames.includes(property.name.text)\n );\n });\n return ts.factory.createObjectLiteralExpression(updatedProperties, true);\n }\n return node;\n });\n return ts.createPrinter().printFile(updatedSourceFile);\n}\n\n/**\n * This function adds a new property with a given name and value to an object literal\n * provided as a text string.\n *\n * @param {string} fileContent - the source code as text\n * @param {string} propertyName - the name of the property to add\n * @param {string | string[]} propertyValue - the value of the property to add\n */\nexport function addPropertyWithName(\n fileContent: string,\n propertyName: string,\n propertyValue: string | Array<string> | Record<string, string>\n) {\n const sourceFile = tsquery.ast(fileContent);\n const updatedSourceFile = tsquery.map(sourceFile, \"ObjectLiteralExpression\", node => {\n if (ts.isObjectLiteralExpression(node)) {\n // Add a new property to the object literal\n let updatedProperties;\n if (typeof propertyValue === \"string\") {\n updatedProperties = [\n ...node.properties,\n ts.factory.createPropertyAssignment(\n ts.factory.createIdentifier(propertyName),\n ts.factory.createStringLiteral(propertyValue)\n ),\n ];\n } else if (Array.isArray(propertyValue)) {\n const arrayLiteral = ts.factory.createArrayLiteralExpression(\n propertyValue.map(value => ts.factory.createStringLiteral(value))\n );\n updatedProperties = [\n ...node.properties,\n ts.factory.createPropertyAssignment(ts.factory.createIdentifier(propertyName), arrayLiteral),\n ];\n } else if (typeof propertyValue === \"object\") {\n updatedProperties = [\n ...node.properties,\n ts.factory.createPropertyAssignment(\n ts.factory.createIdentifier(propertyName),\n ts.factory.createObjectLiteralExpression(createObjectLiteralElementLike(propertyValue))\n ),\n ];\n }\n return ts.factory.createObjectLiteralExpression(updatedProperties, true);\n }\n return node;\n });\n return ts.createPrinter().printFile(updatedSourceFile);\n}\n\n/**\n * This function adds a spread assignment to an object literal.\n *\n * @param {string} fileContent - the source code as text\n * @param {string} variableName - the name of the variable to spread\n */\nexport function addSpreadAssignment(fileContent: string, variableName: string) {\n const sourceFile = tsquery.ast(fileContent);\n \n // First check if the spread already exists\n const existingSpreads = tsquery(sourceFile, \"SpreadAssignment\");\n const hasExistingSpread = existingSpreads.some(spread => {\n if (ts.isSpreadAssignment(spread)) {\n return spread.expression.getText() === variableName;\n }\n return false;\n });\n \n if (hasExistingSpread) {\n return fileContent; // Already has the spread, no changes needed\n }\n \n const updatedSourceFile = tsquery.map(sourceFile, \"ObjectLiteralExpression\", node => {\n if (ts.isObjectLiteralExpression(node)) {\n // Add the spread assignment to the object literal\n const spreadAssignment = ts.factory.createSpreadAssignment(\n ts.factory.createIdentifier(variableName)\n );\n const updatedProperties = [...node.properties, spreadAssignment];\n return ts.factory.createObjectLiteralExpression(updatedProperties, true);\n }\n return node;\n });\n return ts.createPrinter().printFile(updatedSourceFile);\n}\n\n/**\n * This function adds a require statement to a file after existing require statements.\n *\n * @param {string} fileContent - the source code as text\n * @param {string} variableName - the name of the variable to assign to\n * @param {string} modulePath - the module path to require\n */\nexport function addRequireStatement(fileContent: string, variableName: string, modulePath: string) {\n const sourceFile = tsquery.ast(fileContent);\n \n // Check if the require statement already exists\n const existingRequires = tsquery(sourceFile, \"CallExpression\");\n const hasExistingRequire = existingRequires.some(call => {\n if (ts.isCallExpression(call) && \n ts.isIdentifier(call.expression) && \n call.expression.text === \"require\" &&\n call.arguments.length > 0) {\n const firstArg = call.arguments[0];\n if (firstArg && ts.isStringLiteral(firstArg)) {\n return firstArg.text === modulePath;\n }\n }\n return false;\n });\n \n if (hasExistingRequire) {\n return fileContent; // Already has the require, no changes needed\n }\n \n // Find all variable statements with require calls\n const requireStatements = tsquery(sourceFile, \"VariableStatement\")\n .filter(stmt => stmt.getText().includes(\"require(\"));\n \n const requireStatement = `const ${variableName} = require(\"${modulePath}\").default;`;\n \n if (requireStatements.length > 0) {\n // Add after the last require statement\n const lastRequire = requireStatements[requireStatements.length - 1];\n if (lastRequire) {\n const lastRequireEnd = lastRequire.getEnd();\n \n return fileContent.slice(0, lastRequireEnd) + '\\n' + requireStatement + fileContent.slice(lastRequireEnd);\n }\n }\n \n // Add at the beginning if no require statements found\n return requireStatement + '\\n' + fileContent;\n}\n\nfunction createObjectLiteralElementLike(obj: Record<string, string>): Array<ts.ObjectLiteralElementLike> {\n const properties: Array<ts.ObjectLiteralElementLike> = [];\n for (const [key, value] of objectEntries(obj)) {\n properties.push(\n ts.factory.createPropertyAssignment(ts.factory.createStringLiteral(key), ts.factory.createStringLiteral(value))\n );\n }\n return properties;\n}\n"]}