opkg 0.9.2 → 0.9.3

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 (140) hide show
  1. package/package.json +3 -1
  2. package/packages/cli/dist/add-U44SL3OR.js +624 -0
  3. package/packages/cli/dist/add-U44SL3OR.js.map +7 -0
  4. package/packages/cli/dist/chunk-4B5HJLP2.js +48 -0
  5. package/packages/cli/dist/chunk-4B5HJLP2.js.map +7 -0
  6. package/packages/cli/dist/chunk-BROJ6OUT.js +631 -0
  7. package/packages/cli/dist/chunk-BROJ6OUT.js.map +7 -0
  8. package/packages/cli/dist/chunk-CVA64SXK.js +1136 -0
  9. package/packages/cli/dist/chunk-CVA64SXK.js.map +7 -0
  10. package/packages/cli/dist/chunk-D6LEPODL.js +413 -0
  11. package/packages/cli/dist/chunk-D6LEPODL.js.map +7 -0
  12. package/packages/cli/dist/chunk-HTYHJA3B.js +61 -0
  13. package/packages/cli/dist/chunk-HTYHJA3B.js.map +7 -0
  14. package/packages/cli/dist/chunk-KI7FDU3H.js +99 -0
  15. package/packages/cli/dist/chunk-KI7FDU3H.js.map +7 -0
  16. package/packages/cli/dist/chunk-PSQXKAL4.js +371 -0
  17. package/packages/cli/dist/chunk-PSQXKAL4.js.map +7 -0
  18. package/packages/cli/dist/chunk-PUDRKDVZ.js +1419 -0
  19. package/packages/cli/dist/chunk-PUDRKDVZ.js.map +7 -0
  20. package/packages/cli/dist/chunk-U7FW7SXX.js +568 -0
  21. package/packages/cli/dist/chunk-U7FW7SXX.js.map +7 -0
  22. package/packages/cli/dist/configure-3AZUMDJZ.js +107 -0
  23. package/packages/cli/dist/configure-3AZUMDJZ.js.map +7 -0
  24. package/packages/cli/dist/index.js +15 -15
  25. package/packages/cli/dist/install-EZNWMLJR.js +7581 -0
  26. package/packages/cli/dist/install-EZNWMLJR.js.map +7 -0
  27. package/packages/cli/dist/list-XR7RSJFS.js +327 -0
  28. package/packages/cli/dist/list-XR7RSJFS.js.map +7 -0
  29. package/packages/cli/dist/login-NRKHXZKM.js +150 -0
  30. package/packages/cli/dist/login-NRKHXZKM.js.map +7 -0
  31. package/packages/cli/dist/logout-SYHXCVCQ.js +40 -0
  32. package/packages/cli/dist/logout-SYHXCVCQ.js.map +7 -0
  33. package/packages/cli/dist/new-F46OSD72.js +277 -0
  34. package/packages/cli/dist/new-F46OSD72.js.map +7 -0
  35. package/packages/cli/dist/publish-4H43PCSG.js +619 -0
  36. package/packages/cli/dist/publish-4H43PCSG.js.map +7 -0
  37. package/packages/cli/dist/remove-BD52BHR2.js +542 -0
  38. package/packages/cli/dist/remove-BD52BHR2.js.map +7 -0
  39. package/packages/cli/dist/save-N3QWF2WN.js +1728 -0
  40. package/packages/cli/dist/save-N3QWF2WN.js.map +7 -0
  41. package/packages/cli/dist/search-ABROK3UO.js +157 -0
  42. package/packages/cli/dist/search-ABROK3UO.js.map +7 -0
  43. package/packages/cli/dist/set-NGM2FIKF.js +251 -0
  44. package/packages/cli/dist/set-NGM2FIKF.js.map +7 -0
  45. package/packages/cli/dist/uninstall-Q3CP4UN5.js +539 -0
  46. package/packages/cli/dist/uninstall-Q3CP4UN5.js.map +7 -0
  47. package/packages/cli/dist/unpublish-VBTNTMS5.js +245 -0
  48. package/packages/cli/dist/unpublish-VBTNTMS5.js.map +7 -0
  49. package/packages/cli/dist/view-MXRBMXOG.js +488 -0
  50. package/packages/cli/dist/view-MXRBMXOG.js.map +7 -0
  51. package/packages/cli/package.json +2 -0
  52. package/packages/core/dist/core/install/conflicts/file-conflict-resolver.d.ts +5 -4
  53. package/packages/core/dist/core/install/conflicts/file-conflict-resolver.d.ts.map +1 -1
  54. package/packages/core/dist/core/install/conflicts/file-conflict-resolver.js +6 -5
  55. package/packages/core/dist/core/install/conflicts/file-conflict-resolver.js.map +1 -1
  56. package/packages/core/dist/core/install/install-reporting.js +1 -1
  57. package/packages/core/dist/core/install/install-reporting.js.map +1 -1
  58. package/packages/core/dist/core/install/list-handler.d.ts.map +1 -1
  59. package/packages/core/dist/core/install/list-handler.js +7 -0
  60. package/packages/core/dist/core/install/list-handler.js.map +1 -1
  61. package/packages/core/dist/core/install/marketplace-handler.d.ts.map +1 -1
  62. package/packages/core/dist/core/install/marketplace-handler.js.map +1 -1
  63. package/packages/core/dist/core/install/operations/conflict-handler.d.ts +2 -1
  64. package/packages/core/dist/core/install/operations/conflict-handler.d.ts.map +1 -1
  65. package/packages/core/dist/core/install/operations/conflict-handler.js +2 -2
  66. package/packages/core/dist/core/install/operations/conflict-handler.js.map +1 -1
  67. package/packages/core/dist/core/install/orchestrator/orchestrator.d.ts.map +1 -1
  68. package/packages/core/dist/core/install/orchestrator/orchestrator.js +22 -14
  69. package/packages/core/dist/core/install/orchestrator/orchestrator.js.map +1 -1
  70. package/packages/core/dist/core/install/orchestrator/strategies/git-strategy.d.ts +1 -0
  71. package/packages/core/dist/core/install/orchestrator/strategies/git-strategy.d.ts.map +1 -1
  72. package/packages/core/dist/core/install/orchestrator/strategies/git-strategy.js +11 -24
  73. package/packages/core/dist/core/install/orchestrator/strategies/git-strategy.js.map +1 -1
  74. package/packages/core/dist/core/install/orchestrator/strategies/path-strategy.d.ts +2 -0
  75. package/packages/core/dist/core/install/orchestrator/strategies/path-strategy.d.ts.map +1 -1
  76. package/packages/core/dist/core/install/orchestrator/strategies/path-strategy.js +14 -14
  77. package/packages/core/dist/core/install/orchestrator/strategies/path-strategy.js.map +1 -1
  78. package/packages/core/dist/core/install/orchestrator/strategies/registry-strategy.d.ts +7 -0
  79. package/packages/core/dist/core/install/orchestrator/strategies/registry-strategy.d.ts.map +1 -1
  80. package/packages/core/dist/core/install/orchestrator/strategies/registry-strategy.js +28 -0
  81. package/packages/core/dist/core/install/orchestrator/strategies/registry-strategy.js.map +1 -1
  82. package/packages/core/dist/core/install/platform-resolution.d.ts +3 -0
  83. package/packages/core/dist/core/install/platform-resolution.d.ts.map +1 -1
  84. package/packages/core/dist/core/install/platform-resolution.js +5 -2
  85. package/packages/core/dist/core/install/platform-resolution.js.map +1 -1
  86. package/packages/core/dist/core/install/preprocessing/context-population.d.ts +18 -0
  87. package/packages/core/dist/core/install/preprocessing/context-population.d.ts.map +1 -0
  88. package/packages/core/dist/core/install/preprocessing/context-population.js +36 -0
  89. package/packages/core/dist/core/install/preprocessing/context-population.js.map +1 -0
  90. package/packages/core/dist/core/install/preprocessing/convenience-preprocessor.d.ts +23 -0
  91. package/packages/core/dist/core/install/preprocessing/convenience-preprocessor.d.ts.map +1 -1
  92. package/packages/core/dist/core/install/preprocessing/convenience-preprocessor.js +44 -0
  93. package/packages/core/dist/core/install/preprocessing/convenience-preprocessor.js.map +1 -1
  94. package/packages/core/dist/core/install/sources/path-source.d.ts.map +1 -1
  95. package/packages/core/dist/core/install/sources/path-source.js +8 -0
  96. package/packages/core/dist/core/install/sources/path-source.js.map +1 -1
  97. package/packages/core/dist/core/install/unified/context-builders.d.ts +5 -0
  98. package/packages/core/dist/core/install/unified/context-builders.d.ts.map +1 -1
  99. package/packages/core/dist/core/install/unified/context-builders.js +13 -0
  100. package/packages/core/dist/core/install/unified/context-builders.js.map +1 -1
  101. package/packages/core/dist/core/install/unified/context-helpers.d.ts.map +1 -1
  102. package/packages/core/dist/core/install/unified/context-helpers.js +5 -0
  103. package/packages/core/dist/core/install/unified/context-helpers.js.map +1 -1
  104. package/packages/core/dist/core/install/unified/context.d.ts +6 -0
  105. package/packages/core/dist/core/install/unified/context.d.ts.map +1 -1
  106. package/packages/core/dist/core/install/unified/multi-context-pipeline.d.ts.map +1 -1
  107. package/packages/core/dist/core/install/unified/multi-context-pipeline.js +0 -2
  108. package/packages/core/dist/core/install/unified/multi-context-pipeline.js.map +1 -1
  109. package/packages/core/dist/core/install/unified/phases/conflicts.d.ts.map +1 -1
  110. package/packages/core/dist/core/install/unified/phases/conflicts.js +1 -1
  111. package/packages/core/dist/core/install/unified/phases/conflicts.js.map +1 -1
  112. package/packages/core/dist/core/install/unified/phases/execute.d.ts.map +1 -1
  113. package/packages/core/dist/core/install/unified/phases/execute.js +2 -1
  114. package/packages/core/dist/core/install/unified/phases/execute.js.map +1 -1
  115. package/packages/core/dist/core/install/unified/phases/report.js +1 -1
  116. package/packages/core/dist/core/install/unified/phases/report.js.map +1 -1
  117. package/packages/core/dist/core/install/unified/pipeline.d.ts.map +1 -1
  118. package/packages/core/dist/core/install/unified/pipeline.js +5 -2
  119. package/packages/core/dist/core/install/unified/pipeline.js.map +1 -1
  120. package/packages/core/dist/core/ports/resolve.d.ts +0 -13
  121. package/packages/core/dist/core/ports/resolve.d.ts.map +1 -1
  122. package/packages/core/dist/core/ports/resolve.js +0 -28
  123. package/packages/core/dist/core/ports/resolve.js.map +1 -1
  124. package/packages/core/dist/core/remove/removal-confirmation.d.ts +4 -1
  125. package/packages/core/dist/core/remove/removal-confirmation.d.ts.map +1 -1
  126. package/packages/core/dist/core/remove/removal-confirmation.js +5 -4
  127. package/packages/core/dist/core/remove/removal-confirmation.js.map +1 -1
  128. package/packages/core/dist/core/remove/remove-from-source-pipeline.d.ts.map +1 -1
  129. package/packages/core/dist/core/remove/remove-from-source-pipeline.js +1 -10
  130. package/packages/core/dist/core/remove/remove-from-source-pipeline.js.map +1 -1
  131. package/packages/core/dist/core/uninstall/uninstall-executor.js +1 -1
  132. package/packages/core/dist/core/uninstall/uninstall-executor.js.map +1 -1
  133. package/packages/core/dist/core/uninstall/uninstall-reporter.d.ts +2 -2
  134. package/packages/core/dist/core/uninstall/uninstall-reporter.d.ts.map +1 -1
  135. package/packages/core/dist/core/uninstall/uninstall-reporter.js +4 -4
  136. package/packages/core/dist/core/uninstall/uninstall-reporter.js.map +1 -1
  137. package/packages/core/dist/index.d.ts +1 -1
  138. package/packages/core/dist/index.d.ts.map +1 -1
  139. package/packages/core/dist/types/execution-context.d.ts +24 -10
  140. package/packages/core/dist/types/execution-context.d.ts.map +1 -1
