@xlinklight/publishing 3.3.0 → 3.4.0

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 (119) hide show
  1. package/README.md +23 -3
  2. package/dist/src/acceptance-delivery-binding.d.ts +20 -0
  3. package/dist/src/acceptance-delivery-binding.js +59 -0
  4. package/dist/src/acceptance.d.ts +49 -0
  5. package/dist/src/acceptance.js +79 -0
  6. package/dist/src/client.d.ts +71 -0
  7. package/dist/src/client.js +146 -0
  8. package/dist/src/index.d.ts +6 -0
  9. package/dist/src/index.js +3 -0
  10. package/dist/src/node/acceptance-delivery.d.ts +34 -0
  11. package/dist/src/node/acceptance-delivery.js +88 -0
  12. package/dist/src/node/activation.d.ts +5 -0
  13. package/dist/src/node/activation.js +3 -0
  14. package/dist/src/node/authorization.d.ts +31 -0
  15. package/dist/src/node/authorization.js +76 -0
  16. package/dist/src/node/cli.d.ts +2 -0
  17. package/dist/src/node/cli.js +22 -0
  18. package/dist/src/node/index.d.ts +20 -0
  19. package/dist/src/node/index.js +11 -0
  20. package/dist/src/node/journal-directory.d.ts +2 -0
  21. package/dist/src/node/journal-directory.js +121 -0
  22. package/dist/src/node/journal.d.ts +49 -0
  23. package/dist/src/node/journal.js +280 -0
  24. package/dist/src/node/local-json-file.d.ts +3 -0
  25. package/dist/src/node/local-json-file.js +49 -0
  26. package/dist/src/node/publishing-command.d.ts +46 -0
  27. package/dist/src/node/publishing-command.js +268 -0
  28. package/dist/src/node/session.d.ts +95 -0
  29. package/dist/src/node/session.js +223 -0
  30. package/dist/src/node/solution-package.d.ts +55 -0
  31. package/dist/src/node/solution-package.js +217 -0
  32. package/dist/src/node/source-error.d.ts +10 -0
  33. package/dist/src/node/source-error.js +15 -0
  34. package/dist/src/node/source-producer.d.ts +5 -0
  35. package/dist/src/node/source-producer.js +145 -0
  36. package/dist/src/node/terminal-network.d.ts +23 -0
  37. package/dist/src/node/terminal-network.js +122 -0
  38. package/dist/src/node/workflow.d.ts +74 -0
  39. package/dist/src/node/workflow.js +467 -0
  40. package/dist/src/package.d.ts +38 -0
  41. package/dist/src/package.js +74 -0
  42. package/dist/src/protocol.d.ts +83 -0
  43. package/dist/src/protocol.js +105 -0
  44. package/dist/src/shared/activation-types.d.ts +37 -0
  45. package/dist/src/shared/activation-types.js +1 -0
  46. package/dist/src/shared/activation.d.ts +17 -0
  47. package/dist/src/shared/activation.js +111 -0
  48. package/dist/src/shared/records.d.ts +10 -0
  49. package/dist/src/shared/records.js +26 -0
  50. package/dist/src/shared/release-version.d.ts +4 -0
  51. package/dist/src/shared/release-version.js +15 -0
  52. package/dist/src/worker/activation.d.ts +12 -0
  53. package/dist/src/worker/activation.js +11 -0
  54. package/dist/src/worker/durable-retention.d.ts +9 -0
  55. package/dist/src/worker/durable-retention.js +96 -0
  56. package/dist/src/worker/index.d.ts +12 -0
  57. package/dist/src/worker/index.js +7 -0
  58. package/dist/src/worker/journal.d.ts +129 -0
  59. package/dist/src/worker/journal.js +328 -0
  60. package/dist/src/worker/package.d.ts +60 -0
  61. package/dist/src/worker/package.js +116 -0
  62. package/dist/src/worker/release-retention.d.ts +34 -0
  63. package/dist/src/worker/release-retention.js +27 -0
  64. package/dist/src/worker/release.d.ts +22 -0
  65. package/dist/src/worker/release.js +59 -0
  66. package/dist/src/worker/runtime.d.ts +47 -0
  67. package/dist/src/worker/runtime.js +98 -0
  68. package/dist/src/worker/service.d.ts +128 -0
  69. package/dist/src/worker/service.js +520 -0
  70. package/package.json +23 -14
  71. package/src/acceptance-delivery-binding.mjs +0 -49
  72. package/src/acceptance.d.mts +0 -24
  73. package/src/acceptance.mjs +0 -67
  74. package/src/client.d.mts +0 -16
  75. package/src/client.mjs +0 -74
  76. package/src/index.d.mts +0 -6
  77. package/src/index.mjs +0 -3
  78. package/src/node/acceptance-delivery.d.mts +0 -11
  79. package/src/node/acceptance-delivery.mjs +0 -70
  80. package/src/node/activation.d.mts +0 -8
  81. package/src/node/activation.mjs +0 -3
  82. package/src/node/authorization.d.mts +0 -8
  83. package/src/node/authorization.mjs +0 -49
  84. package/src/node/cli.mjs +0 -12
  85. package/src/node/index.d.mts +0 -17
  86. package/src/node/index.mjs +0 -9
  87. package/src/node/journal.d.mts +0 -13
  88. package/src/node/journal.mjs +0 -135
  89. package/src/node/publishing-command.d.mts +0 -20
  90. package/src/node/publishing-command.mjs +0 -104
  91. package/src/node/session.d.mts +0 -25
  92. package/src/node/session.mjs +0 -134
  93. package/src/node/solution-package.d.mts +0 -15
  94. package/src/node/solution-package.mjs +0 -113
  95. package/src/node/source-error.d.mts +0 -5
  96. package/src/node/source-error.mjs +0 -9
  97. package/src/node/source-producer.mjs +0 -103
  98. package/src/node/workflow.d.mts +0 -37
  99. package/src/node/workflow.mjs +0 -320
  100. package/src/package.d.mts +0 -11
  101. package/src/package.mjs +0 -36
  102. package/src/protocol.d.mts +0 -27
  103. package/src/protocol.mjs +0 -50
  104. package/src/shared/activation.d.mts +0 -5
  105. package/src/shared/activation.mjs +0 -64
  106. package/src/worker/activation.d.mts +0 -7
  107. package/src/worker/activation.mjs +0 -4
  108. package/src/worker/index.d.mts +0 -6
  109. package/src/worker/index.mjs +0 -6
  110. package/src/worker/journal.d.mts +0 -21
  111. package/src/worker/journal.mjs +0 -151
  112. package/src/worker/package.d.mts +0 -16
  113. package/src/worker/package.mjs +0 -32
  114. package/src/worker/release.d.mts +0 -7
  115. package/src/worker/release.mjs +0 -21
  116. package/src/worker/runtime.d.mts +0 -4
  117. package/src/worker/runtime.mjs +0 -23
  118. package/src/worker/service.d.mts +0 -41
  119. package/src/worker/service.mjs +0 -251
