@holo-js/cli 0.2.6 → 0.3.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 (51) hide show
  1. package/dist/bin/holo.mjs +417 -109
  2. package/dist/{broadcast-JBQWQZSO.mjs → broadcast-PJLFVZH4.mjs} +12 -12
  3. package/dist/cache-KR4ACOYD.mjs +137 -0
  4. package/dist/{cache-migrations-77TLXIVG.mjs → cache-migrations-J34RE4WH.mjs} +13 -13
  5. package/dist/{chunk-LXGQCG56.mjs → chunk-2XXJ76YC.mjs} +1 -1
  6. package/dist/chunk-3ICVWL2M.mjs +491 -0
  7. package/dist/{chunk-YEFJBN56.mjs → chunk-4VYR2ARA.mjs} +11 -8
  8. package/dist/{chunk-VP2E62DF.mjs → chunk-7KZVFDSI.mjs} +49 -349
  9. package/dist/chunk-AZ6NVJAP.mjs +360 -0
  10. package/dist/chunk-CT23GSEC.mjs +156 -0
  11. package/dist/{chunk-7B2RVYLL.mjs → chunk-FFTJKBQF.mjs} +293 -399
  12. package/dist/{chunk-KS5TWO75.mjs → chunk-I3RRWDLV.mjs} +7 -7
  13. package/dist/{chunk-J76GH2DR.mjs → chunk-L3YATEQY.mjs} +129 -86
  14. package/dist/{chunk-4K4CWMMP.mjs → chunk-L6FF22IV.mjs} +76 -61
  15. package/dist/{chunk-ILU426CF.mjs → chunk-PVVGQSUP.mjs} +482 -2
  16. package/dist/chunk-XBOVM6LO.mjs +41 -0
  17. package/dist/{chunk-I7QBCEV7.mjs → chunk-Y355VYRN.mjs} +5 -3
  18. package/dist/{chunk-VRGB6DIS.mjs → chunk-YJWHIQ45.mjs} +2 -0
  19. package/dist/{config-MD27U4FM.mjs → config-XVPV6DJW.mjs} +3 -3
  20. package/dist/{dev-L4Y2GU2E.mjs → dev-NTQTEY5B.mjs} +9 -8
  21. package/dist/{discovery-GWTBF5RZ.mjs → discovery-TMPUQQHI.mjs} +8 -6
  22. package/dist/{generators-VCYISHWO.mjs → generators-3FDCCJDC.mjs} +16 -15
  23. package/dist/index.d.ts +1 -1
  24. package/dist/index.mjs +419 -111
  25. package/dist/{media-migrations-BNVAPYEM.mjs → media-migrations-UJ6BMUSZ.mjs} +12 -12
  26. package/dist/plugins-USHY6SPF.mjs +24 -0
  27. package/dist/{queue-5BXSDFCO.mjs → queue-6U7JU4T6.mjs} +53 -17
  28. package/dist/{queue-D4LSWNS2.mjs → queue-VJEFD6SE.mjs} +55 -19
  29. package/dist/{queue-migrations-EF4AMMSY.mjs → queue-migrations-6YUUOKMH.mjs} +17 -14
  30. package/dist/{runtime-RPMZMTD4.mjs → runtime-FVRB4O2M.mjs} +8 -8
  31. package/dist/{runtime-GSXF4NB3.mjs → runtime-P5R7H3B4.mjs} +1 -1
  32. package/dist/runtime-worker.mjs +7 -1
  33. package/dist/{scaffold-NJ5VH73M.mjs → scaffold-F3AZDNPG.mjs} +9 -4
  34. package/dist/{security-K5PZS3E3.mjs → security-X4274RHX.mjs} +8 -7
  35. package/package.json +35 -8
  36. package/dist/broadcast-YGJFCEPP.mjs +0 -204
  37. package/dist/cache-HUGRWOHQ.mjs +0 -66
  38. package/dist/cache-OSJ4PD52.mjs +0 -66
  39. package/dist/cache-migrations-FKAHRP24.mjs +0 -173
  40. package/dist/chunk-AJLRAC5M.mjs +0 -497
  41. package/dist/chunk-C624G3R2.mjs +0 -3306
  42. package/dist/chunk-D7O4SU6N.mjs +0 -2
  43. package/dist/chunk-FGQ2I2YH.mjs +0 -22
  44. package/dist/chunk-LBJAJLKU.mjs +0 -25
  45. package/dist/dev-YPBQBEOE.mjs +0 -44
  46. package/dist/generators-H4NTV4DB.mjs +0 -520
  47. package/dist/media-migrations-NNB3DAQR.mjs +0 -106
  48. package/dist/queue-migrations-LXEWXJYT.mjs +0 -168
  49. package/dist/runtime-UKBJQFXM.mjs +0 -57
  50. package/dist/scaffold-VV3KTYGO.mjs +0 -139
  51. package/dist/security-JR4P7L2C.mjs +0 -71