@@ -0,0 +1,1136 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ detectPluginWithMarketplace,
4
+ extractBaseVersion,
5
+ extractPackageFromTarball,
6
+ hasPluginContent,
7
+ isUnversionedVersion
8
+ } from "./chunk-TFQ4JBVO.js";
9
+ import {
10
+ getLocalOpenPackageDir,
11
+ getLocalPackageYmlPath,
12
+ getLocalPackagesDir,
13
+ isRootPackage
14
+ } from "./chunk-BCYZDID6.js";
15
+ import {
16
+ loadPackageConfig
17
+ } from "./chunk-V5OW4YEB.js";
18
+ import {
19
+ extractGitHubInfo,
20
+ generateGitHubPackageName
21
+ } from "./chunk-Q2N6OZJC.js";
22
+ import {
23
+ resolveOutput
24
+ } from "./chunk-BROJ6OUT.js";
25
+ import {
26
+ getLatestPackageVersion,
27
+ getPackagePath,
28
+ getPackageVersionPath,
29
+ listPackageVersions
30
+ } from "./chunk-XEPVYZO3.js";
31
+ import {
32
+ parsePackageYml,
33
+ writePackageYml
34
+ } from "./chunk-QTQYI4L5.js";
35
+ import {
36
+ arePackageNamesEquivalent,
37
+ normalizePackageName,
38
+ normalizePackageNameForLookup,
39
+ validatePackageName
40
+ } from "./chunk-VN22A7NW.js";
41
+ import {
42
+ isPlatformId
43
+ } from "./chunk-GKEHDSL4.js";
44
+ import {
45
+ CLAUDE_PLUGIN_PATHS,
46
+ DEPENDENCY_ARRAYS,
47
+ DIR_PATTERNS,
48
+ FILE_PATTERNS,
49
+ PACKAGE_PATHS,
50
+ UNVERSIONED
51
+ } from "./chunk-J4IFFBLP.js";
52
+ import {
53
+ ensureDir,
54
+ exists,
55
+ readTextFile,
56
+ remove,
57
+ walkFiles,
58
+ writeTextFile
59
+ } from "./chunk-S47F4OG4.js";
60
+ import {
61
+ InvalidPackageError,
62
+ PackageNotFoundError,
63
+ ValidationError
64
+ } from "./chunk-ID4SVDQZ.js";
65
+ import {
66
+ logger
67
+ } from "./chunk-5EFWGD33.js";
68
+
69
+ // ../core/src/core/package-management.ts
70
+ import { basename as basename3, relative as relative4 } from "path";
71
+ import semver2 from "semver";
72
+
73
+ // ../core/src/utils/version-ranges.ts
74
+ import * as semver from "semver";
75
+ function parseVersionRange(version) {
76
+ if (!version || version.trim() === "")
77
+ throw new Error("Version cannot be empty");
78
+ let trimmed = version.trim();
79
+ if (trimmed === "*" || trimmed === "latest")
80
+ return {
81
+ type: "wildcard",
82
+ baseVersion: "0.0.0",
83
+ range: "*",
84
+ original: trimmed
85
+ };
86
+ if (trimmed.startsWith("^")) {
87
+ let baseVersion = trimmed.substring(1);
88
+ if (!semver.valid(baseVersion))
89
+ throw new Error(`Invalid base version for caret range: ${baseVersion}`);
90
+ return {
91
+ type: "caret",
92
+ baseVersion,
93
+ range: trimmed,
94
+ original: trimmed
95
+ };
96
+ }
97
+ if (trimmed.startsWith("~")) {
98
+ let baseVersion = trimmed.substring(1);
99
+ if (!semver.valid(baseVersion))
100
+ throw new Error(`Invalid base version for tilde range: ${baseVersion}`);
101
+ return {
102
+ type: "tilde",
103
+ baseVersion,
104
+ range: trimmed,
105
+ original: trimmed
106
+ };
107
+ }
108
+ if (trimmed.match(/^[><=!]+/)) {
109
+ if (!semver.validRange(trimmed))
110
+ throw new Error(`Invalid comparison range: ${trimmed}`);
111
+ return {
112
+ type: "comparison",
113
+ baseVersion: semver.minVersion(trimmed)?.version || "0.0.0",
114
+ range: trimmed,
115
+ original: trimmed
116
+ };
117
+ }
118
+ if (semver.valid(trimmed))
119
+ return {
120
+ type: "exact",
121
+ baseVersion: trimmed,
122
+ range: trimmed,
123
+ original: trimmed
124
+ };
125
+ throw new Error(`Invalid version format: ${trimmed}`);
126
+ }
127
+ function findBestVersion(availableVersions, range) {
128
+ try {
129
+ let sortedVersions = availableVersions.filter((v) => semver.valid(v)).sort((a, b) => semver.compare(b, a));
130
+ return semver.maxSatisfying(sortedVersions, range, { includePrerelease: !0 });
131
+ } catch {
132
+ return null;
133
+ }
134
+ }
135
+ function getLatestVersion(availableVersions) {
136
+ let validVersions = availableVersions.filter((v) => semver.valid(v));
137
+ return validVersions.length === 0 ? null : validVersions.sort((a, b) => semver.compare(b, a))[0];
138
+ }
139
+ function createCaretRange(version) {
140
+ if (!semver.valid(version))
141
+ throw new Error(`Invalid version for caret range: ${version}`);
142
+ return `^${version}`;
143
+ }
144
+ function isExactVersion(version) {
145
+ try {
146
+ return parseVersionRange(version).type === "exact";
147
+ } catch {
148
+ return !1;
149
+ }
150
+ }
151
+ function resolveVersionRange(version, availableVersions) {
152
+ try {
153
+ let parsed = parseVersionRange(version);
154
+ switch (parsed.type) {
155
+ case "exact":
156
+ return availableVersions.includes(parsed.baseVersion) ? parsed.baseVersion : null;
157
+ case "wildcard":
158
+ return getLatestVersion(availableVersions);
159
+ default:
160
+ return findBestVersion(availableVersions, parsed.range);
161
+ }
162
+ } catch {
163
+ return null;
164
+ }
165
+ }
166
+ function isPrereleaseVersion(version) {
167
+ let parsed = semver.parse(version);
168
+ return !!(parsed && parsed.prerelease.length > 0);
169
+ }
170
+ function hasExplicitPrereleaseIntent(range) {
171
+ let trimmed = range.trim();
172
+ if (!trimmed || trimmed === "*" || trimmed.toLowerCase() === "latest" || !trimmed.includes("-"))
173
+ return !1;
174
+ try {
175
+ let parsedRange = new semver.Range(trimmed, { includePrerelease: !0 });
176
+ for (let comparatorSet of parsedRange.set)
177
+ for (let comparator of comparatorSet)
178
+ if (comparator.semver.prerelease.length > 0)
179
+ return !0;
180
+ } catch {
181
+ return !1;
182
+ }
183
+ return !1;
184
+ }
185
+ function selectVersionWithWipPolicy(availableVersions, range, options) {
186
+ let parsedRange = parseVersionRange(range), deduped = dedupeValidVersions(availableVersions), availableStable = sortVersionsDesc(deduped.filter((version) => !isPrereleaseVersion(version))), availablePrerelease = sortVersionsDesc(deduped.filter((version) => isPrereleaseVersion(version))), satisfyingStable = [], satisfyingPrerelease = [], result = {
187
+ version: null,
188
+ isPrerelease: !1,
189
+ satisfyingStable,
190
+ satisfyingPrerelease,
191
+ availableStable,
192
+ availablePrerelease,
193
+ reason: "none"
194
+ }, finish = () => result;
195
+ if (parsedRange.type === "exact") {
196
+ result.reason = "exact";
197
+ let exactMatch = deduped.find((version) => semver.eq(version, parsedRange.baseVersion));
198
+ return exactMatch && (isPrereleaseVersion(exactMatch) ? (satisfyingPrerelease.push(exactMatch), result.isPrerelease = !0) : satisfyingStable.push(exactMatch), result.version = exactMatch), finish();
199
+ }
200
+ let normalizedRange = parsedRange.type === "wildcard" ? "*" : parsedRange.range;
201
+ satisfyingStable.push(
202
+ ...filterSatisfying(availableStable, normalizedRange, !1)
203
+ ), satisfyingPrerelease.push(
204
+ ...filterSatisfying(availablePrerelease, normalizedRange, !0)
205
+ );
206
+ let allSatisfying = sortVersionsDesc([
207
+ ...satisfyingStable,
208
+ ...satisfyingPrerelease
209
+ ]);
210
+ if (parsedRange.type === "wildcard" ? result.reason = "wildcard" : result.reason = "range", allSatisfying.length === 0)
211
+ return finish();
212
+ let selected = allSatisfying[0];
213
+ return result.version = selected, result.isPrerelease = isPrereleaseVersion(selected), finish();
214
+ }
215
+ function dedupeValidVersions(versions) {
216
+ let seen = /* @__PURE__ */ new Set();
217
+ for (let version of versions)
218
+ !version || !semver.valid(version) || seen.has(version) || seen.add(version);
219
+ return Array.from(seen);
220
+ }
221
+ function sortVersionsDesc(versions) {
222
+ return versions.slice().sort(semver.rcompare);
223
+ }
224
+ function filterSatisfying(versions, range, includePrerelease) {
225
+ try {
226
+ return sortVersionsDesc(
227
+ versions.filter((version) => semver.satisfies(version, range, { includePrerelease }))
228
+ );
229
+ } catch {
230
+ return [];
231
+ }
232
+ }
233
+
234
+ // ../core/src/core/package.ts
235
+ import { join as join3, relative as relative3, dirname, basename as basename2 } from "path";
236
+ import { isJunk as isJunk3 } from "junk";
237
+
238
+ // ../core/src/core/install/plugin-transformer.ts
239
+ import { relative } from "path";
240
+ import { isJunk } from "junk";
241
+
242
+ // ../core/src/core/conversion-context/creation.ts
243
+ function createContextFromFormat(format) {
244
+ let now = /* @__PURE__ */ new Date(), originalFormat = {
245
+ type: format.type,
246
+ platform: format.platform,
247
+ detectedAt: now,
248
+ confidence: format.confidence
249
+ }, currentFormat = {
250
+ type: format.type,
251
+ platform: format.platform
252
+ };
253
+ return logger.debug("Created conversion context from format", {
254
+ type: format.type,
255
+ platform: format.platform,
256
+ confidence: format.confidence
257
+ }), {
258
+ originalFormat,
259
+ currentFormat,
260
+ conversionHistory: [],
261
+ targetPlatform: void 0
262
+ };
263
+ }
264
+ function createContextFromPackage(pkg) {
265
+ let format = pkg._format || detectPackageFormat(pkg.files);
266
+ return logger.debug("Creating context from package", {
267
+ name: pkg.metadata.name,
268
+ hasFormat: !!pkg._format,
269
+ detectedType: format.type,
270
+ detectedPlatform: format.platform
271
+ }), createContextFromFormat(format);
272
+ }
273
+ function createPlatformContext(platform, confidence = 1) {
274
+ let originalFormat = {
275
+ type: "platform-specific",
276
+ platform,
277
+ detectedAt: /* @__PURE__ */ new Date(),
278
+ confidence
279
+ }, currentFormat = {
280
+ type: "platform-specific",
281
+ platform
282
+ };
283
+ return logger.debug("Created platform-specific context", { platform, confidence }), {
284
+ originalFormat,
285
+ currentFormat,
286
+ conversionHistory: [],
287
+ targetPlatform: void 0
288
+ };
289
+ }
290
+ function withTargetPlatform(context, targetPlatform) {
291
+ return {
292
+ ...context,
293
+ targetPlatform
294
+ };
295
+ }
296
+ function updateContextAfterConversion(context, newFormat, targetPlatform) {
297
+ let timestamp = /* @__PURE__ */ new Date(), newHistory = [
298
+ ...context.conversionHistory,
299
+ {
300
+ from: context.currentFormat,
301
+ to: newFormat,
302
+ targetPlatform,
303
+ timestamp
304
+ }
305
+ ];
306
+ return logger.debug("Updated context after conversion", {
307
+ from: {
308
+ type: context.currentFormat.type,
309
+ platform: context.currentFormat.platform
310
+ },
311
+ to: {
312
+ type: newFormat.type,
313
+ platform: newFormat.platform
314
+ },
315
+ targetPlatform,
316
+ totalConversions: newHistory.length
317
+ }), {
318
+ ...context,
319
+ currentFormat: newFormat,
320
+ conversionHistory: newHistory,
321
+ targetPlatform
322
+ };
323
+ }
324
+
325
+ // ../core/src/core/conversion-context/serialization.ts
326
+ function serializeContext(context, options) {
327
+ let includeHistory = options?.includeHistory ?? !0;
328
+ return {
329
+ originalFormat: {
330
+ type: context.originalFormat.type,
331
+ platform: context.originalFormat.platform,
332
+ detectedAt: context.originalFormat.detectedAt.toISOString(),
333
+ confidence: context.originalFormat.confidence
334
+ },
335
+ currentFormat: {
336
+ type: context.currentFormat.type,
337
+ platform: context.currentFormat.platform
338
+ },
339
+ conversionHistory: includeHistory ? context.conversionHistory.map((record) => ({
340
+ from: {
341
+ type: record.from.type,
342
+ platform: record.from.platform
343
+ },
344
+ to: {
345
+ type: record.to.type,
346
+ platform: record.to.platform
347
+ },
348
+ targetPlatform: record.targetPlatform,
349
+ timestamp: record.timestamp.toISOString()
350
+ })) : [],
351
+ targetPlatform: context.targetPlatform
352
+ };
353
+ }
354
+ function contextToJSON(context, options) {
355
+ let serialized = serializeContext(context, options), pretty = options?.pretty ?? !0;
356
+ return JSON.stringify(serialized, null, pretty ? 2 : 0);
357
+ }
358
+
359
+ // ../core/src/core/install/format-detector.ts
360
+ var UNIVERSAL_SUBDIRS = [
361
+ "commands",
362
+ "agents",
363
+ "rules",
364
+ "skills",
365
+ "hooks"
366
+ ], PLATFORM_ROOT_DIRS = {
367
+ ".claude": "claude",
368
+ ".claude-plugin": "claude-plugin",
369
+ ".cursor": "cursor",
370
+ ".opencode": "opencode",
371
+ ".codex": "codex",
372
+ ".factory": "factory",
373
+ ".kilocode": "kilo",
374
+ ".kiro": "kiro",
375
+ ".qwen": "qwen",
376
+ ".roo": "roo",
377
+ ".warp": "warp",
378
+ ".windsurf": "windsurf",
379
+ ".augment": "augment",
380
+ ".agent": "antigravity"
381
+ };
382
+ function detectPackageFormat(files) {
383
+ if (files.some(
384
+ (f) => f.path === ".claude-plugin/plugin.json"
385
+ ))
386
+ return {
387
+ type: "platform-specific",
388
+ platform: "claude-plugin",
389
+ confidence: 1,
390
+ analysis: {
391
+ universalFiles: 0,
392
+ platformSpecificFiles: files.length,
393
+ detectedPlatforms: /* @__PURE__ */ new Map([["claude-plugin", files.length]]),
394
+ totalFiles: files.length,
395
+ samplePaths: {
396
+ universal: [],
397
+ platformSpecific: [".claude-plugin/plugin.json"]
398
+ }
399
+ }
400
+ };
401
+ let analysis = {
402
+ universalFiles: 0,
403
+ platformSpecificFiles: 0,
404
+ detectedPlatforms: /* @__PURE__ */ new Map(),
405
+ totalFiles: files.length,
406
+ samplePaths: {
407
+ universal: [],
408
+ platformSpecific: []
409
+ }
410
+ };
411
+ for (let file of files) {
412
+ let classification = classifyFile(file.path);
413
+ if (classification.type === "universal")
414
+ analysis.universalFiles++, analysis.samplePaths.universal.length < 5 && analysis.samplePaths.universal.push(file.path);
415
+ else if (classification.type === "platform-specific" && classification.platform) {
416
+ analysis.platformSpecificFiles++;
417
+ let count = analysis.detectedPlatforms.get(classification.platform) || 0;
418
+ analysis.detectedPlatforms.set(classification.platform, count + 1), analysis.samplePaths.platformSpecific.length < 5 && analysis.samplePaths.platformSpecific.push(file.path);
419
+ }
420
+ }
421
+ return determineFormat(analysis);
422
+ }
423
+ function classifyFile(path) {
424
+ let firstPart = path.split("/")[0];
425
+ if (firstPart in PLATFORM_ROOT_DIRS)
426
+ return {
427
+ type: "platform-specific",
428
+ platform: PLATFORM_ROOT_DIRS[firstPart]
429
+ };
430
+ let platformSuffix = extractPlatformSuffixFromPath(path);
431
+ return platformSuffix ? {
432
+ type: "platform-specific",
433
+ platform: platformSuffix
434
+ } : UNIVERSAL_SUBDIRS.includes(firstPart) ? { type: "universal" } : { type: "other" };
435
+ }
436
+ function extractPlatformSuffixFromPath(path) {
437
+ let parts = path.split("/"), nameParts = parts[parts.length - 1].split(".");
438
+ if (nameParts.length >= 3) {
439
+ let possiblePlatform = nameParts[nameParts.length - 2];
440
+ if (isPlatformId(possiblePlatform))
441
+ return possiblePlatform;
442
+ }
443
+ return null;
444
+ }
445
+ function determineFormat(analysis) {
446
+ let { universalFiles, platformSpecificFiles, detectedPlatforms, totalFiles } = analysis;
447
+ if (totalFiles === 0)
448
+ return {
449
+ type: "universal",
450
+ confidence: 0,
451
+ analysis
452
+ };
453
+ let universalRatio = universalFiles / totalFiles, platformRatio = platformSpecificFiles / totalFiles;
454
+ if (universalRatio > 0.7)
455
+ return {
456
+ type: "universal",
457
+ confidence: universalRatio,
458
+ analysis
459
+ };
460
+ if (platformRatio > 0.7) {
461
+ let dominantPlatform, maxCount = 0;
462
+ for (let [platform, count] of detectedPlatforms)
463
+ count > maxCount && (maxCount = count, dominantPlatform = platform);
464
+ if (dominantPlatform)
465
+ return {
466
+ type: "platform-specific",
467
+ platform: dominantPlatform,
468
+ confidence: platformRatio,
469
+ analysis
470
+ };
471
+ }
472
+ return {
473
+ type: "universal",
474
+ confidence: Math.max(universalRatio, 0.3),
475
+ analysis
476
+ };
477
+ }
478
+ function isPlatformSpecific(format) {
479
+ return format.type === "platform-specific" && format.platform !== void 0;
480
+ }
481
+ function needsConversion(format, targetPlatform) {
482
+ return format.type === "universal" ? !1 : format.type === "platform-specific" && format.platform ? format.platform !== targetPlatform : !1;
483
+ }
484
+ function detectPackageFormatWithContext(files) {
485
+ let format = detectPackageFormat(files), context = createContextFromFormat(format);
486
+ return { format, context };
487
+ }
488
+ async function detectEnhancedPackageFormat(files, targetDir) {
489
+ let { detectPlatformMarkers, getPrimaryPlatformFromMarkers, isPurePlatformSpecific } = await import("./package-marker-detector-JELOHCL7.js"), { detectFileFormats } = await import("./file-format-detector-DEAVQPAT.js"), {
490
+ analyzeFormatDistribution,
491
+ calculatePackageConfidence,
492
+ determinePackageFormat: determineFromDistribution,
493
+ groupFilesByPlatform
494
+ } = await import("./format-distribution-analyzer-MIFCFIAJ.js"), markers = detectPlatformMarkers(files, targetDir);
495
+ if (isPurePlatformSpecific(markers)) {
496
+ let primaryPlatform = getPrimaryPlatformFromMarkers(markers);
497
+ return {
498
+ packageFormat: primaryPlatform,
499
+ detectionMethod: "package-marker",
500
+ confidence: 1,
501
+ // For marker fast-path, we still need format groups so conversion can run.
502
+ // Group everything under the detected platform; individual files can be no-ops
503
+ // if no import flow matches (e.g. plugin manifests).
504
+ formatGroups: /* @__PURE__ */ new Map([[primaryPlatform, files.map((f) => f.path)]]),
505
+ markers: {
506
+ matchedPatterns: markers.matches.map((m) => ({
507
+ platformId: m.platformId,
508
+ pattern: m.matchedPattern
509
+ })),
510
+ hasOpenPackageYml: markers.hasOpenPackageYml,
511
+ hasPackageYml: markers.hasPackageYml
512
+ },
513
+ analysis: {
514
+ totalFiles: files.length,
515
+ analyzedFiles: 0,
516
+ // Fast path - didn't analyze files
517
+ skippedFiles: files.length,
518
+ formatDistribution: /* @__PURE__ */ new Map([[primaryPlatform, files.length]])
519
+ }
520
+ };
521
+ }
522
+ if ((markers.hasOpenPackageYml || markers.hasPackageYml) && markers.matches.length === 0)
523
+ return {
524
+ packageFormat: "universal",
525
+ detectionMethod: "package-marker",
526
+ confidence: 1,
527
+ formatGroups: /* @__PURE__ */ new Map([["universal", files.map((f) => f.path)]]),
528
+ markers: {
529
+ matchedPatterns: [],
530
+ hasOpenPackageYml: markers.hasOpenPackageYml,
531
+ hasPackageYml: markers.hasPackageYml
532
+ },
533
+ analysis: {
534
+ totalFiles: files.length,
535
+ analyzedFiles: 0,
536
+ skippedFiles: files.length,
537
+ formatDistribution: /* @__PURE__ */ new Map([["universal", files.length]])
538
+ }
539
+ };
540
+ let fileFormats = detectFileFormats(files, targetDir), distribution = analyzeFormatDistribution(fileFormats), confidence = calculatePackageConfidence(distribution, fileFormats), packageFormat = determineFromDistribution(distribution), formatGroups = groupFilesByPlatform(fileFormats), analyzedFiles = fileFormats.size, skippedFiles = files.length - analyzedFiles;
541
+ return {
542
+ packageFormat,
543
+ detectionMethod: "per-file",
544
+ confidence,
545
+ fileFormats,
546
+ formatGroups,
547
+ markers: markers.matches.length > 0 ? {
548
+ matchedPatterns: markers.matches.map((m) => ({
549
+ platformId: m.platformId,
550
+ pattern: m.matchedPattern
551
+ })),
552
+ hasOpenPackageYml: markers.hasOpenPackageYml,
553
+ hasPackageYml: markers.hasPackageYml
554
+ } : void 0,
555
+ analysis: {
556
+ totalFiles: files.length,
557
+ analyzedFiles,
558
+ skippedFiles,
559
+ formatDistribution: distribution.counts
560
+ }
561
+ };
562
+ }
563
+
564
+ // ../core/src/core/install/plugin-metadata-resolver.ts
565
+ import { join } from "path";
566
+ async function resolvePluginMetadata(pluginDir, marketplaceEntry) {
567
+ let manifestPath = join(pluginDir, CLAUDE_PLUGIN_PATHS.PLUGIN_MANIFEST), hasPluginJson = await exists(manifestPath), isStrictFalse = marketplaceEntry?.strict === !1;
568
+ if (hasPluginJson) {
569
+ let pluginManifest;
570
+ try {
571
+ let content = await readTextFile(manifestPath);
572
+ pluginManifest = JSON.parse(content);
573
+ } catch (error) {
574
+ throw new ValidationError(
575
+ `Failed to parse plugin manifest at ${manifestPath}: ${error}`
576
+ );
577
+ }
578
+ return isStrictFalse ? (logger.warn(
579
+ `Plugin at '${pluginDir}' has strict:false in marketplace but contains plugin.json. Using plugin.json as primary source. Consider removing plugin.json or setting strict:true.`
580
+ ), {
581
+ manifest: pluginManifest,
582
+ source: "plugin.json"
583
+ }) : marketplaceEntry ? {
584
+ manifest: mergePluginMetadata(pluginManifest, marketplaceEntry),
585
+ source: "merged"
586
+ } : {
587
+ manifest: pluginManifest,
588
+ source: "plugin.json"
589
+ };
590
+ }
591
+ if (isStrictFalse && marketplaceEntry)
592
+ return {
593
+ manifest: marketplaceEntryToManifest(marketplaceEntry),
594
+ source: "marketplace"
595
+ };
596
+ throw marketplaceEntry ? new ValidationError(
597
+ `Plugin '${marketplaceEntry.name}' at '${pluginDir}' is missing plugin.json. Either add .claude-plugin/plugin.json or set "strict": false in marketplace entry.`
598
+ ) : new ValidationError(
599
+ `Plugin at '${pluginDir}' is missing plugin.json at ${CLAUDE_PLUGIN_PATHS.PLUGIN_MANIFEST}`
600
+ );
601
+ }
602
+ function mergePluginMetadata(pluginManifest, marketplaceEntry) {
603
+ return {
604
+ name: pluginManifest.name,
605
+ // Always use plugin.json name
606
+ version: pluginManifest.version ?? marketplaceEntry.version,
607
+ description: pluginManifest.description ?? marketplaceEntry.description,
608
+ author: pluginManifest.author ?? marketplaceEntry.author,
609
+ homepage: pluginManifest.homepage ?? marketplaceEntry.homepage,
610
+ repository: pluginManifest.repository ?? marketplaceEntry.repository,
611
+ license: pluginManifest.license ?? marketplaceEntry.license,
612
+ keywords: pluginManifest.keywords ?? marketplaceEntry.keywords,
613
+ commands: pluginManifest.commands ?? marketplaceEntry.commands,
614
+ agents: pluginManifest.agents ?? marketplaceEntry.agents,
615
+ hooks: pluginManifest.hooks ?? marketplaceEntry.hooks,
616
+ mcpServers: pluginManifest.mcpServers ?? marketplaceEntry.mcpServers,
617
+ lspServers: pluginManifest.lspServers ?? marketplaceEntry.lspServers
618
+ };
619
+ }
620
+ function marketplaceEntryToManifest(entry) {
621
+ return {
622
+ name: entry.name,
623
+ version: entry.version,
624
+ description: entry.description,
625
+ author: entry.author,
626
+ homepage: entry.homepage,
627
+ repository: entry.repository,
628
+ license: entry.license,
629
+ keywords: entry.keywords,
630
+ commands: entry.commands,
631
+ agents: entry.agents,
632
+ hooks: entry.hooks,
633
+ mcpServers: entry.mcpServers,
634
+ lspServers: entry.lspServers
635
+ };
636
+ }
637
+
638
+ // ../core/src/core/install/plugin-transformer.ts
639
+ var transformedPluginCache = /* @__PURE__ */ new Map();
640
+ function cacheTransformedPlugin(pkg, context) {
641
+ let key = `${pkg.metadata.name}@${pkg.metadata.version}`, cached = context ? { package: pkg, context } : { package: pkg, context: createPlatformContext("claude-plugin", 1) };
642
+ transformedPluginCache.set(key, cached);
643
+ }
644
+ function getTransformedPlugin(name, version) {
645
+ let key = `${name}@${version}`;
646
+ return transformedPluginCache.get(key);
647
+ }
648
+ async function transformPluginToPackage(pluginDir, context) {
649
+ let pluginManifest = (await resolvePluginMetadata(pluginDir, context?.marketplaceEntry)).manifest, metadata = {
650
+ name: generateGitHubPackageName({
651
+ gitUrl: context?.gitUrl,
652
+ path: context?.path,
653
+ resourcePath: context?.resourcePath,
654
+ packageName: pluginManifest.name,
655
+ repoPath: context?.repoPath
656
+ }),
657
+ // Claude Code plugins often omit version; normalize to a concrete value so:
658
+ // - logs/install output are consistent
659
+ // - transformed plugin cache keys remain stable
660
+ version: pluginManifest.version?.trim() || "0.0.0",
661
+ description: pluginManifest.description,
662
+ keywords: pluginManifest.keywords,
663
+ license: pluginManifest.license,
664
+ homepage: pluginManifest.homepage
665
+ };
666
+ pluginManifest.author?.name && (metadata.author = pluginManifest.author.name), pluginManifest.repository && (typeof pluginManifest.repository == "string" ? metadata.repository = {
667
+ type: "git",
668
+ url: pluginManifest.repository
669
+ } : pluginManifest.repository.url && (metadata.repository = {
670
+ type: pluginManifest.repository.type || "git",
671
+ url: pluginManifest.repository.url
672
+ }));
673
+ let files = await extractPluginFiles(pluginDir), format = detectPackageFormat(files), pkg = {
674
+ metadata,
675
+ files,
676
+ // Store format metadata for installation pipeline
677
+ _format: format
678
+ }, conversionContext = createPlatformContext("claude-plugin", format.confidence);
679
+ return cacheTransformedPlugin(pkg, conversionContext), logger.info("Transformed Claude Code plugin", {
680
+ name: metadata.name,
681
+ version: metadata.version,
682
+ fileCount: files.length,
683
+ format: format.type,
684
+ platform: format.platform,
685
+ confidence: format.confidence
686
+ }), { package: pkg, context: conversionContext };
687
+ }
688
+ async function extractPluginFiles(pluginDir) {
689
+ let files = [];
690
+ try {
691
+ for await (let fullPath of walkFiles(pluginDir)) {
692
+ let relativePath = relative(pluginDir, fullPath);
693
+ if (relativePath.split("/").some((part) => isJunk(part)) || relativePath.startsWith(".git/") || relativePath === ".git" || relativePath.startsWith(`${DIR_PATTERNS.CLAUDE_PLUGIN}/`))
694
+ continue;
695
+ let content = await readTextFile(fullPath);
696
+ files.push({
697
+ path: relativePath,
698
+ content,
699
+ encoding: "utf8"
700
+ });
701
+ }
702
+ return files;
703
+ } catch (error) {
704
+ throw new ValidationError(
705
+ `Failed to extract files from plugin directory ${pluginDir}: ${error}`
706
+ );
707
+ }
708
+ }
709
+
710
+ // ../core/src/core/install/path-package-loader.ts
711
+ import { relative as relative2, basename } from "path";
712
+ import { readFile } from "fs/promises";
713
+ import { isJunk as isJunk2 } from "junk";
714
+ import * as yaml from "js-yaml";
715
+ function inferSourceType(path) {
716
+ return path.endsWith(FILE_PATTERNS.TGZ_FILES) || path.endsWith(FILE_PATTERNS.TAR_GZ_FILES) ? "tarball" : "directory";
717
+ }
718
+ async function loadPackageFromDirectory(dirPath, context) {
719
+ let pluginDetection = await detectPluginWithMarketplace(dirPath, context?.marketplaceEntry);
720
+ if (pluginDetection.isPlugin && (pluginDetection.type === "individual" || pluginDetection.type === "marketplace-defined")) {
721
+ logger.info(`Detected Claude Code plugin (${pluginDetection.type}), transforming to OpenPackage format`, { dirPath });
722
+ let { package: pkg } = await transformPluginToPackage(dirPath, context);
723
+ return pkg;
724
+ }
725
+ if (pluginDetection.isPlugin && pluginDetection.type === "marketplace")
726
+ throw new ValidationError(
727
+ `Directory '${dirPath}' is a Claude Code plugin marketplace. Marketplace installation requires plugin selection and should be handled by the install command.`
728
+ );
729
+ let config = await loadPackageConfig(dirPath);
730
+ if (!config) {
731
+ if (await hasPluginContent(dirPath)) {
732
+ let syntheticEntry = {
733
+ strict: !1,
734
+ name: context?.packageName ?? basename(dirPath),
735
+ source: "."
736
+ // minimal spec for marketplace-defined plugin without marketplace manifest
737
+ }, marketplaceDefined = await detectPluginWithMarketplace(dirPath, syntheticEntry);
738
+ if (marketplaceDefined.isPlugin && marketplaceDefined.type === "marketplace-defined") {
739
+ let { package: pkg } = await transformPluginToPackage(dirPath, {
740
+ ...context,
741
+ marketplaceEntry: syntheticEntry
742
+ });
743
+ return pkg;
744
+ }
745
+ }
746
+ if (!context?.resourcePath)
747
+ throw new ValidationError(
748
+ `Directory '${dirPath}' is not a valid OpenPackage directory or Claude Code plugin. Missing ${FILE_PATTERNS.OPENPACKAGE_YML} or ${CLAUDE_PLUGIN_PATHS.PLUGIN_MANIFEST}`
749
+ );
750
+ let fallbackBaseName = basename(dirPath);
751
+ config = {
752
+ name: context?.gitUrl ? generateGitHubPackageName({
753
+ gitUrl: context.gitUrl,
754
+ path: context.path,
755
+ resourcePath: context.resourcePath,
756
+ packageName: fallbackBaseName,
757
+ repoPath: context.repoPath
758
+ }) : fallbackBaseName,
759
+ version: "0.0.0"
760
+ };
761
+ }
762
+ if (context?.gitUrl) {
763
+ let originalName = config.name, scopedName = generateGitHubPackageName({
764
+ gitUrl: context.gitUrl,
765
+ path: context.path,
766
+ resourcePath: context.resourcePath,
767
+ packageName: originalName,
768
+ // Pass original name for non-GitHub sources
769
+ repoPath: context.repoPath
770
+ });
771
+ scopedName !== originalName && (config.name = scopedName);
772
+ }
773
+ let files = [];
774
+ try {
775
+ for await (let fullPath of walkFiles(dirPath)) {
776
+ let relativePath = relative2(dirPath, fullPath);
777
+ if (isJunk2(basename(relativePath)))
778
+ continue;
779
+ let content = await readTextFile(fullPath);
780
+ files.push({
781
+ path: relativePath,
782
+ content,
783
+ encoding: "utf8"
784
+ });
785
+ }
786
+ return {
787
+ metadata: config,
788
+ files
789
+ };
790
+ } catch (error) {
791
+ throw logger.error(`Failed to load package from directory: ${dirPath}`, { error }), new ValidationError(`Failed to load package from directory: ${error}`);
792
+ }
793
+ }
794
+ async function loadPackageFromTarball(tarballPath) {
795
+ let tarballBuffer;
796
+ try {
797
+ tarballBuffer = await readFile(tarballPath);
798
+ } catch (error) {
799
+ throw new ValidationError(`Failed to read tarball file '${tarballPath}': ${error}`);
800
+ }
801
+ let extracted = await extractPackageFromTarball(tarballBuffer), packageYmlFile = extracted.files.find(
802
+ (f) => f.path === PACKAGE_PATHS.MANIFEST_RELATIVE || f.path === "openpackage.yml"
803
+ );
804
+ if (!packageYmlFile)
805
+ throw new ValidationError(
806
+ `Tarball '${tarballPath}' does not contain a valid ${FILE_PATTERNS.OPENPACKAGE_YML} file`
807
+ );
808
+ let config = yaml.load(packageYmlFile.content);
809
+ if (!config.name)
810
+ throw new ValidationError(
811
+ `Tarball '${tarballPath}' contains invalid ${FILE_PATTERNS.OPENPACKAGE_YML}: missing name field`
812
+ );
813
+ return logger.debug(`Loaded package ${config.name}@${config.version} from tarball: ${tarballPath}`), {
814
+ metadata: config,
815
+ files: extracted.files
816
+ };
817
+ }
818
+ async function loadPackageFromPath(path, context) {
819
+ return inferSourceType(path) === "tarball" ? await loadPackageFromTarball(path) : await loadPackageFromDirectory(path, context);
820
+ }
821
+
822
+ // ../core/src/core/package.ts
823
+ var PackageManager = class {
824
+ /**
825
+ * Load a package from the registry (latest version by default)
826
+ */
827
+ async loadPackage(packageName, version, opts) {
828
+ if (logger.debug(`Loading package: ${packageName}`, { version }), validatePackageName(packageName), version) {
829
+ let cachedPluginWithContext = getTransformedPlugin(packageName, version);
830
+ if (cachedPluginWithContext)
831
+ return logger.debug(`Using cached transformed plugin: ${packageName}@${version}`), cachedPluginWithContext.package;
832
+ }
833
+ let targetVersion = opts?.packageRootDir ? version ?? null : null;
834
+ if (!opts?.packageRootDir)
835
+ if (version === UNVERSIONED)
836
+ targetVersion = UNVERSIONED;
837
+ else if (version)
838
+ if (isExactVersion(version))
839
+ targetVersion = version;
840
+ else {
841
+ let availableVersions = await listPackageVersions(packageName);
842
+ if (availableVersions.length === 0)
843
+ throw new PackageNotFoundError(packageName);
844
+ if (targetVersion = resolveVersionRange(version, availableVersions), !targetVersion)
845
+ throw new PackageNotFoundError(
846
+ `No version of '${packageName}' satisfies range '${version}'. Available versions: ${availableVersions.join(", ")}`
847
+ );
848
+ logger.debug(`Resolved version range '${version}' to '${targetVersion}' for package '${packageName}'`);
849
+ }
850
+ else
851
+ targetVersion = await getLatestPackageVersion(packageName);
852
+ if (!targetVersion && !opts?.packageRootDir)
853
+ throw new PackageNotFoundError(packageName);
854
+ let packagePath = opts?.packageRootDir ? opts.packageRootDir : getPackageVersionPath(packageName, targetVersion ?? void 0);
855
+ if (!await exists(packagePath))
856
+ throw new PackageNotFoundError(packageName);
857
+ try {
858
+ return await loadPackageFromPath(packagePath, { packageName });
859
+ } catch (error) {
860
+ throw error instanceof PackageNotFoundError || error.name === "ValidationError" ? new PackageNotFoundError(packageName) : (logger.error(`Failed to load package: ${packageName}`, { error }), new InvalidPackageError(`Failed to load package: ${error}`));
861
+ }
862
+ }
863
+ /**
864
+ * Save a package to the registry (versioned)
865
+ */
866
+ async savePackage(pkg, options = {}) {
867
+ let { metadata, files } = pkg, packagePath = getPackageVersionPath(metadata.name, metadata.version);
868
+ logger.debug(`Saving package: ${metadata.name}@${metadata.version ?? UNVERSIONED}`, { packagePath });
869
+ try {
870
+ await ensureDir(packagePath);
871
+ for (let file of files) {
872
+ let fullPath = join3(packagePath, file.path);
873
+ await ensureDir(dirname(fullPath)), await writeTextFile(fullPath, file.content, file.encoding || "utf8");
874
+ }
875
+ options.partial ? await this.markPartialInManifest(packagePath) : await this.clearPartialInManifest(packagePath), logger.info(`Package '${metadata.name}@${metadata.version}' saved successfully`);
876
+ } catch (error) {
877
+ throw logger.error(`Failed to save package: ${metadata.name}@${metadata.version}`, { error }), new InvalidPackageError(`Failed to save package: ${error}`);
878
+ }
879
+ }
880
+ /**
881
+ * Delete a specific version of a package
882
+ */
883
+ async deletePackageVersion(packageName, version) {
884
+ logger.info(`Deleting package version: ${packageName}@${version}`), validatePackageName(packageName);
885
+ let packagePath = getPackageVersionPath(packageName, version);
886
+ if (!await exists(packagePath))
887
+ throw new PackageNotFoundError(`${packageName}@${version}`);
888
+ try {
889
+ await remove(packagePath), logger.info(`Package version '${packageName}@${version}' deleted successfully`);
890
+ } catch (error) {
891
+ throw logger.error(`Failed to delete package version: ${packageName}@${version}`, { error }), new InvalidPackageError(`Failed to delete package version: ${error}`);
892
+ }
893
+ }
894
+ /**
895
+ * Delete all versions of a package
896
+ */
897
+ async deletePackage(packageName) {
898
+ logger.info(`Deleting all versions of package: ${packageName}`), validatePackageName(packageName);
899
+ let packagePath = getPackagePath(packageName);
900
+ if (!await exists(packagePath))
901
+ throw new PackageNotFoundError(packageName);
902
+ try {
903
+ await remove(packagePath), logger.info(`All versions of package '${packageName}' deleted successfully`);
904
+ } catch (error) {
905
+ throw logger.error(`Failed to delete package: ${packageName}`, { error }), new InvalidPackageError(`Failed to delete package: ${error}`);
906
+ }
907
+ }
908
+ /**
909
+ * Check if a package exists in the registry (any version)
910
+ */
911
+ async packageExists(packageName) {
912
+ return validatePackageName(packageName), await getLatestPackageVersion(packageName) !== null;
913
+ }
914
+ /**
915
+ * Return local state for a specific package version, including partial metadata.
916
+ */
917
+ async getPackageVersionState(packageName, version) {
918
+ let packagePath = getPackageVersionPath(packageName, version);
919
+ if (!await exists(packagePath))
920
+ return { exists: !1, isPartial: !1, paths: [] };
921
+ let manifestPath = join3(packagePath, PACKAGE_PATHS.MANIFEST_RELATIVE), manifestExists = await exists(manifestPath), isPartial = !manifestExists;
922
+ if (manifestExists)
923
+ try {
924
+ isPartial = !!(await parsePackageYml(manifestPath)).partial;
925
+ } catch (error) {
926
+ logger.warn("Failed to read package manifest for partial state", { packageName, version, error }), isPartial = !0;
927
+ }
928
+ let paths = await this.listPackageFilePaths(packagePath);
929
+ return { exists: !0, isPartial, paths };
930
+ }
931
+ /**
932
+ * Discover all files in a package directory
933
+ */
934
+ async discoverPackageFiles(packagePath) {
935
+ let files = [];
936
+ try {
937
+ for await (let fullPath of walkFiles(packagePath)) {
938
+ let relativePath = relative3(packagePath, fullPath);
939
+ if (isJunk3(basename2(relativePath)))
940
+ continue;
941
+ let content = await readTextFile(fullPath);
942
+ files.push({
943
+ path: relativePath,
944
+ content,
945
+ encoding: "utf8"
946
+ });
947
+ }
948
+ return logger.debug(`Discovered ${files.length} files in package directory`, { packagePath }), files;
949
+ } catch (error) {
950
+ throw logger.error(`Failed to discover files in package directory: ${packagePath}`, { error }), new InvalidPackageError(`Failed to discover package files: ${error}`);
951
+ }
952
+ }
953
+ async markPartialInManifest(packagePath) {
954
+ let manifestPath = join3(packagePath, PACKAGE_PATHS.MANIFEST_RELATIVE);
955
+ if (!await exists(manifestPath))
956
+ return;
957
+ let manifest = await parsePackageYml(manifestPath);
958
+ manifest.partial = !0, await writePackageYml(manifestPath, manifest);
959
+ }
960
+ async clearPartialInManifest(packagePath) {
961
+ let manifestPath = join3(packagePath, PACKAGE_PATHS.MANIFEST_RELATIVE);
962
+ if (!await exists(manifestPath))
963
+ return;
964
+ let manifest = await parsePackageYml(manifestPath);
965
+ manifest.partial !== void 0 && (delete manifest.partial, await writePackageYml(manifestPath, manifest));
966
+ }
967
+ async listPackageFilePaths(packagePath) {
968
+ let paths = [];
969
+ for await (let fullPath of walkFiles(packagePath)) {
970
+ let relativePath = relative3(packagePath, fullPath);
971
+ isJunk3(basename2(relativePath)) || paths.push(relativePath);
972
+ }
973
+ return paths.sort(), paths;
974
+ }
975
+ }, packageManager = new PackageManager();
976
+
977
+ // ../core/src/core/package-management.ts
978
+ async function ensureLocalOpenPackageStructure(targetDir) {
979
+ let openpackageDir = getLocalOpenPackageDir(targetDir), packagesDir = getLocalPackagesDir(targetDir);
980
+ await Promise.all([
981
+ ensureDir(openpackageDir),
982
+ ensureDir(packagesDir)
983
+ ]);
984
+ }
985
+ async function createWorkspacePackageYml(targetDir, force = !1, output) {
986
+ let out = output ?? resolveOutput();
987
+ await ensureLocalOpenPackageStructure(targetDir);
988
+ let packageYmlPath = getLocalPackageYmlPath(targetDir), projectName = basename3(targetDir), basicPackageYml = {
989
+ name: projectName,
990
+ dependencies: [],
991
+ "dev-dependencies": []
992
+ };
993
+ return await exists(packageYmlPath) ? force ? (await writePackageYml(packageYmlPath, basicPackageYml), logger.info(`Overwrote basic openpackage.yml with name: ${projectName}`), out.success(`Overwrote basic openpackage.yml in .openpackage/ with name: ${projectName}`), basicPackageYml) : null : (await writePackageYml(packageYmlPath, basicPackageYml), logger.info("Initialized workspace openpackage.yml"), out.success("Initialized workspace openpackage.yml in .openpackage/"), basicPackageYml);
994
+ }
995
+ async function addPackageToYml(targetDir, packageName, packageVersion, isDev = !1, originalVersion, silent = !1, path, git, ref, gitPath, base, output) {
996
+ let out = output ?? resolveOutput(), packageYmlPath = getLocalPackageYmlPath(targetDir);
997
+ if (!await exists(packageYmlPath))
998
+ return;
999
+ if (await isRootPackage(targetDir, packageName)) {
1000
+ logger.debug(`Skipping manifest update: package '${packageName}' is the workspace package itself`);
1001
+ return;
1002
+ }
1003
+ let config = await parsePackageYml(packageYmlPath);
1004
+ config.dependencies || (config.dependencies = []), config[DEPENDENCY_ARRAYS.DEV_DEPENDENCIES] || (config[DEPENDENCY_ARRAYS.DEV_DEPENDENCIES] = []);
1005
+ let normalizedPackageName = normalizePackageName(packageName), nameWithVersion = packageVersion ? `${packageName}@${packageVersion}` : packageName, dependenciesArray = config.dependencies, devDependenciesArray = config[DEPENDENCY_ARRAYS.DEV_DEPENDENCIES], findIndex = (arr) => arr.findIndex((dep) => arePackageNamesEquivalent(dep.name, normalizedPackageName)), currentLocation = null, existingIndex = findIndex(dependenciesArray);
1006
+ existingIndex >= 0 ? currentLocation = DEPENDENCY_ARRAYS.DEPENDENCIES : (existingIndex = findIndex(devDependenciesArray), existingIndex >= 0 ? currentLocation = DEPENDENCY_ARRAYS.DEV_DEPENDENCIES : existingIndex = -1);
1007
+ let existingRange = currentLocation && existingIndex >= 0 ? config[currentLocation][existingIndex]?.version : void 0, shouldOmitVersion = isUnversionedVersion(packageVersion) || isUnversionedVersion(originalVersion), versionToWrite = git || shouldOmitVersion ? void 0 : originalVersion;
1008
+ if (!git && !shouldOmitVersion && packageVersion) {
1009
+ let baseVersion = extractBaseVersion(packageVersion), defaultRange = createCaretRange(baseVersion);
1010
+ if (versionToWrite = originalVersion ?? defaultRange, !originalVersion && existingRange) {
1011
+ let hasPrereleaseIntent = hasExplicitPrereleaseIntent(existingRange), isNewVersionStable = !isPrereleaseVersion(packageVersion);
1012
+ hasPrereleaseIntent ? isNewVersionStable ? (versionToWrite = createCaretRange(baseVersion), logger.debug(
1013
+ `Updating range from prerelease-including '${existingRange}' to stable '${versionToWrite}' for ${packageName} (pack transition to ${packageVersion})`
1014
+ )) : versionToWrite = existingRange : rangeIncludesVersion(existingRange, baseVersion) ? versionToWrite = existingRange : versionToWrite = defaultRange;
1015
+ }
1016
+ }
1017
+ let urlField;
1018
+ git && (urlField = ref ? `${git}#${ref}` : git);
1019
+ let dependency = {
1020
+ name: normalizedPackageName,
1021
+ ...versionToWrite ? { version: versionToWrite } : {},
1022
+ ...path && !git ? { path } : {},
1023
+ // Only use path for local sources
1024
+ ...urlField ? { url: urlField } : {},
1025
+ // Use url with embedded ref
1026
+ ...gitPath ? { path: gitPath } : {},
1027
+ // Use path field for git subdirectory
1028
+ ...base ? { base } : {}
1029
+ // Phase 4: Base field for resource model
1030
+ }, targetArray;
1031
+ currentLocation === DEPENDENCY_ARRAYS.DEV_DEPENDENCIES && !isDev ? (targetArray = DEPENDENCY_ARRAYS.DEV_DEPENDENCIES, logger.info(`Keeping package in dev-dependencies: ${nameWithVersion}`)) : currentLocation === DEPENDENCY_ARRAYS.DEPENDENCIES && isDev ? (targetArray = DEPENDENCY_ARRAYS.DEV_DEPENDENCIES, logger.info(`Moving package from dependencies to dev-dependencies: ${nameWithVersion}`)) : targetArray = isDev ? DEPENDENCY_ARRAYS.DEV_DEPENDENCIES : DEPENDENCY_ARRAYS.DEPENDENCIES, currentLocation && currentLocation !== targetArray && existingIndex >= 0 && (config[currentLocation].splice(existingIndex, 1), existingIndex = -1, currentLocation = null);
1032
+ let targetArrayRef = config[targetArray], existingTargetIndex = currentLocation === targetArray ? findIndex(targetArrayRef) : -1;
1033
+ existingTargetIndex >= 0 ? targetArrayRef[existingTargetIndex].version !== dependency.version && (targetArrayRef[existingTargetIndex] = dependency, silent || (logger.info(`Updated existing package dependency: ${nameWithVersion}`), out.success(`Updated ${nameWithVersion} in main openpackage.yml`))) : (targetArrayRef.push(dependency), silent || (logger.info(`Added new package dependency: ${nameWithVersion}`), out.success(`Added ${nameWithVersion} to main openpackage.yml`))), await writePackageYml(packageYmlPath, config);
1034
+ }
1035
+ function doesDependencyMatchPackageName(dep, userInputName) {
1036
+ let normalizedDepName = normalizePackageNameForLookup(dep.name), normalizedUserName = normalizePackageNameForLookup(userInputName);
1037
+ if (normalizedDepName === normalizedUserName)
1038
+ return !0;
1039
+ let gitUrlRaw = dep.url || dep.git;
1040
+ if (gitUrlRaw) {
1041
+ let githubInfo = extractGitHubInfo(gitUrlRaw);
1042
+ if (!githubInfo)
1043
+ return !1;
1044
+ let { username, repo } = githubInfo, actualPath = dep.path || (dep.subdirectory?.startsWith("./") ? dep.subdirectory.substring(2) : dep.subdirectory), possibleNames = [
1045
+ `${username}/${repo}`,
1046
+ `@${username}/${repo}`,
1047
+ `gh@${username}/${repo}`
1048
+ ];
1049
+ if (actualPath) {
1050
+ possibleNames.push(
1051
+ `${username}/${repo}/${actualPath}`,
1052
+ `@${username}/${repo}/${actualPath}`,
1053
+ `gh@${username}/${repo}/${actualPath}`
1054
+ );
1055
+ let pathBasename = actualPath.split("/").pop();
1056
+ pathBasename && pathBasename !== actualPath && possibleNames.push(
1057
+ `${username}/${repo}/${pathBasename}`,
1058
+ `@${username}/${repo}/${pathBasename}`,
1059
+ `gh@${username}/${repo}/${pathBasename}`
1060
+ );
1061
+ }
1062
+ let normalizedInput = normalizePackageName(userInputName);
1063
+ for (let possibleName of possibleNames)
1064
+ if (normalizePackageName(possibleName) === normalizedInput)
1065
+ return !0;
1066
+ }
1067
+ return !1;
1068
+ }
1069
+ async function removeDependencyFromManifest(manifestPath, dependencyName) {
1070
+ if (!await exists(manifestPath)) return { removed: !1 };
1071
+ try {
1072
+ let config = await parsePackageYml(manifestPath), sections = [DEPENDENCY_ARRAYS.DEPENDENCIES, DEPENDENCY_ARRAYS.DEV_DEPENDENCIES], removed = !1, removedFromSection, hadAnyDependencies = !1;
1073
+ for (let section of sections) {
1074
+ let arr = config[section];
1075
+ if (!arr) continue;
1076
+ arr.length > 0 && (hadAnyDependencies = !0);
1077
+ let next = arr.filter((dep) => !doesDependencyMatchPackageName(dep, dependencyName));
1078
+ next.length !== arr.length && (config[section] = next, removed = !0, removedFromSection = section);
1079
+ }
1080
+ return (removed || hadAnyDependencies) && await writePackageYml(manifestPath, config), { removed, section: removedFromSection };
1081
+ } catch (error) {
1082
+ return logger.warn(`Failed to update openpackage.yml when removing ${dependencyName}: ${error}`), { removed: !1 };
1083
+ }
1084
+ }
1085
+ async function removePackageFromOpenpackageYml(targetDir, packageName) {
1086
+ let packageYmlPath = getLocalPackageYmlPath(targetDir);
1087
+ return (await removeDependencyFromManifest(packageYmlPath, packageName)).removed;
1088
+ }
1089
+ async function findMatchingDependencyInManifest(manifestPath, userInput) {
1090
+ if (!await exists(manifestPath)) return null;
1091
+ try {
1092
+ let config = await parsePackageYml(manifestPath), sections = [DEPENDENCY_ARRAYS.DEPENDENCIES, DEPENDENCY_ARRAYS.DEV_DEPENDENCIES];
1093
+ for (let section of sections) {
1094
+ let arr = config[section];
1095
+ if (!arr) continue;
1096
+ let match = arr.find((dep) => doesDependencyMatchPackageName(dep, userInput));
1097
+ if (match) return match.name;
1098
+ }
1099
+ return null;
1100
+ } catch {
1101
+ return null;
1102
+ }
1103
+ }
1104
+ function rangeIncludesVersion(range, version) {
1105
+ if (!range || !version)
1106
+ return !1;
1107
+ try {
1108
+ return semver2.satisfies(version, range, { includePrerelease: !0 });
1109
+ } catch {
1110
+ return !1;
1111
+ }
1112
+ }
1113
+
1114
+ export {
1115
+ hasExplicitPrereleaseIntent,
1116
+ selectVersionWithWipPolicy,
1117
+ createContextFromFormat,
1118
+ createContextFromPackage,
1119
+ withTargetPlatform,
1120
+ updateContextAfterConversion,
1121
+ contextToJSON,
1122
+ detectPackageFormat,
1123
+ isPlatformSpecific,
1124
+ needsConversion,
1125
+ detectPackageFormatWithContext,
1126
+ detectEnhancedPackageFormat,
1127
+ loadPackageFromPath,
1128
+ packageManager,
1129
+ ensureLocalOpenPackageStructure,
1130
+ createWorkspacePackageYml,
1131
+ addPackageToYml,
1132
+ removeDependencyFromManifest,
1133
+ removePackageFromOpenpackageYml,
1134
+ findMatchingDependencyInManifest
1135
+ };
1136
+ //# sourceMappingURL=chunk-CVA64SXK.js.map