@@ -0,0 +1,223 @@
1
+ import { errorCode, jsonSnapshot, objectRecord } from '../shared/records.js';
2
+ import { createHash } from 'node:crypto';
3
+ import { bindArtifactOperation, performArtifactOperation, observeArtifactOperation } from '@openge/forge-artifact-publish';
4
+ import { createPublishingClient } from '../client.js';
5
+ import { parsePublishingConfiguration, parsePublishingIntent, publishingIntentBytes, publishingRequestId, protocolRecord, publishingError } from '../protocol.js';
6
+ import { verifySolutionPackageBytes } from './solution-package.js';
7
+ import { maximumAcceptanceArchiveBytes } from './acceptance-delivery.js';
8
+ import { publishingDigest } from '../protocol.js';
9
+ const hash = (bytes) => createHash('sha256').update(bytes).digest('hex');
10
+ const encoded = (value) => new TextEncoder().encode(JSON.stringify(value));
11
+ const fail = (code) => publishingError(code);
12
+ function validAcceptanceTarget(target) {
13
+ if (!protocolRecord(target, ['origin', 'keyId', 'publicKeySha256']) || typeof target.origin !== 'string' || !publishingDigest(target.publicKeySha256) ||
14
+ typeof target.keyId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(target.keyId))
15
+ return false;
16
+ const origin = URL.parse(target.origin);
17
+ return origin?.protocol === 'https:' && origin.origin === target.origin;
18
+ }
19
+ const operationDefaults = { timeoutMilliseconds: 30000, closeTimeoutMilliseconds: 2000 };
20
+ function checkBinding(intent, prepared, configuration) {
21
+ const item = intent.package, descriptor = prepared.descriptor;
22
+ if (intent.projectId !== configuration.projectId || item.publisherId !== configuration.publisher.publisherId || ['solutionId', 'publisherId', 'packageName', 'version'].some(key => item[key] !== descriptor[key]) || item.fileCount !== prepared.files.length || item.totalBytes !== prepared.payloadBytes || item.content.manifestSha256 !== prepared.content.manifestSha256)
23
+ throw fail('PACKAGE_BINDING_INVALID');
24
+ }
25
+ function transportFor({ client, intent, manifestBytes, target, configurationSha256, stage }) {
26
+ const pending = new Set(), controller = new AbortController();
27
+ let status, closed = false;
28
+ const run = (signal, execute) => {
29
+ if (closed)
30
+ throw fail('TRANSPORT_CLOSED');
31
+ const promise = Promise.resolve().then(() => execute(AbortSignal.any([signal, controller.signal])));
32
+ pending.add(promise);
33
+ const settled = () => pending.delete(promise);
34
+ promise.then(settled, settled);
35
+ return promise;
36
+ };
37
+ const transport = {
38
+ target, capability: stage === 'create' ? 'artifact-upload' : 'deployment-create', configurationSha256,
39
+ async execute(_binding, context) {
40
+ try {
41
+ status = await run(context.signal, async (signal) => { if (stage !== 'create')
42
+ return client.queueRequest({ intent, signal }); if (!manifestBytes)
43
+ throw fail('FROZEN_BYTES_MISSING'); return client.createRequest({ intent, manifestBytes, signal }); });
44
+ }
45
+ catch (error) {
46
+ if (stage === 'create' && errorCode(error) === 'PUBLISHING_CONFLICT')
47
+ return { state: 'rejected', code: 'CONFLICT' };
48
+ throw error;
49
+ }
50
+ return { state: 'accepted', reference: intent.requestId };
51
+ },
52
+ async observe(binding, _reference, context) {
53
+ try {
54
+ status = await run(context.signal, signal => client.getStatus({ intent, signal }));
55
+ }
56
+ catch (error) {
57
+ if (errorCode(error) === 'PUBLISHING_REQUEST_NOT_FOUND')
58
+ return { state: 'absent', fingerprint: binding.fingerprint };
59
+ throw error;
60
+ }
61
+ const state = stage === 'create' ? 'succeeded' : status.state === 'uploading' ? 'pending' : status.state === 'unknown' ? 'unknown' : ['failed', 'abandoned', 'superseded'].includes(status.state) ? 'failed' : 'succeeded';
62
+ return { state, fingerprint: binding.fingerprint, reference: intent.requestId };
63
+ },
64
+ async close({ timeoutMilliseconds }) {
65
+ closed = true;
66
+ controller.abort();
67
+ let timer;
68
+ try {
69
+ await Promise.race([Promise.allSettled([...pending]), new Promise(resolve => { timer = setTimeout(resolve, timeoutMilliseconds); })]);
70
+ }
71
+ finally {
72
+ clearTimeout(timer);
73
+ }
74
+ return { status: pending.size ? 'unconfirmed' : 'closed', activeRequests: pending.size };
75
+ },
76
+ };
77
+ return { transport, status: () => status };
78
+ }
79
+ /** A project session holds no deployment-provider credential and never evaluates payloads. */
80
+ export function createPublishingSession({ journal, configuration, credential, allowLoopback = false, request, clientLimits, verifyActivation, packageLimits, pathCaseSensitivity, operationLimits = operationDefaults }) {
81
+ const config = parsePublishingConfiguration(configuration, { allowLoopback }), configurationSha256 = hash(encoded(config)), selectedLimits = { ...packageLimits }, selectedOperations = { ...operationLimits }, selectedClientLimits = clientLimits ? { ...clientLimits } : undefined;
82
+ if (!journal || ['load', 'compareAndSet', 'readBlob', 'operationJournal'].some(name => typeof journal[name] !== 'function') || !['case-sensitive', 'case-insensitive'].includes(pathCaseSensitivity))
83
+ throw fail('SESSION_INPUT_INVALID');
84
+ const client = createPublishingClient({ configuration: config, credential, allowLoopback, ...(request ? { request } : {}), ...(selectedClientLimits ? { limits: selectedClientLimits } : {}), ...(verifyActivation ? { verifyActivation } : {}) });
85
+ const key = (requestId) => { if (!publishingRequestId(requestId))
86
+ throw fail('REQUEST_ID_INVALID'); return 'request:' + requestId; };
87
+ const metadata = async ({ requestId, signal }) => {
88
+ const record = await journal.load(key(requestId), { signal });
89
+ if (!record)
90
+ throw fail('FROZEN_REQUEST_MISSING');
91
+ const saved = record.payload;
92
+ if (record.revision !== 1 || !protocolRecord(saved, ['schemaVersion', 'configuration', 'intent', 'manifestByteLength'], ['acceptanceArchive', 'acceptanceTarget']) || saved.schemaVersion !== 1 || typeof saved.manifestByteLength !== 'number' || !Number.isSafeInteger(saved.manifestByteLength) || saved.manifestByteLength < 1 || saved.manifestByteLength > 1048576)
93
+ throw fail('FROZEN_REQUEST_INVALID');
94
+ const archive = saved.acceptanceArchive, target = saved.acceptanceTarget;
95
+ let installed;
96
+ if (archive !== undefined) {
97
+ if (!validAcceptanceTarget(target) || !protocolRecord(archive, ['archiveSha256', 'artifactSha256', 'byteLength']) || !publishingDigest(archive.archiveSha256) || !publishingDigest(archive.artifactSha256) || typeof archive.byteLength !== 'number' || !Number.isSafeInteger(archive.byteLength) || archive.byteLength < 1 || archive.byteLength > maximumAcceptanceArchiveBytes)
98
+ throw fail('FROZEN_REQUEST_INVALID');
99
+ installed = { archive: { archiveSha256: archive.archiveSha256, artifactSha256: archive.artifactSha256, byteLength: archive.byteLength }, target };
100
+ }
101
+ else if (target !== undefined)
102
+ throw fail('FROZEN_REQUEST_INVALID');
103
+ if (hash(encoded(parsePublishingConfiguration(saved.configuration, { allowLoopback }))) !== configurationSha256)
104
+ throw fail('CONFIGURATION_CHANGED');
105
+ const intent = parsePublishingIntent(saved.intent);
106
+ if (intent.requestId !== requestId || intent.projectId !== config.projectId || intent.package.publisherId !== config.publisher.publisherId)
107
+ throw fail('FROZEN_REQUEST_INVALID');
108
+ return { intent, manifestByteLength: saved.manifestByteLength, installed };
109
+ };
110
+ const read = async ({ requestId, signal }) => {
111
+ const { intent, manifestByteLength } = await metadata({ requestId, signal });
112
+ const manifestBytes = await journal.readBlob({ sha256: intent.package.content.manifestSha256, byteLength: manifestByteLength }, { signal });
113
+ if (!manifestBytes)
114
+ throw fail('FROZEN_BYTES_MISSING');
115
+ let manifest;
116
+ try {
117
+ manifest = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(manifestBytes));
118
+ }
119
+ catch {
120
+ throw fail('FROZEN_REQUEST_INVALID');
121
+ }
122
+ if (!objectRecord(manifest) || !Array.isArray(manifest.files) || manifest.files.length !== intent.package.fileCount)
123
+ throw fail('FROZEN_REQUEST_INVALID');
124
+ const files = [];
125
+ for (const file of manifest.files) {
126
+ if (!objectRecord(file) || typeof file.path !== 'string' || !publishingDigest(file.sha256) || typeof file.byteLength !== 'number')
127
+ throw fail('FROZEN_REQUEST_INVALID');
128
+ const bytes = await journal.readBlob({ sha256: file.sha256, byteLength: file.byteLength }, { signal });
129
+ if (!bytes)
130
+ throw fail('FROZEN_BYTES_MISSING');
131
+ files.push({ path: file.path, bytes });
132
+ }
133
+ const prepared = await verifySolutionPackageBytes({ files, manifestBytes, expectedContent: intent.package.content, pathCaseSensitivity, limits: selectedLimits, signal });
134
+ checkBinding(intent, prepared, config);
135
+ return { intent, prepared };
136
+ };
137
+ const operation = async (mode, { requestId, signal, stage = 'create', attempt = 0 }) => {
138
+ if (!['create', 'commit'].includes(stage) || !Number.isSafeInteger(attempt) || attempt < 0 || attempt > 64 || stage === 'commit' && attempt !== 0)
139
+ throw fail('SESSION_INPUT_INVALID');
140
+ const { intent, manifestByteLength } = await metadata({ requestId, signal }), frozen = mode === 'create' ? await read({ requestId, signal }) : undefined, intentBytes = publishingIntentBytes(intent);
141
+ const target = { provider: 'link-light-publishing', namespace: config.projectId, endpoint: config.serviceUrl };
142
+ const operationId = requestId + '.' + stage + (attempt ? '.' + attempt : '');
143
+ const binding = await bindArtifactOperation({ requestId: operationId, content: intent.package.content, ...(intent.provenance ? { provenance: intent.provenance } : {}), target, capability: stage === 'create' ? 'artifact-upload' : 'deployment-create', configurationSha256, inputs: [{ name: 'intent.json', sha256: hash(intentBytes), byteLength: intentBytes.byteLength }, { name: 'content-manifest.json', sha256: intent.package.content.manifestSha256, byteLength: manifestByteLength }] });
144
+ const current = transportFor({ client, intent, manifestBytes: frozen?.prepared.manifestBytes, target, configurationSha256, stage });
145
+ const receipt = await (mode === 'create' ? performArtifactOperation : observeArtifactOperation)(current.transport, binding, journal.operationJournal(), { ...selectedOperations, signal });
146
+ return { receipt, ...(current.status() ? { status: current.status() } : {}) };
147
+ };
148
+ return Object.freeze({
149
+ async freeze({ intent: input, prepared: inputPackage, acceptanceArchive, acceptanceTarget, signal }) {
150
+ const intent = parsePublishingIntent(input);
151
+ key(intent.requestId);
152
+ if (await journal.load(key(intent.requestId), { signal }))
153
+ throw fail('REQUEST_EXISTS');
154
+ const prepared = await verifySolutionPackageBytes({ files: inputPackage.files, manifestBytes: inputPackage.manifestBytes, expectedContent: intent.package.content, pathCaseSensitivity, limits: selectedLimits, signal });
155
+ checkBinding(intent, prepared, config);
156
+ const files = new Map(prepared.manifest.files.map(file => [file.path, file]));
157
+ const blobs = [{ sha256: prepared.content.manifestSha256, bytes: prepared.manifestBytes }, ...prepared.files.map(file => { const entry = files.get(file.path); if (!entry)
158
+ throw fail('PACKAGE_BINDING_INVALID'); return { sha256: entry.sha256, bytes: file.bytes }; })];
159
+ let archive;
160
+ if (acceptanceArchive !== undefined) {
161
+ const { bytes, artifactSha256 } = acceptanceArchive;
162
+ if (!(bytes instanceof Uint8Array) || bytes.byteLength < 1 || bytes.byteLength > maximumAcceptanceArchiveBytes || !publishingDigest(artifactSha256) || !validAcceptanceTarget(acceptanceTarget))
163
+ throw fail('ACCEPTANCE_ARCHIVE_INVALID');
164
+ archive = { archiveSha256: hash(bytes), artifactSha256, byteLength: bytes.byteLength };
165
+ blobs.push({ sha256: archive.archiveSha256, bytes });
166
+ }
167
+ const result = await journal.compareAndSet({ key: key(intent.requestId), expectedRevision: 0, payload: jsonSnapshot({ schemaVersion: 1, configuration: config, intent, manifestByteLength: prepared.manifestBytes.byteLength, ...(archive ? { acceptanceArchive: archive, acceptanceTarget } : {}) }), blobs }, { signal });
168
+ if (result !== 'stored')
169
+ throw fail('REQUEST_EXISTS');
170
+ return { requestId: intent.requestId, content: prepared.content };
171
+ },
172
+ read,
173
+ async acceptanceMetadata({ requestId, signal }) {
174
+ const { installed, intent } = await metadata({ requestId, signal });
175
+ return installed ? { intent, ...installed } : undefined;
176
+ },
177
+ async readAcceptanceArchive({ requestId, signal }) {
178
+ const { installed, intent } = await metadata({ requestId, signal });
179
+ if (!installed)
180
+ return undefined;
181
+ const { archive, target } = installed;
182
+ const bytes = await journal.readBlob({ sha256: archive.archiveSha256, byteLength: archive.byteLength }, { signal });
183
+ if (!bytes || hash(bytes) !== archive.archiveSha256)
184
+ throw fail('FROZEN_BYTES_MISSING');
185
+ return { archive, bytes, intent, target };
186
+ },
187
+ create: input => operation('create', { ...input, stage: 'create' }),
188
+ observe: input => operation('observe', input),
189
+ queue: input => operation('create', { ...input, stage: 'commit' }),
190
+ async status({ requestId, signal }) { const { intent } = await metadata({ requestId, signal }); return client.getStatus({ intent, signal }); },
191
+ async resume({ requestId, signal }) { const { intent } = await metadata({ requestId, signal }); return client.resumeRequest({ intent, signal }); },
192
+ async recover({ requestId, signal }) { const { intent } = await metadata({ requestId, signal }); return client.recoverRequest({ intent, signal }); },
193
+ async upload({ requestId, signal }) {
194
+ const { intent, prepared } = await read({ requestId, signal }), manifest = new Map(prepared.manifest.files.map(file => [file.path, file])), bodies = new Map(prepared.files.map(file => [file.path, file.bytes]));
195
+ const checked = async () => {
196
+ const status = await client.getStatus({ intent, signal }), seen = new Map();
197
+ for (const file of status.missingFiles) {
198
+ const original = manifest.get(file.path);
199
+ if (!original || original.sha256 !== file.sha256 || original.byteLength !== file.byteLength || file.receivedBytes >= file.byteLength || seen.has(file.sha256) && seen.get(file.sha256) !== file.receivedBytes)
200
+ throw fail('STATUS_BINDING_INVALID');
201
+ seen.set(file.sha256, file.receivedBytes);
202
+ }
203
+ return status;
204
+ };
205
+ const status = await checked();
206
+ if (status.state !== 'uploading')
207
+ return status;
208
+ const done = new Set(), chunkBytes = selectedClientLimits?.maximumChunkBytes ?? 262144;
209
+ for (const file of status.missingFiles) {
210
+ if (done.has(file.sha256))
211
+ continue;
212
+ done.add(file.sha256);
213
+ const bytes = bodies.get(file.path);
214
+ if (!bytes)
215
+ throw fail('FROZEN_BYTES_MISSING');
216
+ for (let offset = file.receivedBytes; offset < file.byteLength; offset += chunkBytes)
217
+ await client.uploadChunk({ requestId, file, offset, bytes: bytes.subarray(offset, Math.min(offset + chunkBytes, file.byteLength)), signal });
218
+ }
219
+ return checked();
220
+ },
221
+ async abandon({ requestId, signal }) { const { intent } = await metadata({ requestId, signal }); return client.abandonRequest({ intent, signal }); },
222
+ });
223
+ }
@@ -0,0 +1,55 @@
1
+ import type { ArtifactContentIdentity, ArtifactContentManifest, ArtifactContentManifestFile } from '@openge/forge-artifact-publish';
2
+ import type { SolutionPackageDescriptor, SolutionPackageLimits } from '../package.js';
3
+ export type { SolutionPackageLimits } from '../package.js';
4
+ export type SolutionPackageFilePlan = Omit<Extract<ArtifactContentManifestFile, {
5
+ role: 'asset';
6
+ }>, 'byteLength' | 'sha256'> | Omit<Extract<ArtifactContentManifestFile, {
7
+ role: 'control';
8
+ }>, 'byteLength' | 'sha256'>;
9
+ export interface PreparedSolutionPackage {
10
+ descriptor: SolutionPackageDescriptor;
11
+ content: ArtifactContentIdentity;
12
+ manifest: ArtifactContentManifest;
13
+ manifestBytes: Uint8Array;
14
+ files: {
15
+ path: string;
16
+ bytes: Uint8Array;
17
+ }[];
18
+ payloadBytes: number;
19
+ readFile(path: string, input: {
20
+ maximumBytes: number;
21
+ signal?: AbortSignal;
22
+ }): Promise<Uint8Array>;
23
+ streamFile(path: string, input?: {
24
+ signal?: AbortSignal;
25
+ }): AsyncIterable<Uint8Array>;
26
+ }
27
+ interface PackageInput {
28
+ root: string;
29
+ pathCaseSensitivity: 'case-sensitive' | 'case-insensitive';
30
+ limits: SolutionPackageLimits;
31
+ signal?: AbortSignal;
32
+ }
33
+ /** Capture exact artifact bytes, independently of source control or a deployment. */
34
+ export declare function prepareSolutionPackage({ root, files, pathCaseSensitivity, limits, signal }: PackageInput & {
35
+ files: readonly SolutionPackageFilePlan[];
36
+ }): Promise<PreparedSolutionPackage>;
37
+ /** Compose already-captured components without staging a second directory tree. */
38
+ export declare function prepareSolutionPackageBytes({ files, pathCaseSensitivity, limits, signal }: Omit<PackageInput, 'root'> & {
39
+ files: readonly (SolutionPackageFilePlan & {
40
+ bytes: Uint8Array;
41
+ })[];
42
+ }): Promise<PreparedSolutionPackage>;
43
+ export declare function verifySolutionPackage({ root, manifestBytes, expectedContent, pathCaseSensitivity, limits, signal }: PackageInput & {
44
+ manifestBytes: Uint8Array;
45
+ expectedContent: ArtifactContentIdentity;
46
+ }): Promise<PreparedSolutionPackage>;
47
+ /** Validate opaque received bytes without importing or executing the payload. */
48
+ export declare function verifySolutionPackageBytes({ files, manifestBytes, expectedContent, pathCaseSensitivity, limits, signal }: Omit<PackageInput, 'root'> & {
49
+ files: readonly {
50
+ path: string;
51
+ bytes: Uint8Array;
52
+ }[];
53
+ manifestBytes: Uint8Array;
54
+ expectedContent: ArtifactContentIdentity;
55
+ }): Promise<PreparedSolutionPackage>;
@@ -0,0 +1,217 @@
1
+ import path from 'node:path';
2
+ import { createHash } from 'node:crypto';
3
+ import { calculateBytesIntegrity } from '@openge/forge-artifact-integrity';
4
+ import { createArtifactContentManifest } from '@openge/forge-artifact-publish';
5
+ import { captureArtifactFiles, verifyArtifactFiles } from '@openge/forge-artifact-publish/node';
6
+ import { parseSolutionPackageDescriptor, parseSolutionPackageLimits } from '../package.js';
7
+ const failure = (code) => Error('PUBLISHING_PACKAGE_' + code);
8
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
9
+ const check = (signal) => signal.throwIfAborted();
10
+ function runtimeClosure(descriptor, files, pathCaseSensitivity) {
11
+ const names = new Set(files), links = new Map(), fold = (value) => pathCaseSensitivity === 'case-insensitive' ? value.toLowerCase() : value;
12
+ const overlaps = (first, second) => first === second || first.startsWith(second + '/') || second.startsWith(first + '/');
13
+ for (const link of descriptor.runtime.links) {
14
+ const name = fold(link.path);
15
+ if (files.some(file => overlaps(fold(file), name)) || [...links.keys()].some(file => overlaps(fold(file), name)))
16
+ throw failure('RUNTIME_LINK_INVALID');
17
+ links.set(link.path, link.target);
18
+ }
19
+ const resolve = (input, visited = new Set()) => {
20
+ if (visited.size > 64 || visited.has(input))
21
+ throw failure('RUNTIME_LINK_INVALID');
22
+ visited.add(input);
23
+ const match = [...links.keys()].filter(name => input === name || input.startsWith(name + '/')).sort((a, b) => b.length - a.length)[0];
24
+ if (match) {
25
+ const linkTarget = links.get(match);
26
+ if (linkTarget === undefined)
27
+ throw failure('RUNTIME_LINK_INVALID');
28
+ const target = path.posix.normalize(path.posix.join(path.posix.dirname(match), linkTarget, input.slice(match.length)));
29
+ if (!target.startsWith('server/'))
30
+ throw failure('RUNTIME_LINK_INVALID');
31
+ return resolve(target, visited);
32
+ }
33
+ if (!names.has(input) && !files.some(name => name.startsWith(input + '/')))
34
+ throw failure('RUNTIME_LINK_INVALID');
35
+ return input;
36
+ };
37
+ for (const name of links.keys())
38
+ resolve(name);
39
+ if (!names.has(descriptor.runtime.entry) || !names.has(descriptor.ui.entry))
40
+ throw failure('ENTRY_MISSING');
41
+ }
42
+ function packageNames(files, pathCaseSensitivity) {
43
+ if (!['case-sensitive', 'case-insensitive'].includes(pathCaseSensitivity))
44
+ throw failure('INPUT_INVALID');
45
+ const names = files.map(file => file.path), folded = names.map(name => pathCaseSensitivity === 'case-insensitive' ? name.toLowerCase() : name);
46
+ const paths = new Set(folded), collision = folded.some(name => { for (let slash = name.lastIndexOf('/'); slash >= 0; slash = name.lastIndexOf('/', slash - 1))
47
+ if (paths.has(name.slice(0, slash)))
48
+ return true; return false; });
49
+ if (paths.size !== folded.length || collision || names.some(name => name.split('/').some(part => part.startsWith('.env') || ['.git', '.npmrc', '.ssh', 'release-private'].includes(part))) || files.find(file => file.path === 'solution.json')?.role !== 'control')
50
+ throw failure('PLAN_INVALID');
51
+ return names;
52
+ }
53
+ function completed(prepared, captured, pathCaseSensitivity, total) {
54
+ let descriptor;
55
+ try {
56
+ const control = captured.find(file => file.path === 'solution.json');
57
+ if (!control)
58
+ throw failure('DESCRIPTOR_INVALID');
59
+ descriptor = parseSolutionPackageDescriptor(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(control.bytes)));
60
+ }
61
+ catch {
62
+ throw failure('DESCRIPTOR_INVALID');
63
+ }
64
+ runtimeClosure(descriptor, packageNames(prepared.manifest.files, pathCaseSensitivity), pathCaseSensitivity);
65
+ const files = captured.sort((a, b) => compare(a.path, b.path));
66
+ const streamFile = async function* (path, { signal } = {}) { const file = files.find(file => file.path === path), declared = prepared.manifest.files.find(file => file.path === path); if (!file || !declared)
67
+ throw failure('CLOSURE'); const digest = createHash('sha256'); let count = 0; for (let offset = 0; offset < file.bytes.length; offset += 1048576) {
68
+ signal?.throwIfAborted();
69
+ const bytes = new Uint8Array(file.bytes.subarray(offset, Math.min(offset + 1048576, file.bytes.length)));
70
+ digest.update(bytes);
71
+ count += bytes.length;
72
+ yield bytes;
73
+ } if (count !== declared.byteLength || digest.digest('hex') !== declared.sha256)
74
+ throw failure('CHANGED'); };
75
+ const readFile = async (path, input) => { const declared = prepared.manifest.files.find(file => file.path === path), maximumBytes = input?.maximumBytes, signal = input?.signal; if (!Number.isSafeInteger(maximumBytes) || maximumBytes < 0 || maximumBytes > 16777216 || !declared || declared.byteLength > maximumBytes)
76
+ throw failure('BYTE_LIMIT'); const bytes = new Uint8Array(declared.byteLength); let offset = 0; for await (const part of streamFile(path, { signal })) {
77
+ bytes.set(part, offset);
78
+ offset += part.length;
79
+ } return bytes; };
80
+ return { descriptor, content: prepared.content, manifest: prepared.manifest, manifestBytes: prepared.bytes, files, payloadBytes: total, streamFile, readFile };
81
+ }
82
+ async function capturedPackage(declared, captured, pathCaseSensitivity, selected, current, total) {
83
+ const byPath = new Map(captured.map(file => [file.path, file])), manifestFiles = [];
84
+ if (byPath.size !== captured.length || declared.length !== captured.length)
85
+ throw failure('CLOSURE');
86
+ for (const file of declared) {
87
+ const capturedFile = byPath.get(file.path);
88
+ if (!capturedFile)
89
+ throw failure('CLOSURE');
90
+ const bytes = capturedFile.bytes, integrity = await calculateBytesIntegrity(bytes);
91
+ check(current);
92
+ manifestFiles.push({ ...file, byteLength: bytes.byteLength, sha256: integrity.sha256 });
93
+ }
94
+ const prepared = await createArtifactContentManifest({ schemaVersion: 1, files: manifestFiles });
95
+ check(current);
96
+ if (prepared.bytes.byteLength > selected.maximumManifestBytes || total + prepared.bytes.byteLength > selected.maximumTotalBytes)
97
+ throw failure('BYTE_LIMIT');
98
+ return completed(prepared, captured, pathCaseSensitivity, total);
99
+ }
100
+ async function canonicalManifest(manifestBytes, expectedContent, limits) {
101
+ if (!(manifestBytes instanceof Uint8Array) || manifestBytes.byteLength > limits.maximumManifestBytes || !expectedContent || Object.keys(expectedContent).join(',') !== 'manifestSha256' || !/^[a-f0-9]{64}$/.test(expectedContent.manifestSha256 ?? ''))
102
+ throw failure('MANIFEST_INVALID');
103
+ const snapshot = new Uint8Array(manifestBytes);
104
+ let manifest;
105
+ try {
106
+ manifest = await createArtifactContentManifest(JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(snapshot)));
107
+ }
108
+ catch {
109
+ throw failure('MANIFEST_INVALID');
110
+ }
111
+ if (manifest.content.manifestSha256 !== expectedContent.manifestSha256 || manifest.bytes.byteLength !== snapshot.byteLength || manifest.bytes.some((byte, index) => byte !== snapshot[index]))
112
+ throw failure('MANIFEST_CHANGED');
113
+ return manifest;
114
+ }
115
+ /** Capture exact artifact bytes, independently of source control or a deployment. */
116
+ export async function prepareSolutionPackage({ root, files, pathCaseSensitivity, limits, signal }) {
117
+ signal?.throwIfAborted();
118
+ const selected = parseSolutionPackageLimits(limits);
119
+ if (typeof root !== 'string' || !path.isAbsolute(root) || !['case-sensitive', 'case-insensitive'].includes(pathCaseSensitivity) || !Array.isArray(files) || !files.length || files.length > selected.maximumFiles)
120
+ throw failure('INPUT_INVALID');
121
+ let declared;
122
+ try {
123
+ declared = (await createArtifactContentManifest({ schemaVersion: 1, files: files.map(file => ({ ...file, byteLength: 0, sha256: '0'.repeat(64) })) })).manifest.files;
124
+ }
125
+ catch {
126
+ throw failure('PLAN_INVALID');
127
+ }
128
+ if (files.some(file => Object.keys(file).sort().join(',') !== (file.role === 'asset' ? 'path,responseHeaders,role' : 'path,role')))
129
+ throw failure('PLAN_INVALID');
130
+ packageNames(declared, pathCaseSensitivity);
131
+ return captureSolution({ root, files, pathCaseSensitivity, selected, signal });
132
+ }
133
+ async function captureSolution({ root, files, pathCaseSensitivity, selected, signal, manifestBytes, expectedContent }) {
134
+ const options = { sources: [{ rootDirectory: root, closure: 'exact', files: files.map(file => ({ ...file, sourcePath: file.path })) }], pathCaseSensitivity, maxFiles: selected.maximumFiles, maxEntries: selected.maximumFiles * 8, maxFileBytes: selected.maximumFileBytes, maxTotalBytes: selected.maximumTotalBytes, maxManifestBytes: selected.maximumManifestBytes, timeoutMilliseconds: selected.timeoutMs, ...(signal ? { signal } : {}) };
135
+ let captured;
136
+ try {
137
+ captured = await (manifestBytes ? verifyArtifactFiles({ ...options, manifestBytes, expectedContent }) : captureArtifactFiles(options));
138
+ }
139
+ catch (error) {
140
+ signal?.throwIfAborted();
141
+ const reasons = { INVALID_PLAN: 'PLAN_INVALID', INVALID_SOURCE: 'CLOSURE', INTEGRITY_MISMATCH: 'CHANGED', BUDGET_EXCEEDED: 'BYTE_LIMIT', CLOSURE_UNCONFIRMED: 'CLOSE_FAILED' };
142
+ throw failure(error instanceof Error && 'code' in error && typeof error.code === 'string' ? (reasons[error.code] ?? 'CAPTURE_FAILED') : 'CAPTURE_FAILED');
143
+ }
144
+ return completed({ manifest: captured.manifest, content: captured.content, bytes: captured.manifestBytes }, captured.manifest.files.map(file => ({ path: file.path, bytes: captured.readFile(file.path) })), pathCaseSensitivity, captured.payloadByteLength);
145
+ }
146
+ /** Compose already-captured components without staging a second directory tree. */
147
+ export async function prepareSolutionPackageBytes({ files, pathCaseSensitivity, limits, signal }) {
148
+ signal?.throwIfAborted();
149
+ const selected = parseSolutionPackageLimits(limits), deadline = AbortSignal.timeout(selected.timeoutMs), current = signal ? AbortSignal.any([signal, deadline]) : deadline;
150
+ if (!Array.isArray(files) || !files.length || files.length > selected.maximumFiles)
151
+ throw failure('INPUT_INVALID');
152
+ const captured = [], plan = [];
153
+ let total = 0;
154
+ for (const file of files) {
155
+ if (!file || !(file.bytes instanceof Uint8Array) || Object.keys(file).sort().join(',') !== (file.role === 'asset' ? 'bytes,path,responseHeaders,role' : 'bytes,path,role'))
156
+ throw failure('PLAN_INVALID');
157
+ if (file.bytes.byteLength > selected.maximumFileBytes)
158
+ throw failure('BYTE_LIMIT');
159
+ total += file.bytes.byteLength;
160
+ if (total > selected.maximumTotalBytes)
161
+ throw failure('BYTE_LIMIT');
162
+ captured.push({ path: file.path, bytes: new Uint8Array(file.bytes) });
163
+ const { bytes, ...declaration } = file;
164
+ void bytes;
165
+ plan.push({ ...declaration, byteLength: 0, sha256: '0'.repeat(64) });
166
+ }
167
+ let declared;
168
+ try {
169
+ declared = (await createArtifactContentManifest({ schemaVersion: 1, files: plan })).manifest.files;
170
+ }
171
+ catch {
172
+ throw failure('PLAN_INVALID');
173
+ }
174
+ packageNames(declared, pathCaseSensitivity);
175
+ return capturedPackage(declared, captured, pathCaseSensitivity, selected, current, total);
176
+ }
177
+ export async function verifySolutionPackage({ root, manifestBytes, expectedContent, pathCaseSensitivity, limits, signal }) {
178
+ const selected = parseSolutionPackageLimits(limits), manifest = await canonicalManifest(manifestBytes, expectedContent, selected);
179
+ packageNames(manifest.manifest.files, pathCaseSensitivity);
180
+ return captureSolution({ root, files: manifest.manifest.files.map(file => file.role === 'asset' ? { path: file.path, role: file.role, responseHeaders: file.responseHeaders } : { path: file.path, role: file.role }), pathCaseSensitivity, selected, signal, manifestBytes: manifest.bytes, expectedContent });
181
+ }
182
+ /** Validate opaque received bytes without importing or executing the payload. */
183
+ export async function verifySolutionPackageBytes({ files, manifestBytes, expectedContent, pathCaseSensitivity, limits, signal }) {
184
+ signal?.throwIfAborted();
185
+ const selected = parseSolutionPackageLimits(limits), deadline = AbortSignal.timeout(selected.timeoutMs), current = signal ? AbortSignal.any([signal, deadline]) : deadline;
186
+ if (!Array.isArray(files) || files.length < 1 || files.length > selected.maximumFiles)
187
+ throw failure('CLOSURE');
188
+ const captured = [], seen = new Set();
189
+ let total = 0;
190
+ for (const file of files) {
191
+ if (!file || Object.keys(file).sort().join(',') !== 'bytes,path' || typeof file.path !== 'string' || !(file.bytes instanceof Uint8Array) || seen.has(file.path))
192
+ throw failure('CLOSURE');
193
+ if (file.bytes.byteLength > selected.maximumFileBytes)
194
+ throw failure('BYTE_LIMIT');
195
+ total += file.bytes.byteLength;
196
+ if (total > selected.maximumTotalBytes)
197
+ throw failure('BYTE_LIMIT');
198
+ seen.add(file.path);
199
+ captured.push({ path: file.path, bytes: new Uint8Array(file.bytes) });
200
+ }
201
+ const prepared = await canonicalManifest(manifestBytes, expectedContent, selected);
202
+ check(current);
203
+ if (total + prepared.bytes.byteLength > selected.maximumTotalBytes)
204
+ throw failure('BYTE_LIMIT');
205
+ if (prepared.manifest.files.length !== captured.length)
206
+ throw failure('CLOSURE');
207
+ const byPath = new Map(captured.map(file => [file.path, file]));
208
+ for (const declared of prepared.manifest.files) {
209
+ const file = byPath.get(declared.path);
210
+ if (!file)
211
+ throw failure('CLOSURE');
212
+ if (file.bytes.byteLength !== declared.byteLength || (await calculateBytesIntegrity(file.bytes)).sha256 !== declared.sha256)
213
+ throw failure('CHANGED');
214
+ check(current);
215
+ }
216
+ return completed(prepared, captured, pathCaseSensitivity, total);
217
+ }
@@ -0,0 +1,10 @@
1
+ /** Only a source owner that observed its process lifecycle may assert closure.
2
+ * The original cause stays private; CLI diagnostics emit only the stable code. */
3
+ export declare class PublishingSourceError extends Error {
4
+ readonly code: 'PUBLISHING_SOURCE_PREPARATION_FAILED' | 'PUBLISHING_SOURCE_PREPARATION_UNKNOWN';
5
+ readonly processesClosed: boolean;
6
+ constructor({ cause, processesClosed }: {
7
+ cause: unknown;
8
+ processesClosed: boolean;
9
+ });
10
+ }
@@ -0,0 +1,15 @@
1
+ /** Only a source owner that observed its process lifecycle may assert closure.
2
+ * The original cause stays private; CLI diagnostics emit only the stable code. */
3
+ export class PublishingSourceError extends Error {
4
+ code;
5
+ processesClosed;
6
+ constructor({ cause, processesClosed }) {
7
+ if (typeof processesClosed !== 'boolean')
8
+ throw TypeError('PUBLISHING_SOURCE_CLOSURE_REQUIRED');
9
+ const code = processesClosed ? 'PUBLISHING_SOURCE_PREPARATION_FAILED' : 'PUBLISHING_SOURCE_PREPARATION_UNKNOWN';
10
+ super(code, { cause });
11
+ this.name = 'PublishingSourceError';
12
+ this.code = code;
13
+ this.processesClosed = processesClosed;
14
+ }
15
+ }
@@ -0,0 +1,5 @@
1
+ export declare const defaultProducer = "deployment/publishing.mjs";
2
+ export declare function validateLocalProducer(relative: string): string;
3
+ export declare function checkoutReleaseVersion(root: string, packageName: string): Promise<string | undefined>;
4
+ export declare function checkoutRequiresAcceptanceDelivery(root: string): Promise<boolean>;
5
+ export declare function selectProducerFile(root: string, explicit?: string): Promise<string>;