@@ -0,0 +1,360 @@
1
+ import {
2
+ COMMAND_FILE_PATTERN,
3
+ MIGRATION_NAME_PATTERN,
4
+ isRecord,
5
+ makeProjectRelativePath,
6
+ pathExists,
7
+ readTextFile,
8
+ toPosixPath
9
+ } from "./chunk-PVVGQSUP.mjs";
10
+
11
+ // src/project/discovery-helpers.ts
12
+ import { readdir } from "fs/promises";
13
+ import { basename, dirname, extname, join, relative, resolve } from "path";
14
+ async function collectFiles(root) {
15
+ if (!await pathExists(root)) {
16
+ return [];
17
+ }
18
+ const entries = await readdir(root, { withFileTypes: true });
19
+ const files = [];
20
+ for (const entry of entries) {
21
+ const target = join(root, entry.name);
22
+ if (entry.isDirectory()) {
23
+ files.push(...await collectFiles(target));
24
+ continue;
25
+ }
26
+ if (entry.isFile() && COMMAND_FILE_PATTERN.test(entry.name)) {
27
+ files.push(target);
28
+ }
29
+ }
30
+ return files;
31
+ }
32
+ function deriveCommandNameFromPath(commandsRoot, sourcePath) {
33
+ const relativePath = toPosixPath(relative(commandsRoot, sourcePath));
34
+ return relativePath.replace(COMMAND_FILE_PATTERN, "").split("/").filter(Boolean).join(":");
35
+ }
36
+ function deriveJobNameFromPath(jobsRoot, sourcePath) {
37
+ const relativePath = toPosixPath(relative(jobsRoot, sourcePath));
38
+ return relativePath.replace(COMMAND_FILE_PATTERN, "").split("/").filter(Boolean).join(".");
39
+ }
40
+ function deriveDottedNameFromPath(root, sourcePath, emptyMessage) {
41
+ const relativePath = toPosixPath(relative(root, sourcePath)).replace(COMMAND_FILE_PATTERN, "");
42
+ const derived = relativePath.split("/").map((part) => part.trim()).filter(Boolean).join(".");
43
+ if (!derived) {
44
+ throw new Error(emptyMessage);
45
+ }
46
+ return derived;
47
+ }
48
+ function deriveEventNameFromPath(eventsRoot, sourcePath) {
49
+ return deriveDottedNameFromPath(eventsRoot, sourcePath, "[Holo Events] Derived event names require a non-empty source path.");
50
+ }
51
+ function deriveListenerIdFromPath(listenersRoot, sourcePath) {
52
+ return deriveDottedNameFromPath(listenersRoot, sourcePath, "[Holo Events] Derived listener identifiers require a non-empty source path.");
53
+ }
54
+ function deriveBroadcastNameFromPath(root, sourcePath) {
55
+ return deriveDottedNameFromPath(root, sourcePath, "[Holo Broadcast] Derived broadcast names require a non-empty source path.");
56
+ }
57
+ function deriveChannelPatternFromPath(root, sourcePath) {
58
+ return deriveDottedNameFromPath(root, sourcePath, "[Holo Broadcast] Derived channel patterns require a non-empty source path.");
59
+ }
60
+ function resolveDiscoveredJobMetadata(job, sourcePath, derivedName, queueConfig) {
61
+ const connection = job.connection ?? queueConfig.default;
62
+ let queue = job.queue;
63
+ if (!queue) {
64
+ const configuredConnection = queueConfig.connections[connection];
65
+ queue = configuredConnection ? configuredConnection.queue : "default";
66
+ }
67
+ return {
68
+ sourcePath,
69
+ name: derivedName,
70
+ connection,
71
+ queue,
72
+ ...typeof job.tries === "number" ? { tries: job.tries } : {},
73
+ ...typeof job.backoff !== "undefined" ? { backoff: job.backoff } : {},
74
+ ...typeof job.timeout === "number" ? { timeout: job.timeout } : {}
75
+ };
76
+ }
77
+ function isAppCommand(value) {
78
+ return isRecord(value) && typeof value.description === "string" && typeof value.run === "function";
79
+ }
80
+ function resolveCommandExport(moduleValue) {
81
+ if (isRecord(moduleValue) && isAppCommand(moduleValue.default)) {
82
+ return moduleValue.default;
83
+ }
84
+ if (isRecord(moduleValue)) {
85
+ for (const value of Object.values(moduleValue)) {
86
+ if (isAppCommand(value)) {
87
+ return value;
88
+ }
89
+ }
90
+ }
91
+ return void 0;
92
+ }
93
+ function normalizeCommandAliases(value) {
94
+ if (!value) {
95
+ return void 0;
96
+ }
97
+ const normalized = [...new Set(value.map((alias) => alias.trim()).filter(Boolean))];
98
+ return normalized.length > 0 ? normalized : void 0;
99
+ }
100
+ function assertUniqueEntries(kind, entries) {
101
+ const seen = /* @__PURE__ */ new Map();
102
+ for (const entry of entries) {
103
+ const existing = seen.get(entry.name);
104
+ if (existing) {
105
+ throw new Error(`Discovered duplicate ${kind} "${entry.name}" in "${existing}" and "${entry.sourcePath}".`);
106
+ }
107
+ seen.set(entry.name, entry.sourcePath);
108
+ }
109
+ }
110
+ function assertUniqueCommandTokens(entries) {
111
+ const seen = /* @__PURE__ */ new Map();
112
+ for (const entry of entries) {
113
+ for (const token of [entry.name, ...entry.aliases]) {
114
+ const existing = seen.get(token);
115
+ if (existing) {
116
+ throw new Error(`Discovered duplicate command token "${token}" in "${existing}" and "${entry.sourcePath}".`);
117
+ }
118
+ seen.set(token, entry.sourcePath);
119
+ }
120
+ }
121
+ }
122
+ function resolveRegisteredPath(projectRoot, entry) {
123
+ return resolve(projectRoot, entry);
124
+ }
125
+ function resolveNamedExport(moduleValue, matcher) {
126
+ if (!isRecord(moduleValue)) return void 0;
127
+ if (matcher(moduleValue.default)) return moduleValue.default;
128
+ for (const value of Object.values(moduleValue)) {
129
+ if (matcher(value)) return value;
130
+ }
131
+ return void 0;
132
+ }
133
+ function resolveNamedExportEntry(moduleValue, matcher) {
134
+ if (!isRecord(moduleValue)) return void 0;
135
+ if (matcher(moduleValue.default)) {
136
+ return { exportName: "default", value: moduleValue.default };
137
+ }
138
+ for (const [exportName, value] of Object.entries(moduleValue)) {
139
+ if (matcher(value)) return { exportName, value };
140
+ }
141
+ return void 0;
142
+ }
143
+ function isCliModelReference(value) {
144
+ return isRecord(value) && isRecord(value.definition) && value.definition.kind === "model" && typeof value.definition.name === "string" && typeof value.prune === "function";
145
+ }
146
+ function isMissingGeneratedSchemaModelError(error) {
147
+ return error instanceof Error && error.message.includes("is not present in the generated schema registry");
148
+ }
149
+ function isInactiveGeneratedModelModule(value) {
150
+ return isRecord(value) && value.holoModelPendingSchema === true;
151
+ }
152
+ function isMigrationDefinition(value) {
153
+ return isRecord(value) && typeof value.up === "function";
154
+ }
155
+ function isSeederDefinition(value) {
156
+ return isRecord(value) && typeof value.name === "string" && typeof value.run === "function";
157
+ }
158
+ function resolveListenerEventNamesForDiscovery(listener, eventNamesByReference = /* @__PURE__ */ new Map()) {
159
+ return Object.freeze([...new Set(listener.listensTo.map((reference) => {
160
+ if (typeof reference === "string") {
161
+ return reference.trim();
162
+ }
163
+ if (typeof reference.name === "string" && reference.name.trim()) {
164
+ return reference.name.trim();
165
+ }
166
+ if (eventNamesByReference.has(reference)) {
167
+ return eventNamesByReference.get(reference);
168
+ }
169
+ throw new Error("[Holo Events] Listener event references must resolve to explicit event names before discovery registration.");
170
+ }))]);
171
+ }
172
+ function resolveAuthorizationTargetName(target) {
173
+ const modelFacadeTarget = target;
174
+ if (typeof modelFacadeTarget.definition?.name === "string" && modelFacadeTarget.definition.name.trim()) {
175
+ return modelFacadeTarget.definition.name.trim();
176
+ }
177
+ const namedTarget = target;
178
+ return typeof namedTarget.name === "string" && namedTarget.name.trim() ? namedTarget.name.trim() : void 0;
179
+ }
180
+ function captureAuthorizationDefinitionNames(definitions) {
181
+ return new Set(definitions.keys());
182
+ }
183
+ function findAddedAuthorizationDefinitionNames(definitions, existingNames) {
184
+ return [...definitions.keys()].filter((name) => !existingNames.has(name));
185
+ }
186
+ function unregisterAuthorizationDefinitionNames(authorizationDiscovery, policyNames, abilityNames) {
187
+ if (typeof authorizationDiscovery.authorizationInternals.unregisterPolicyDefinition !== "function" || typeof authorizationDiscovery.authorizationInternals.unregisterAbilityDefinition !== "function") {
188
+ authorizationDiscovery.authorizationInternals.resetAuthorizationRuntimeState?.();
189
+ return;
190
+ }
191
+ for (const policyName of policyNames) {
192
+ authorizationDiscovery.authorizationInternals.unregisterPolicyDefinition(policyName);
193
+ }
194
+ for (const abilityName of abilityNames) {
195
+ authorizationDiscovery.authorizationInternals.unregisterAbilityDefinition(abilityName);
196
+ }
197
+ }
198
+ function collectImportedBindingsBySource(sourceText) {
199
+ const bindings = /* @__PURE__ */ new Map();
200
+ const importPattern = /import\s+([\s\S]*?)\s+from\s+['"]([^'"]+)['"]/g;
201
+ for (const match of sourceText.matchAll(importPattern)) {
202
+ const clause = match[1]?.trim();
203
+ const source = match[2]?.trim();
204
+ if (!clause || !source) {
205
+ continue;
206
+ }
207
+ const namedMatch = clause.match(/\{([\s\S]+)\}/);
208
+ const defaultClause = clause.replace(/\{[\s\S]+\}/, "").replace(/,$/, "").trim();
209
+ if (defaultClause && defaultClause !== "*") {
210
+ bindings.set(defaultClause, source);
211
+ }
212
+ if (namedMatch?.[1]) {
213
+ for (const specifier of namedMatch[1].split(",")) {
214
+ const trimmed = specifier.trim();
215
+ if (!trimmed) {
216
+ continue;
217
+ }
218
+ const [imported, local] = trimmed.split(/\s+as\s+/);
219
+ const bindingName = (local ?? imported)?.trim();
220
+ if (bindingName) {
221
+ bindings.set(bindingName, source);
222
+ }
223
+ }
224
+ }
225
+ }
226
+ return bindings;
227
+ }
228
+ function extractListensToItems(sourceText) {
229
+ const markerIndex = sourceText.indexOf("listensTo");
230
+ if (markerIndex < 0) {
231
+ return [];
232
+ }
233
+ const colonIndex = sourceText.indexOf(":", markerIndex);
234
+ if (colonIndex < 0) {
235
+ return [];
236
+ }
237
+ let cursor = colonIndex + 1;
238
+ while (cursor < sourceText.length && /\s/.test(sourceText[cursor])) {
239
+ cursor += 1;
240
+ }
241
+ const startChar = sourceText[cursor];
242
+ let depth = 0;
243
+ let inString;
244
+ let expression = "";
245
+ for (; cursor < sourceText.length; cursor += 1) {
246
+ const char = sourceText[cursor];
247
+ expression += char;
248
+ if (inString) {
249
+ if (char === inString && sourceText[cursor - 1] !== "\\") {
250
+ inString = void 0;
251
+ }
252
+ continue;
253
+ }
254
+ if (char === "'" || char === '"' || char === "`") {
255
+ inString = char;
256
+ continue;
257
+ }
258
+ if (char === "[" || char === "{" || char === "(") {
259
+ depth += 1;
260
+ continue;
261
+ }
262
+ if (char === "]" || char === "}" || char === ")") {
263
+ depth -= 1;
264
+ if (depth === 0 && startChar === "[") {
265
+ break;
266
+ }
267
+ continue;
268
+ }
269
+ if (depth === 0 && startChar !== "[" && (char === "," || char === "\n" || char === "\r")) {
270
+ expression = expression.slice(0, -1);
271
+ break;
272
+ }
273
+ }
274
+ if (startChar !== "[") {
275
+ const item = expression.trim().replace(/\s+as\s+const$/, "");
276
+ return item ? [item] : [];
277
+ }
278
+ return expression.slice(1, -1).split(",").map((item) => item.trim().replace(/\s+as\s+const$/, "")).filter(Boolean);
279
+ }
280
+ async function resolveListenerEventNamesFromSource(projectRoot, listenerPath, discoveredEventNamesBySourcePath) {
281
+ const sourceText = await readTextFile(listenerPath) ?? "";
282
+ const bindingsByName = collectImportedBindingsBySource(sourceText);
283
+ const discoveredEventNamesByExtensionlessSourcePath = new Map(
284
+ [...discoveredEventNamesBySourcePath.entries()].map(([sourcePath, eventName]) => {
285
+ return [sourcePath.replace(/\.[^.]+$/, ""), eventName];
286
+ })
287
+ );
288
+ const resolvedEventNames = [];
289
+ for (const item of extractListensToItems(sourceText)) {
290
+ const quoted = item.match(/^['"](.+)['"]$/);
291
+ if (quoted) {
292
+ resolvedEventNames.push(quoted[1].trim());
293
+ continue;
294
+ }
295
+ const importSource = bindingsByName.get(item);
296
+ if (!importSource) {
297
+ throw new Error("[Holo Events] Listener event references must resolve to explicit event names before discovery registration.");
298
+ }
299
+ const importedPath = makeProjectRelativePath(projectRoot, resolve(dirname(listenerPath), importSource));
300
+ const eventName = discoveredEventNamesBySourcePath.get(importedPath) ?? discoveredEventNamesByExtensionlessSourcePath.get(importedPath.replace(/\.[^.]+$/, ""));
301
+ if (!eventName) {
302
+ throw new Error("[Holo Events] Listener event references must resolve to explicit event names before discovery registration.");
303
+ }
304
+ resolvedEventNames.push(eventName);
305
+ }
306
+ return Object.freeze([...new Set(resolvedEventNames)]);
307
+ }
308
+ function resolveBroadcastArtifactsPath(config, key) {
309
+ const configuredPaths = config.paths;
310
+ return configuredPaths[key] ?? `server/${key}`;
311
+ }
312
+ function inferMigrationNameFromEntry(entry) {
313
+ const fileName = basename(entry, extname(entry));
314
+ return validateMigrationName(
315
+ fileName,
316
+ `Registered migration "${entry}" must use a timestamped file name matching YYYY_MM_DD_HHMMSS_description.`
317
+ );
318
+ }
319
+ function validateMigrationName(name, message) {
320
+ if (!MIGRATION_NAME_PATTERN.test(name)) {
321
+ throw new Error(
322
+ message ?? `Migration name "${name}" must match YYYY_MM_DD_HHMMSS_description.`
323
+ );
324
+ }
325
+ return name;
326
+ }
327
+
328
+ export {
329
+ collectFiles,
330
+ deriveCommandNameFromPath,
331
+ deriveJobNameFromPath,
332
+ deriveEventNameFromPath,
333
+ deriveListenerIdFromPath,
334
+ deriveBroadcastNameFromPath,
335
+ deriveChannelPatternFromPath,
336
+ resolveDiscoveredJobMetadata,
337
+ resolveCommandExport,
338
+ normalizeCommandAliases,
339
+ assertUniqueEntries,
340
+ assertUniqueCommandTokens,
341
+ resolveRegisteredPath,
342
+ resolveNamedExport,
343
+ resolveNamedExportEntry,
344
+ isCliModelReference,
345
+ isMissingGeneratedSchemaModelError,
346
+ isInactiveGeneratedModelModule,
347
+ isMigrationDefinition,
348
+ isSeederDefinition,
349
+ resolveListenerEventNamesForDiscovery,
350
+ resolveAuthorizationTargetName,
351
+ captureAuthorizationDefinitionNames,
352
+ findAddedAuthorizationDefinitionNames,
353
+ unregisterAuthorizationDefinitionNames,
354
+ collectImportedBindingsBySource,
355
+ extractListensToItems,
356
+ resolveListenerEventNamesFromSource,
357
+ resolveBroadcastArtifactsPath,
358
+ inferMigrationNameFromEntry,
359
+ validateMigrationName
360
+ };
@@ -0,0 +1,156 @@
1
+ import {
2
+ HOLO_PACKAGE_VERSION,
3
+ readTextFile,
4
+ writeTextFile
5
+ } from "./chunk-PVVGQSUP.mjs";
6
+
7
+ // src/package-json.ts
8
+ import { join } from "path";
9
+ function normalizeDependencyMap(value) {
10
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
11
+ return {};
12
+ }
13
+ return Object.fromEntries(
14
+ Object.entries(value).filter(([, dependencyVersion]) => typeof dependencyVersion === "string").sort(([left], [right]) => left.localeCompare(right))
15
+ );
16
+ }
17
+ function isWorkspaceDependencyVersion(value) {
18
+ return typeof value === "string" && value.startsWith("workspace:");
19
+ }
20
+ function assertValidDependencyName(packageName) {
21
+ if (!/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/.test(packageName) && !/^[a-z0-9][a-z0-9._-]*$/.test(packageName)) {
22
+ throw new Error(`Invalid dependency package name: ${packageName || "(empty)"}.`);
23
+ }
24
+ }
25
+ function resolveInstalledPackageJsonPath(projectRoot, packageName) {
26
+ return join(projectRoot, "node_modules", ...packageName.split("/"), "package.json");
27
+ }
28
+ async function resolveInstalledPackageVersion(projectRoot, packageName) {
29
+ const packageJson = await readTextFile(resolveInstalledPackageJsonPath(projectRoot, packageName));
30
+ if (!packageJson) {
31
+ return void 0;
32
+ }
33
+ try {
34
+ const parsed = JSON.parse(packageJson);
35
+ return typeof parsed.version === "string" && parsed.version.trim() ? `^${parsed.version.trim()}` : void 0;
36
+ } catch {
37
+ return void 0;
38
+ }
39
+ }
40
+ async function resolvePackageVersion(projectRoot, packageName, dependencies, devDependencies) {
41
+ const currentPackageVersion = dependencies[packageName] ?? devDependencies[packageName];
42
+ if (typeof currentPackageVersion === "string") {
43
+ return currentPackageVersion;
44
+ }
45
+ const workspaceVersion = Object.entries({
46
+ ...dependencies,
47
+ ...devDependencies
48
+ }).find(([dependencyName, dependencyVersion]) => dependencyName.startsWith("@holo-js/") && isWorkspaceDependencyVersion(dependencyVersion))?.[1];
49
+ if (packageName.startsWith("@holo-js/")) {
50
+ return workspaceVersion ?? `^${HOLO_PACKAGE_VERSION}`;
51
+ }
52
+ return await resolveInstalledPackageVersion(projectRoot, packageName) ?? "latest";
53
+ }
54
+ function sortDependencyMap(dependencies) {
55
+ return Object.fromEntries(
56
+ Object.entries(dependencies).sort(([left], [right]) => left.localeCompare(right))
57
+ );
58
+ }
59
+ async function readPackageJsonDependencyState(projectRoot) {
60
+ const packageJsonPath = join(projectRoot, "package.json");
61
+ const packageJson = await readTextFile(packageJsonPath);
62
+ if (!packageJson) {
63
+ throw new Error(`Missing package.json in ${projectRoot}.`);
64
+ }
65
+ let parsed;
66
+ try {
67
+ parsed = JSON.parse(packageJson);
68
+ } catch {
69
+ throw new Error(`Invalid package.json in ${projectRoot}.`);
70
+ }
71
+ return {
72
+ packageJsonPath,
73
+ parsed,
74
+ dependencies: normalizeDependencyMap(parsed.dependencies),
75
+ devDependencies: normalizeDependencyMap(parsed.devDependencies)
76
+ };
77
+ }
78
+ async function writePackageJsonDependencyState(state) {
79
+ state.parsed.dependencies = sortDependencyMap(state.dependencies);
80
+ if (Object.keys(state.devDependencies).length > 0) {
81
+ state.parsed.devDependencies = sortDependencyMap(state.devDependencies);
82
+ } else {
83
+ delete state.parsed.devDependencies;
84
+ }
85
+ await writeTextFile(state.packageJsonPath, `${JSON.stringify(state.parsed, null, 2)}
86
+ `);
87
+ }
88
+ async function hasProjectDependency(projectRoot, packageName) {
89
+ const packageJson = await readTextFile(join(projectRoot, "package.json"));
90
+ if (!packageJson) {
91
+ return false;
92
+ }
93
+ try {
94
+ const parsed = JSON.parse(packageJson);
95
+ return typeof parsed.dependencies?.[packageName] === "string" || typeof parsed.devDependencies?.[packageName] === "string";
96
+ } catch {
97
+ return false;
98
+ }
99
+ }
100
+ async function upsertProjectDependency(projectRoot, packageName) {
101
+ assertValidDependencyName(packageName);
102
+ const state = await readPackageJsonDependencyState(projectRoot);
103
+ const nextVersion = await resolvePackageVersion(projectRoot, packageName, state.dependencies, state.devDependencies);
104
+ if (state.dependencies[packageName] === nextVersion && typeof state.devDependencies[packageName] === "undefined") {
105
+ return false;
106
+ }
107
+ state.dependencies[packageName] = nextVersion;
108
+ delete state.devDependencies[packageName];
109
+ await writePackageJsonDependencyState(state);
110
+ return true;
111
+ }
112
+ async function pinProjectDependencyVersions(projectRoot, packageNames) {
113
+ const state = await readPackageJsonDependencyState(projectRoot);
114
+ let changed = false;
115
+ for (const packageName of packageNames) {
116
+ assertValidDependencyName(packageName);
117
+ if (packageName.startsWith("@holo-js/")) {
118
+ continue;
119
+ }
120
+ const installedVersion = await resolveInstalledPackageVersion(projectRoot, packageName);
121
+ if (!installedVersion) {
122
+ continue;
123
+ }
124
+ if (state.dependencies[packageName] === "latest") {
125
+ state.dependencies[packageName] = installedVersion;
126
+ changed = true;
127
+ }
128
+ if (state.devDependencies[packageName] === "latest") {
129
+ state.devDependencies[packageName] = installedVersion;
130
+ changed = true;
131
+ }
132
+ }
133
+ if (!changed) {
134
+ return false;
135
+ }
136
+ await writePackageJsonDependencyState(state);
137
+ return true;
138
+ }
139
+ async function removeProjectDependency(projectRoot, packageName) {
140
+ assertValidDependencyName(packageName);
141
+ const state = await readPackageJsonDependencyState(projectRoot);
142
+ if (typeof state.dependencies[packageName] === "undefined" && typeof state.devDependencies[packageName] === "undefined") {
143
+ return false;
144
+ }
145
+ delete state.dependencies[packageName];
146
+ delete state.devDependencies[packageName];
147
+ await writePackageJsonDependencyState(state);
148
+ return true;
149
+ }
150
+
151
+ export {
152
+ hasProjectDependency,
153
+ upsertProjectDependency,
154
+ pinProjectDependencyVersions,
155
+ removeProjectDependency
156
+ };