proteum 1.0.2 → 2.0.0-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.
Files changed (185) hide show
  1. package/AGENTS.md +101 -0
  2. package/agents/codex/AGENTS.md +95 -0
  3. package/agents/codex/CODING_STYLE.md +71 -0
  4. package/agents/codex/agents.md.zip +0 -0
  5. package/agents/codex/client/AGENTS.md +102 -0
  6. package/agents/codex/client/pages/AGENTS.md +35 -0
  7. package/agents/codex/server/routes/AGENTS.md +12 -0
  8. package/agents/codex/server/services/AGENTS.md +137 -0
  9. package/agents/codex/tests/AGENTS.md +8 -0
  10. package/cli/app/config.ts +13 -11
  11. package/cli/app/index.ts +74 -82
  12. package/cli/bin.js +1 -1
  13. package/cli/commands/build.ts +51 -14
  14. package/cli/commands/check.ts +19 -0
  15. package/cli/commands/deploy/app.ts +4 -8
  16. package/cli/commands/deploy/web.ts +16 -20
  17. package/cli/commands/dev.ts +189 -64
  18. package/cli/commands/devEvents.ts +106 -0
  19. package/cli/commands/init.ts +63 -57
  20. package/cli/commands/lint.ts +21 -0
  21. package/cli/commands/refresh.ts +18 -0
  22. package/cli/commands/typecheck.ts +18 -0
  23. package/cli/compiler/client/identite.ts +80 -53
  24. package/cli/compiler/client/index.ts +139 -213
  25. package/cli/compiler/common/bundleAnalysis.ts +94 -0
  26. package/cli/compiler/common/clientManifest.ts +67 -0
  27. package/cli/compiler/common/controllers.ts +288 -0
  28. package/cli/compiler/common/files/autres.ts +7 -18
  29. package/cli/compiler/common/files/images.ts +40 -37
  30. package/cli/compiler/common/files/style.ts +11 -22
  31. package/cli/compiler/common/generatedRouteModules.ts +368 -0
  32. package/cli/compiler/common/index.ts +31 -65
  33. package/cli/compiler/common/loaders/forbid-ssr-import.js +13 -0
  34. package/cli/compiler/common/rspackAliases.ts +13 -0
  35. package/cli/compiler/common/scripts.ts +37 -0
  36. package/cli/compiler/index.ts +781 -230
  37. package/cli/compiler/server/index.ts +59 -75
  38. package/cli/compiler/writeIfChanged.ts +21 -0
  39. package/cli/index.ts +71 -72
  40. package/cli/paths.ts +51 -57
  41. package/cli/print.ts +17 -11
  42. package/cli/tsconfig.json +5 -4
  43. package/cli/utils/agents.ts +100 -0
  44. package/cli/utils/check.ts +71 -0
  45. package/cli/utils/index.ts +1 -3
  46. package/cli/utils/keyboard.ts +8 -25
  47. package/cli/utils/runProcess.ts +30 -0
  48. package/client/app/component.tsx +29 -29
  49. package/client/app/index.ts +36 -57
  50. package/client/app/service.ts +7 -12
  51. package/client/app.tsconfig.json +2 -2
  52. package/client/components/Dialog/Manager.ssr.tsx +40 -0
  53. package/client/components/Dialog/Manager.tsx +119 -150
  54. package/client/components/Dialog/status.tsx +3 -3
  55. package/client/components/index.ts +1 -1
  56. package/client/components/types.d.ts +1 -3
  57. package/client/dev/hmr.ts +65 -0
  58. package/client/global.d.ts +2 -2
  59. package/client/hooks.ts +6 -9
  60. package/client/index.ts +2 -1
  61. package/client/islands/index.ts +7 -0
  62. package/client/islands/useDeferredModule.ts +199 -0
  63. package/client/pages/_layout/index.tsx +4 -12
  64. package/client/pages/useHeader.tsx +14 -21
  65. package/client/router.ts +27 -0
  66. package/client/services/router/components/Link.tsx +34 -27
  67. package/client/services/router/components/Page.tsx +6 -14
  68. package/client/services/router/components/router.ssr.tsx +36 -0
  69. package/client/services/router/components/router.tsx +63 -83
  70. package/client/services/router/index.tsx +185 -220
  71. package/client/services/router/request/api.ts +97 -119
  72. package/client/services/router/request/history.ts +2 -2
  73. package/client/services/router/request/index.ts +13 -12
  74. package/client/services/router/request/multipart.ts +72 -62
  75. package/client/services/router/response/index.tsx +68 -61
  76. package/client/services/router/response/page.ts +28 -32
  77. package/client/utils/dom.ts +17 -33
  78. package/common/app/index.ts +3 -3
  79. package/common/data/chaines/index.ts +22 -23
  80. package/common/data/dates.ts +35 -70
  81. package/common/data/markdown.ts +42 -39
  82. package/common/dev/serverHotReload.ts +26 -0
  83. package/common/errors/index.tsx +110 -142
  84. package/common/router/contracts.ts +29 -0
  85. package/common/router/index.ts +89 -108
  86. package/common/router/layouts.ts +34 -47
  87. package/common/router/pageSetup.ts +50 -0
  88. package/common/router/register.ts +53 -24
  89. package/common/router/request/api.ts +30 -36
  90. package/common/router/request/index.ts +2 -8
  91. package/common/router/response/index.ts +8 -15
  92. package/common/router/response/page.ts +70 -58
  93. package/common/utils.ts +1 -1
  94. package/doc/TODO.md +1 -1
  95. package/eslint.js +62 -0
  96. package/package.json +14 -49
  97. package/prettier.config.cjs +9 -0
  98. package/scripts/cleanup-generated-controllers.ts +62 -0
  99. package/scripts/fix-reference-app-typing.ts +490 -0
  100. package/scripts/refactor-client-app-imports.ts +244 -0
  101. package/scripts/refactor-client-pages.ts +587 -0
  102. package/scripts/refactor-server-controllers.ts +470 -0
  103. package/scripts/refactor-server-runtime-aliases.ts +360 -0
  104. package/scripts/restore-client-app-import-files.ts +41 -0
  105. package/scripts/restore-files-from-git-head.ts +20 -0
  106. package/scripts/update-codex-agents.ts +35 -0
  107. package/server/app/commands.ts +35 -64
  108. package/server/app/container/config.ts +48 -59
  109. package/server/app/container/console/index.ts +202 -248
  110. package/server/app/container/index.ts +33 -71
  111. package/server/app/controller/index.ts +61 -0
  112. package/server/app/index.ts +39 -105
  113. package/server/app/service/container.ts +41 -42
  114. package/server/app/service/index.ts +120 -147
  115. package/server/context.ts +1 -1
  116. package/server/index.ts +25 -1
  117. package/server/services/auth/index.ts +75 -115
  118. package/server/services/auth/router/index.ts +31 -32
  119. package/server/services/auth/router/request.ts +14 -16
  120. package/server/services/cron/CronTask.ts +13 -26
  121. package/server/services/cron/index.ts +14 -36
  122. package/server/services/disks/driver.ts +40 -58
  123. package/server/services/disks/drivers/local/index.ts +79 -90
  124. package/server/services/disks/drivers/s3/index.ts +116 -163
  125. package/server/services/disks/index.ts +23 -38
  126. package/server/services/email/index.ts +45 -104
  127. package/server/services/email/utils.ts +14 -27
  128. package/server/services/fetch/index.ts +53 -85
  129. package/server/services/prisma/Facet.ts +39 -91
  130. package/server/services/prisma/index.ts +74 -110
  131. package/server/services/router/generatedRuntime.ts +29 -0
  132. package/server/services/router/http/index.ts +78 -73
  133. package/server/services/router/http/multipart.ts +19 -42
  134. package/server/services/router/index.ts +378 -365
  135. package/server/services/router/request/api.ts +26 -25
  136. package/server/services/router/request/index.ts +44 -51
  137. package/server/services/router/request/service.ts +7 -11
  138. package/server/services/router/request/validation/zod.ts +111 -148
  139. package/server/services/router/response/index.ts +110 -125
  140. package/server/services/router/response/mask/Filter.ts +31 -72
  141. package/server/services/router/response/mask/index.ts +8 -15
  142. package/server/services/router/response/mask/selecteurs.ts +11 -25
  143. package/server/services/router/response/page/clientManifest.ts +25 -0
  144. package/server/services/router/response/page/document.tsx +199 -127
  145. package/server/services/router/response/page/index.tsx +89 -94
  146. package/server/services/router/service.ts +13 -15
  147. package/server/services/schema/index.ts +17 -26
  148. package/server/services/schema/request.ts +19 -33
  149. package/server/services/schema/router/index.ts +8 -11
  150. package/server/services/security/encrypt/aes/index.ts +15 -35
  151. package/server/utils/slug.ts +29 -35
  152. package/skills/clean-project-code/SKILL.md +63 -0
  153. package/skills/clean-project-code/agents/openai.yaml +4 -0
  154. package/tsconfig.common.json +4 -3
  155. package/tsconfig.json +4 -1
  156. package/types/aliases.d.ts +17 -21
  157. package/types/controller-input.test.ts +48 -0
  158. package/types/express-extra.d.ts +6 -0
  159. package/types/global/constants.d.ts +13 -0
  160. package/types/global/express-extra.d.ts +6 -0
  161. package/types/global/modules.d.ts +13 -16
  162. package/types/global/utils.d.ts +17 -49
  163. package/types/global/vendors.d.ts +62 -0
  164. package/types/icons.d.ts +65 -1
  165. package/types/uuid.d.ts +3 -0
  166. package/types/vendors.d.ts +62 -0
  167. package/cli/compiler/common/babel/index.ts +0 -170
  168. package/cli/compiler/common/babel/plugins/index.ts +0 -0
  169. package/cli/compiler/common/babel/plugins/services.ts +0 -586
  170. package/cli/compiler/common/babel/routes/imports.ts +0 -127
  171. package/cli/compiler/common/babel/routes/routes.ts +0 -1130
  172. package/client/services/captcha/index.ts +0 -67
  173. package/client/services/socket/index.ts +0 -147
  174. package/common/data/rte/nodes.ts +0 -83
  175. package/common/data/stats.ts +0 -90
  176. package/common/utils/rte.ts +0 -183
  177. package/server/services/auth/old.ts +0 -277
  178. package/server/services/cache/commands.ts +0 -41
  179. package/server/services/cache/index.ts +0 -297
  180. package/server/services/cache/service.json +0 -6
  181. package/server/services/socket/index.ts +0 -162
  182. package/server/services/socket/scope.ts +0 -226
  183. package/server/services/socket/service.json +0 -6
  184. package/server/services_old/SocketClient.ts +0 -92
  185. package/server/services_old/Token.old.ts +0 -97
@@ -0,0 +1,490 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import ts from 'typescript';
4
+
5
+ const ROOT = '/Users/gaetan/Desktop/Projets';
6
+ const UNIQUE_ROOT = path.join(ROOT, 'unique.domains/website');
7
+ const CROSSPATH_ROOT = path.join(ROOT, 'crosspath/platform');
8
+
9
+ const TARGET_CONTEXT_NAMES = new Set([
10
+ 'Investor',
11
+ 'Crm',
12
+ 'Prospect',
13
+ 'Headhunters',
14
+ 'Founder',
15
+ 'Domains',
16
+ 'Navigation',
17
+ 'Router',
18
+ 'Users',
19
+ 'Plans',
20
+ 'Auth',
21
+ 'Admin',
22
+ ]);
23
+
24
+ type TLogConfig = { filepath: string; baseDir: string };
25
+
26
+ const LOGS: TLogConfig[] = [
27
+ { filepath: '/tmp/unique-client-after-page-contract.log', baseDir: path.join(UNIQUE_ROOT, 'client') },
28
+ { filepath: '/tmp/unique-server-after-page-contract.log', baseDir: path.join(UNIQUE_ROOT, 'server') },
29
+ { filepath: '/tmp/crosspath-client-after-page-contract.log', baseDir: path.join(CROSSPATH_ROOT, 'client') },
30
+ { filepath: '/tmp/crosspath-server-after-page-contract.log', baseDir: path.join(CROSSPATH_ROOT, 'server') },
31
+ ];
32
+
33
+ const assertReplace = (filepath: string, source: string, searchValue: string, replaceValue: string) => {
34
+ if (!source.includes(searchValue)) throw new Error(`Could not find expected content in ${filepath}: ${searchValue}`);
35
+
36
+ return source.replace(searchValue, replaceValue);
37
+ };
38
+
39
+ const ensureContextBinding = (source: string, bindingName: string) => {
40
+ if (
41
+ source.includes(`const { ${bindingName} } = context;`) ||
42
+ source.includes(`const { ${bindingName} } = useContext();`)
43
+ ) {
44
+ return source;
45
+ }
46
+
47
+ return source.replace(
48
+ ' const context = useContext();',
49
+ ` const context = useContext();\n const { ${bindingName} } = context;`,
50
+ );
51
+ };
52
+
53
+ const ensureContextHookBinding = (source: string, bindingName: string, anchor: string) => {
54
+ if (
55
+ source.includes(`const { ${bindingName} } = useContext();`) ||
56
+ source.includes(`const { ${bindingName} } = context;`)
57
+ ) {
58
+ return source;
59
+ }
60
+
61
+ return source.replace(anchor, ` const { ${bindingName} } = useContext();\n${anchor}`);
62
+ };
63
+
64
+ const writeIfChanged = (filepath: string, nextContent: string) => {
65
+ const currentContent = fs.readFileSync(filepath, 'utf8');
66
+ if (currentContent === nextContent) return false;
67
+
68
+ fs.writeFileSync(filepath, nextContent);
69
+ console.info(`updated ${filepath}`);
70
+ return true;
71
+ };
72
+
73
+ const applyLiteralReplacement = (filepath: string, updater: (source: string) => string) => {
74
+ const currentContent = fs.readFileSync(filepath, 'utf8');
75
+ const nextContent = updater(currentContent);
76
+ if (nextContent !== currentContent) {
77
+ fs.writeFileSync(filepath, nextContent);
78
+ console.info(`updated ${filepath}`);
79
+ }
80
+ };
81
+
82
+ const patchCentralFiles = () => {
83
+ applyLiteralReplacement(path.join(CROSSPATH_ROOT, 'client/components/legacy/Button.tsx'), (source) =>
84
+ source.includes('export type TLinkProps = React.JSX.HTMLAttributes<HTMLAnchorElement> & { link: string };')
85
+ ? source
86
+ : assertReplace(
87
+ path.join(CROSSPATH_ROOT, 'client/components/legacy/Button.tsx'),
88
+ source,
89
+ 'export type TLinkProps = React.JSX.HTMLAttributes<HTMLAnchorElement>;',
90
+ 'export type TLinkProps = React.JSX.HTMLAttributes<HTMLAnchorElement> & { link: string };',
91
+ ),
92
+ );
93
+
94
+ applyLiteralReplacement(path.join(CROSSPATH_ROOT, 'client/pages/_messages/401.tsx'), (source) =>
95
+ source.includes(' Router.go(loginPage);')
96
+ ? source
97
+ : assertReplace(
98
+ path.join(CROSSPATH_ROOT, 'client/pages/_messages/401.tsx'),
99
+ source,
100
+ ' page?.go(loginPage);',
101
+ ' Router.go(loginPage);',
102
+ ),
103
+ );
104
+
105
+ applyLiteralReplacement(path.join(UNIQUE_ROOT, 'client/pages/_messages/ErrorScreen.tsx'), (source) =>
106
+ source
107
+ .replace(
108
+ '{ ArrowRight, Home, LifeBuoy, LogIn, RefreshCw } from "lucide-preact";',
109
+ '{ ArrowRight, Home, LifeBuoy, LogIn, RefreshCw, type LucideIcon } from "lucide-preact";',
110
+ )
111
+ .replace(
112
+ 'type TLucideIcon = React.ComponentType<{ size?: number | string; className?: string }>;',
113
+ 'type TLucideIcon = LucideIcon;',
114
+ ),
115
+ );
116
+
117
+ applyLiteralReplacement(path.join(UNIQUE_ROOT, 'client/pages/Investor/database/DatabasePage.tsx'), (source) =>
118
+ source.includes('const { page: serverPage, user, Router, Investor, Domains } = useContext();')
119
+ ? source
120
+ : assertReplace(
121
+ path.join(UNIQUE_ROOT, 'client/pages/Investor/database/DatabasePage.tsx'),
122
+ source,
123
+ ' const { page: serverPage, user, Router } = useContext();',
124
+ ' const { page: serverPage, user, Router, Investor, Domains } = useContext();',
125
+ ),
126
+ );
127
+
128
+ applyLiteralReplacement(path.join(UNIQUE_ROOT, 'client/pages/Investor/insights/index.tsx'), (source) =>
129
+ source.includes(' const { Investor } = useAppContext();\n const [byGroupBy, setByGroupBy]')
130
+ ? source
131
+ : assertReplace(
132
+ path.join(UNIQUE_ROOT, 'client/pages/Investor/insights/index.tsx'),
133
+ source,
134
+ `}) => {
135
+ const [byGroupBy, setByGroupBy] = React.useState<InsightsRadarLensState>(() =>
136
+ emptyRadarLensState(),
137
+ );
138
+ `,
139
+ `}) => {
140
+ const { Investor } = useAppContext();
141
+ const [byGroupBy, setByGroupBy] = React.useState<InsightsRadarLensState>(() =>
142
+ emptyRadarLensState(),
143
+ );
144
+ `,
145
+ ),
146
+ );
147
+
148
+ applyLiteralReplacement(
149
+ path.join(UNIQUE_ROOT, 'client/pages/Investor/layout/components/user-settings/sections/GeneralSettingsSection.tsx'),
150
+ (source) =>
151
+ ensureContextBinding(
152
+ source.replace(
153
+ 'type UpdateProfileResponse = Awaited<ReturnType<typeof Users.updateProfile>>;',
154
+ `type UpdateProfileResponse = {
155
+ ok?: boolean;
156
+ firstName?: string | null;
157
+ lastName?: string | null;
158
+ name?: string | null;
159
+ };`,
160
+ ),
161
+ 'Users',
162
+ ),
163
+ );
164
+
165
+ applyLiteralReplacement(
166
+ path.join(UNIQUE_ROOT, 'client/pages/Investor/layout/components/user-settings/sections/PlanSettingsSection.tsx'),
167
+ (source) =>
168
+ ensureContextBinding(
169
+ source.replace('type PlansById = Awaited<ReturnType<typeof Plans.getPlans>>;', 'type PlansById = Record<string, any>;'),
170
+ 'Plans',
171
+ ),
172
+ );
173
+
174
+ applyLiteralReplacement(
175
+ path.join(UNIQUE_ROOT, 'client/pages/Investor/layout/components/user-settings/sections/SecuritySettingsSection.tsx'),
176
+ (source) =>
177
+ ensureContextHookBinding(
178
+ source
179
+ .replace(
180
+ '// App\n\nimport Icon from "@/client/components/Icon";',
181
+ '// App\n\nimport Icon from "@/client/components/Icon";\nimport useContext from "@/client/context";',
182
+ )
183
+ .replace(
184
+ 'type SecuritySummary = Awaited<ReturnType<typeof Auth.getSecuritySummary>>;',
185
+ `type SecuritySummary = {
186
+ authMethod?: string | null;
187
+ hasPassword?: boolean;
188
+ lastLogin?: string | Date | null;
189
+ lastLoginIP?: string | null;
190
+ connectedProviders?: Array<{ provider?: string | null; email?: string | null }>;
191
+ trustedDevices?: Array<{ deviceName?: string | null; userAgent?: string | null; lastSeen?: string | Date | null }>;
192
+ };`,
193
+ ),
194
+ 'Auth',
195
+ ' const [state, setState] = React.useState<LoadState>("idle");',
196
+ ),
197
+ );
198
+
199
+ applyLiteralReplacement(path.join(UNIQUE_ROOT, 'server/services/Domains/search/search.controller.ts'), (source) =>
200
+ source.includes(' public async GetLandingSeoCachedSearches() {')
201
+ ? source
202
+ : assertReplace(
203
+ path.join(UNIQUE_ROOT, 'server/services/Domains/search/search.controller.ts'),
204
+ source,
205
+ ` public async GetLandingSeoCachedSearch() {
206
+ const { Domains } = this.services;
207
+ const data = this.input(schema.object({ "searchHash": schema.string() }));
208
+ return Domains.search.GetLandingSeoCachedSearch(data);
209
+ }
210
+ `,
211
+ ` public async GetLandingSeoCachedSearches() {
212
+ const { Domains } = this.services;
213
+ return Domains.search.GetLandingSeoCachedSearches();
214
+ }
215
+
216
+ public async GetLandingSeoCachedSearch() {
217
+ const { Domains } = this.services;
218
+ const data = this.input(schema.object({ "searchHash": schema.string() }));
219
+ return Domains.search.GetLandingSeoCachedSearch(data);
220
+ }
221
+ `,
222
+ ),
223
+ );
224
+
225
+ applyLiteralReplacement(path.join(UNIQUE_ROOT, 'client/pages/Founder/setup/index.tsx'), (source) =>
226
+ source.includes(' const mutate = async (promise: PromiseLike<FounderSetupMutationResponse>) => {')
227
+ ? source
228
+ : assertReplace(
229
+ path.join(UNIQUE_ROOT, 'client/pages/Founder/setup/index.tsx'),
230
+ source,
231
+ ' const mutate = async (promise: Promise<FounderSetupMutationResponse>) => {',
232
+ ' const mutate = async (promise: PromiseLike<FounderSetupMutationResponse>) => {',
233
+ ),
234
+ );
235
+
236
+ for (const relativePath of [
237
+ 'client/components/crm/shared/LeadsTable.tsx',
238
+ 'client/components/crm/bizdev/dealPartners/DealPartnersTablePanel.tsx',
239
+ 'client/pages/crm/bizdev/tabs/PartnersTab.tsx',
240
+ 'client/pages/crm/bizdev/tabs/CsmsTab.tsx',
241
+ ]) {
242
+ applyLiteralReplacement(path.join(CROSSPATH_ROOT, relativePath), (source) =>
243
+ source
244
+ .replaceAll('Array<Promise<unknown>>', 'Array<PromiseLike<unknown>>')
245
+ .replaceAll('Promise<void>[]', 'PromiseLike<void>[]'),
246
+ );
247
+ }
248
+ };
249
+
250
+ const parseMissingContextNames = () => {
251
+ const files = new Map<string, Set<string>>();
252
+ const pattern =
253
+ /^(.+?)\(\d+,\d+\): error TS2304: Cannot find name '(Investor|Crm|Prospect|Headhunters|Founder|Domains|Navigation|Router|Users|Plans|Auth|Admin)'\.$/gm;
254
+
255
+ for (const log of LOGS) {
256
+ if (!fs.existsSync(log.filepath)) continue;
257
+
258
+ const content = fs.readFileSync(log.filepath, 'utf8');
259
+ let match: RegExpExecArray | null;
260
+
261
+ while ((match = pattern.exec(content)) !== null) {
262
+ const relativePath = match[1];
263
+ const identifier = match[2];
264
+ const absolutePath = path.resolve(log.baseDir, relativePath);
265
+
266
+ if (!fs.existsSync(absolutePath) || absolutePath.includes('/.generated/')) continue;
267
+
268
+ let names = files.get(absolutePath);
269
+ if (!names) {
270
+ names = new Set<string>();
271
+ files.set(absolutePath, names);
272
+ }
273
+
274
+ names.add(identifier);
275
+ }
276
+ }
277
+
278
+ return files;
279
+ };
280
+
281
+ const findChildContainingPosition = (node: ts.Node, position: number): ts.Node | undefined => {
282
+ let matchedChild: ts.Node | undefined;
283
+
284
+ node.forEachChild((child) => {
285
+ if (position >= child.getFullStart() && position < child.getEnd()) matchedChild = child;
286
+ });
287
+
288
+ return matchedChild;
289
+ };
290
+
291
+ const findEnclosingFunction = (sourceFile: ts.SourceFile, position: number) => {
292
+ let current: ts.Node = sourceFile;
293
+ const functions: Array<
294
+ | ts.FunctionDeclaration
295
+ | ts.FunctionExpression
296
+ | ts.ArrowFunction
297
+ | ts.MethodDeclaration
298
+ | ts.GetAccessorDeclaration
299
+ | ts.SetAccessorDeclaration
300
+ | ts.ConstructorDeclaration
301
+ > = [];
302
+
303
+ while (true) {
304
+ const next = findChildContainingPosition(current, position);
305
+ if (!next) return functions[0];
306
+
307
+ if (
308
+ ts.isFunctionDeclaration(next) ||
309
+ ts.isFunctionExpression(next) ||
310
+ ts.isArrowFunction(next) ||
311
+ ts.isMethodDeclaration(next) ||
312
+ ts.isGetAccessorDeclaration(next) ||
313
+ ts.isSetAccessorDeclaration(next) ||
314
+ ts.isConstructorDeclaration(next)
315
+ ) {
316
+ functions.push(next);
317
+ }
318
+
319
+ current = next;
320
+ }
321
+ };
322
+
323
+ const getContextHookName = (sourceFile: ts.SourceFile) => {
324
+ for (const statement of sourceFile.statements) {
325
+ if (!ts.isImportDeclaration(statement)) continue;
326
+ if (!ts.isStringLiteral(statement.moduleSpecifier)) continue;
327
+ if (statement.moduleSpecifier.text !== '@/client/context') continue;
328
+ if (!statement.importClause?.name) continue;
329
+
330
+ return statement.importClause.name.text;
331
+ }
332
+
333
+ return null;
334
+ };
335
+
336
+ const ensureContextImport = (filepath: string, source: string, sourceFile: ts.SourceFile) => {
337
+ const existing = getContextHookName(sourceFile);
338
+ if (existing) return { source, hookName: existing };
339
+
340
+ const hookName = 'useAppContext';
341
+ const importStatement = `import ${hookName} from "@/client/context";\n`;
342
+
343
+ let insertPos = 0;
344
+ for (const statement of sourceFile.statements) {
345
+ if (!ts.isImportDeclaration(statement)) break;
346
+ insertPos = statement.getEnd() + 1;
347
+ }
348
+
349
+ const nextSource = source.slice(0, insertPos) + importStatement + source.slice(insertPos);
350
+ console.info(`added context import in ${filepath}`);
351
+
352
+ return { source: nextSource, hookName };
353
+ };
354
+
355
+ const findExistingContextBinding = (
356
+ functionBody: ts.Block,
357
+ hookName: string,
358
+ ): ts.VariableDeclaration | undefined => {
359
+ for (const statement of functionBody.statements) {
360
+ if (!ts.isVariableStatement(statement)) continue;
361
+
362
+ for (const declaration of statement.declarationList.declarations) {
363
+ if (!ts.isObjectBindingPattern(declaration.name)) continue;
364
+ if (!declaration.initializer || !ts.isCallExpression(declaration.initializer)) continue;
365
+ if (!ts.isIdentifier(declaration.initializer.expression) || declaration.initializer.expression.text !== hookName)
366
+ continue;
367
+
368
+ return declaration;
369
+ }
370
+ }
371
+
372
+ return undefined;
373
+ };
374
+
375
+ const isContextBindingDeclaration = (declaration: ts.VariableDeclaration, hookName: string) => {
376
+ if (!ts.isObjectBindingPattern(declaration.name)) return false;
377
+ if (!declaration.initializer || !ts.isCallExpression(declaration.initializer)) return false;
378
+ if (!ts.isIdentifier(declaration.initializer.expression) || declaration.initializer.expression.text !== hookName)
379
+ return false;
380
+
381
+ return declaration.name.elements.every((element) => {
382
+ const identifier = element.propertyName || element.name;
383
+ return ts.isIdentifier(identifier) && TARGET_CONTEXT_NAMES.has(identifier.text);
384
+ });
385
+ };
386
+
387
+ const removeNestedContextBindings = (source: string, parentFunction: ts.Node, hookName: string) => {
388
+ const removals: Array<{ start: number; end: number }> = [];
389
+
390
+ const visit = (node: ts.Node) => {
391
+ if (node !== parentFunction && ts.isBlock(node) && node.parent) {
392
+ const functionParent = node.parent;
393
+ if (
394
+ ts.isFunctionDeclaration(functionParent) ||
395
+ ts.isFunctionExpression(functionParent) ||
396
+ ts.isArrowFunction(functionParent) ||
397
+ ts.isMethodDeclaration(functionParent) ||
398
+ ts.isGetAccessorDeclaration(functionParent) ||
399
+ ts.isSetAccessorDeclaration(functionParent) ||
400
+ ts.isConstructorDeclaration(functionParent)
401
+ ) {
402
+ for (const statement of node.statements) {
403
+ if (!ts.isVariableStatement(statement)) continue;
404
+
405
+ const allContextBindings =
406
+ statement.declarationList.declarations.length > 0 &&
407
+ statement.declarationList.declarations.every((declaration) =>
408
+ isContextBindingDeclaration(declaration, hookName),
409
+ );
410
+
411
+ if (allContextBindings) removals.push({ start: statement.getFullStart(), end: statement.getEnd() });
412
+ }
413
+ }
414
+ }
415
+
416
+ node.forEachChild(visit);
417
+ };
418
+
419
+ parentFunction.forEachChild(visit);
420
+
421
+ return removals
422
+ .sort((left, right) => right.start - left.start)
423
+ .reduce((nextSource, removal) => nextSource.slice(0, removal.start) + nextSource.slice(removal.end), source);
424
+ };
425
+
426
+ const addContextBindings = (filepath: string, names: Set<string>) => {
427
+ let source = fs.readFileSync(filepath, 'utf8');
428
+ let sourceFile = ts.createSourceFile(filepath, source, ts.ScriptTarget.Latest, true, filepath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
429
+ const importResult = ensureContextImport(filepath, source, sourceFile);
430
+ source = importResult.source;
431
+ sourceFile = ts.createSourceFile(filepath, source, ts.ScriptTarget.Latest, true, filepath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
432
+ const hookName = importResult.hookName;
433
+
434
+ const positions = [...names]
435
+ .map((name) => source.indexOf(`${name}.`))
436
+ .filter((position) => position >= 0)
437
+ .sort((left, right) => left - right);
438
+
439
+ if (positions.length === 0) return;
440
+
441
+ const targetFunction = findEnclosingFunction(sourceFile, positions[0]);
442
+ if (!targetFunction || !targetFunction.body || !ts.isBlock(targetFunction.body)) {
443
+ console.warn(`could not find function body for ${filepath}`);
444
+ return;
445
+ }
446
+
447
+ source = removeNestedContextBindings(source, targetFunction, hookName);
448
+ sourceFile = ts.createSourceFile(filepath, source, ts.ScriptTarget.Latest, true, filepath.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS);
449
+ const refreshedTargetFunction = findEnclosingFunction(sourceFile, positions[0]);
450
+ if (!refreshedTargetFunction || !refreshedTargetFunction.body || !ts.isBlock(refreshedTargetFunction.body)) {
451
+ console.warn(`could not refresh function body for ${filepath}`);
452
+ return;
453
+ }
454
+
455
+ const existingBinding = findExistingContextBinding(refreshedTargetFunction.body, hookName);
456
+
457
+ if (existingBinding && ts.isObjectBindingPattern(existingBinding.name)) {
458
+ const currentElements = existingBinding.name.elements.map((element) => element.getText(sourceFile));
459
+ const mergedElements = [...currentElements];
460
+
461
+ for (const name of names) {
462
+ if (!TARGET_CONTEXT_NAMES.has(name)) continue;
463
+ if (currentElements.some((element) => element === name || element.startsWith(name + ':'))) continue;
464
+ mergedElements.push(name);
465
+ }
466
+
467
+ const start = existingBinding.name.getStart(sourceFile) + 1;
468
+ const end = existingBinding.name.getEnd() - 1;
469
+ source = source.slice(0, start) + ` ${mergedElements.join(', ')} ` + source.slice(end);
470
+ } else {
471
+ const functionLineStart = source.lastIndexOf('\n', refreshedTargetFunction.getStart(sourceFile) - 1) + 1;
472
+ const functionIndent =
473
+ source.slice(functionLineStart, refreshedTargetFunction.getStart(sourceFile)).match(/^\s*/)?.[0] || '';
474
+ const statementIndent = functionIndent + ' ';
475
+ const insertPos = refreshedTargetFunction.body.getStart(sourceFile) + 1;
476
+ const statement = `\n${statementIndent}const { ${[...names].join(', ')} } = ${hookName}();`;
477
+ source = source.slice(0, insertPos) + statement + source.slice(insertPos);
478
+ }
479
+
480
+ writeIfChanged(filepath, source);
481
+ };
482
+
483
+ const patchAmbientContextUsages = () => {
484
+ const files = parseMissingContextNames();
485
+
486
+ for (const [filepath, names] of files) addContextBindings(filepath, names);
487
+ };
488
+
489
+ patchCentralFiles();
490
+ patchAmbientContextUsages();