@cardinali-studio/adminkit 2.2.49 → 2.2.50

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 (63) hide show
  1. package/dist/app/App.js +6 -6
  2. package/dist/app/app.css +67 -1
  3. package/dist/app/delivery.js +7 -7
  4. package/dist/app/guide/TransferGuide.js +1 -1
  5. package/dist/app/lib/deliveries.d.ts +6 -0
  6. package/dist/app/lib/delivery-capabilities.d.ts +31 -0
  7. package/dist/app/lib/delivery-capabilities.js +115 -0
  8. package/dist/app/lib/delivery-checkpoint-pipeline.d.ts +81 -0
  9. package/dist/app/lib/delivery-checkpoint-pipeline.js +195 -0
  10. package/dist/app/lib/delivery-finalize.d.ts +21 -0
  11. package/dist/app/lib/delivery-finalize.js +42 -0
  12. package/dist/app/lib/delivery-multipart-large.d.ts +18 -0
  13. package/dist/app/lib/delivery-multipart-large.js +28 -0
  14. package/dist/app/lib/delivery-network.d.ts +7 -1
  15. package/dist/app/lib/delivery-network.js +85 -18
  16. package/dist/app/lib/delivery-part-pipeline.d.ts +79 -0
  17. package/dist/app/lib/delivery-part-pipeline.js +270 -0
  18. package/dist/app/lib/delivery-upload-coordinator.d.ts +112 -0
  19. package/dist/app/lib/delivery-upload-coordinator.js +229 -0
  20. package/dist/app/lib/delivery-upload.d.ts +19 -3
  21. package/dist/app/lib/delivery-upload.js +226 -29
  22. package/dist/app/lib/upload-queue.d.ts +5 -0
  23. package/dist/app/lib/upload-queue.js +54 -29
  24. package/dist/app/routes/Deliveries.d.ts +9 -3
  25. package/dist/app/routes/Deliveries.js +299 -164
  26. package/dist/app/routes/DeliveryDashboard.js +1 -1
  27. package/dist/app/routes/DeliveryEmail.d.ts +8 -1
  28. package/dist/app/routes/DeliveryEmail.js +63 -23
  29. package/dist/app/routes/Overview.js +5 -5
  30. package/dist/app/routes/UploadDock.js +4 -3
  31. package/dist/form/media/MediaGrid.js +1 -1
  32. package/dist/functions/_shared/b2.js +98 -19
  33. package/dist/functions/_shared/delivery-activation.js +98 -0
  34. package/dist/functions/_shared/delivery-download-bundle.js +280 -0
  35. package/dist/functions/_shared/delivery-email.js +92 -13
  36. package/dist/functions/_shared/delivery-file-names.js +19 -0
  37. package/dist/functions/_shared/delivery-finalization-paid.js +31 -0
  38. package/dist/functions/_shared/delivery-finalization-storage.js +64 -0
  39. package/dist/functions/_shared/delivery-manifest-free.js +74 -0
  40. package/dist/functions/_shared/delivery-manifest.js +277 -20
  41. package/dist/functions/_shared/delivery-multipart-verification.js +68 -0
  42. package/dist/functions/_shared/delivery-request.js +74 -0
  43. package/dist/functions/_shared/delivery-storage-access.js +14 -0
  44. package/dist/functions/_shared/delivery-upload-admission.js +221 -0
  45. package/dist/functions/_shared/delivery-upload-contract.js +44 -0
  46. package/dist/functions/_shared/delivery-upload-free.js +80 -0
  47. package/dist/functions/_shared/delivery-upload-policy.js +64 -0
  48. package/dist/functions/_shared/delivery-upload-session.js +365 -0
  49. package/dist/functions/_shared/delivery-work-budget.js +49 -0
  50. package/dist/functions/api/deliveries.js +58 -17
  51. package/dist/functions/api/delivery/multipart.js +152 -15
  52. package/dist/functions/delivery-public/assets/client.js +59 -54
  53. package/dist/functions/delivery-public/assets/delivery.css +6 -2
  54. package/dist/functions/delivery-public/index.js +43 -15
  55. package/dist/functions/delivery-public/migrations/0015_delivery_activation_intents.sql +12 -0
  56. package/dist/functions/delivery-public/migrations/0016_delivery_multipart_verification.sql +16 -0
  57. package/dist/functions/delivery-public/migrations/0017_delivery_upload_admission.sql +38 -0
  58. package/dist/functions/delivery-public/migrations/0018_delivery_upload_sessions.sql +26 -0
  59. package/dist/functions/delivery-public/migrations/0019_delivery_manifest_fragments.sql +27 -0
  60. package/dist/functions/delivery-public/migrations/0020_delivery_email_reply_to.sql +1 -0
  61. package/dist/functions/index.js +3 -1
  62. package/dist/theme.css +2 -1
  63. package/package.json +1 -1
@@ -0,0 +1,270 @@
1
+ import { deliveryGate, checkCancelled, UploadCancelled } from './delivery-network.js';
2
+ export const PART_BATCH_ROLLOUT_ENABLED = false;
3
+ const PART = 16 * 1024 * 1024;
4
+ const hex = (value) => [...new Uint8Array(value)].map(n => n.toString(16).padStart(2, '0')).join('');
5
+ const digest = async (value) => hex(await crypto.subtle.digest('SHA-256', value));
6
+ /** Bounded PUT and receipt queues. Production construction stays disabled until
7
+ * capability negotiation and full-consumer budgets have been certified. */
8
+ export class DeliveryPartPipeline {
9
+ uploadId;
10
+ transport;
11
+ onPut;
12
+ onRegistered;
13
+ batchSize;
14
+ flushAfterMs;
15
+ controller = new AbortController();
16
+ control;
17
+ receiptControl;
18
+ active = new Set();
19
+ known;
20
+ signatures = new Map();
21
+ signing = null;
22
+ pending = [];
23
+ recording = null;
24
+ timer = null;
25
+ failure = null;
26
+ waiters = [];
27
+ unconfirmed = 0;
28
+ retainedBytes = 0;
29
+ highestPart = 0;
30
+ transferredBytes = 0;
31
+ registeredBytes = 0;
32
+ contiguousPart = 0;
33
+ verified = new Set();
34
+ abort = () => this.fail(new UploadCancelled());
35
+ constructor(uploadId, transport, control, prior = new Map(), onPut = () => { }, onRegistered = () => { }, batchSize = 4, flushAfterMs = 25) {
36
+ this.uploadId = uploadId;
37
+ this.transport = transport;
38
+ this.onPut = onPut;
39
+ this.onRegistered = onRegistered;
40
+ this.batchSize = batchSize;
41
+ this.flushAfterMs = flushAfterMs;
42
+ if (![1, 2, 4].includes(batchSize) || !Number.isFinite(flushAfterMs) || flushAfterMs < 0 || flushAfterMs > 100) {
43
+ throw new Error('Budget della pipeline non valido');
44
+ }
45
+ this.known = new Map(prior);
46
+ this.control = { ...control, gate: () => control.gate(), signal: this.controller.signal };
47
+ // Pausing stops new production and PUTs, but can drain metadata for PUTs
48
+ // already finished. Cancellation still aborts every kind of request.
49
+ this.receiptControl = { ...this.control, gate: async () => { } };
50
+ control.signal?.addEventListener('abort', this.abort, { once: true });
51
+ this.detach = () => control.signal?.removeEventListener('abort', this.abort);
52
+ if (control.signal?.aborted)
53
+ this.abort();
54
+ }
55
+ detach;
56
+ get stats() {
57
+ return { activePuts: this.active.size, unconfirmedParts: this.unconfirmed,
58
+ retainedBytes: this.retainedBytes, transferredBytes: this.transferredBytes,
59
+ registeredBytes: this.registeredBytes, cachedSignatures: this.signatures.size };
60
+ }
61
+ restorePrefix(through) {
62
+ this.check();
63
+ if (!Number.isInteger(through) || through < 0 || through > 10_000 || this.active.size || this.unconfirmed || this.highestPart)
64
+ throw new Error('Ripristino del prefisso non valido');
65
+ for (let n = 1; n <= through; n++)
66
+ if (this.known.get(n)?.size !== PART || !/^[a-f0-9]{64}$/.test(this.known.get(n)?.digest || ''))
67
+ throw new Error('Prefisso non confermato');
68
+ this.contiguousPart = this.highestPart = through;
69
+ this.registeredBytes = through * PART;
70
+ }
71
+ async waitThrough(through) {
72
+ this.check();
73
+ if (!Number.isInteger(through) || through < 0 || through > this.highestPart)
74
+ throw new Error('Prefisso non prodotto');
75
+ while (this.contiguousPart < through) {
76
+ void this.flushRecords().catch(error => this.fail(error));
77
+ await new Promise(resolve => this.waiters.push(resolve));
78
+ this.check();
79
+ }
80
+ }
81
+ verifyPart(number) {
82
+ this.verified.add(number);
83
+ while (this.verified.delete(this.contiguousPart + 1))
84
+ this.contiguousPart++;
85
+ this.wake();
86
+ }
87
+ async enqueue(partNumber, body) {
88
+ this.check();
89
+ if (!Number.isInteger(partNumber) || partNumber <= this.highestPart || partNumber > 10_000 ||
90
+ !body.byteLength || body.byteLength > PART)
91
+ throw new Error('Parte fuori sequenza o dimensione non valida');
92
+ try {
93
+ await deliveryGate(this.control);
94
+ }
95
+ catch (error) {
96
+ this.check();
97
+ throw error;
98
+ }
99
+ while (this.active.size >= 4 || this.unconfirmed >= 8 || this.retainedBytes + body.byteLength > 4 * PART) {
100
+ if (this.unconfirmed >= 8)
101
+ void this.flushRecords().catch(error => this.fail(error));
102
+ await new Promise(resolve => this.waiters.push(resolve));
103
+ this.check();
104
+ }
105
+ this.check();
106
+ if (partNumber <= this.highestPart)
107
+ throw new Error('Parte già accodata');
108
+ this.highestPart = partNumber;
109
+ this.unconfirmed++;
110
+ this.retainedBytes += body.byteLength;
111
+ let released = false;
112
+ const release = () => { if (!released) {
113
+ released = true;
114
+ this.retainedBytes -= body.byteLength;
115
+ this.wake();
116
+ } };
117
+ const task = this.upload(partNumber, body, release).catch(error => this.fail(error)).finally(() => {
118
+ release();
119
+ this.active.delete(task);
120
+ this.wake();
121
+ });
122
+ this.active.add(task);
123
+ }
124
+ async upload(partNumber, body, release) {
125
+ const hash = await digest(body);
126
+ this.check();
127
+ const prior = this.known.get(partNumber);
128
+ if (prior?.digest && (prior.digest !== hash || prior.size !== body.byteLength)) {
129
+ throw new Error('La parte originale confermata non corrisponde al contenuto selezionato');
130
+ }
131
+ if (prior?.digest === hash && prior.size === body.byteLength) {
132
+ release();
133
+ this.unconfirmed--;
134
+ this.registeredBytes += body.byteLength;
135
+ this.verifyPart(partNumber);
136
+ this.onRegistered(body.byteLength, true);
137
+ return;
138
+ }
139
+ let attempt = 0;
140
+ const etag = await this.transport.put(() => this.signature(partNumber, attempt++ > 0), body, this.control);
141
+ this.check();
142
+ if (!etag?.trim())
143
+ throw new Error('ETag della parte non disponibile');
144
+ const receipt = { partNumber, size: body.byteLength, etag: etag.trim(), digest: hash };
145
+ release();
146
+ this.transferredBytes += receipt.size;
147
+ this.onPut(receipt.size);
148
+ this.pending.push(receipt);
149
+ if (this.pending.length >= this.batchSize)
150
+ void this.flushRecords().catch(error => this.fail(error));
151
+ else if (this.timer === null)
152
+ this.timer = setTimeout(() => {
153
+ this.timer = null;
154
+ void this.flushRecords().catch(error => this.fail(error));
155
+ }, this.flushAfterMs);
156
+ }
157
+ async signature(partNumber, renew) {
158
+ this.check();
159
+ if (renew) {
160
+ const reply = await this.transport.presign([partNumber], this.control);
161
+ this.validateSignatures(reply, [partNumber]);
162
+ return reply.parts[0].url;
163
+ }
164
+ for (;;) {
165
+ this.check();
166
+ const signed = this.signatures.get(partNumber);
167
+ this.signatures.delete(partNumber);
168
+ if (signed && signed.until > Date.now() + 30_000)
169
+ return signed.url;
170
+ if (this.signing) {
171
+ await this.signing;
172
+ continue;
173
+ }
174
+ const numbers = [];
175
+ // Digest completion order must not move the first signature window past
176
+ // an earlier concurrent part, forcing a second signing request for it.
177
+ const start = Math.floor((partNumber - 1) / 4) * 4 + 1;
178
+ for (let n = start; n < start + 4 && n <= 10_000; n++)
179
+ if (!this.known.get(n)?.digest)
180
+ numbers.push(n);
181
+ const started = Date.now();
182
+ this.signing = (async () => {
183
+ const reply = await this.transport.presign(numbers, this.control);
184
+ this.validateSignatures(reply, numbers);
185
+ this.signatures.clear();
186
+ for (const p of reply.parts)
187
+ this.signatures.set(p.partNumber, { url: p.url, until: started + reply.expiresIn * 1000 });
188
+ })();
189
+ try {
190
+ await this.signing;
191
+ }
192
+ finally {
193
+ this.signing = null;
194
+ }
195
+ }
196
+ }
197
+ validateSignatures(reply, numbers) {
198
+ if (!reply || !Array.isArray(reply.parts) || reply.parts.length !== numbers.length ||
199
+ new Set(reply.parts.map(p => p.partNumber)).size !== numbers.length ||
200
+ !Number.isFinite(reply.expiresIn) || reply.expiresIn <= 30 || reply.expiresIn > 900 ||
201
+ reply.parts.some(p => !numbers.includes(p.partNumber) || typeof p.url !== 'string' || !p.url.startsWith('https://'))) {
202
+ throw new Error('Risposta delle firme non valida');
203
+ }
204
+ }
205
+ async flushRecords() {
206
+ this.clearTimer();
207
+ for (;;) {
208
+ this.check();
209
+ if (this.recording) {
210
+ await this.recording;
211
+ continue;
212
+ }
213
+ if (!this.pending.length)
214
+ return;
215
+ const parts = this.pending.splice(0, this.batchSize).sort((a, b) => a.partNumber - b.partNumber);
216
+ for (const part of parts)
217
+ Object.freeze(part);
218
+ Object.freeze(parts);
219
+ // Acquire the serialization slot before hashing as well as network work.
220
+ const task = (async () => {
221
+ const batchId = await digest(new TextEncoder().encode(JSON.stringify([this.uploadId, parts])));
222
+ this.check();
223
+ const reply = await this.transport.record(parts, batchId, this.receiptControl);
224
+ this.check();
225
+ if (reply.batchId !== batchId || JSON.stringify(reply.parts) !== JSON.stringify(parts))
226
+ throw new Error('Conferma del batch non coerente');
227
+ for (const part of parts) {
228
+ this.known.set(part.partNumber, part);
229
+ this.unconfirmed--;
230
+ this.registeredBytes += part.size;
231
+ this.verifyPart(part.partNumber);
232
+ this.onRegistered(part.size, false);
233
+ }
234
+ })().catch(error => { this.fail(error); throw error; }).finally(() => { this.recording = null; this.wake(); });
235
+ this.recording = task;
236
+ await task;
237
+ }
238
+ }
239
+ async flush() {
240
+ while (this.active.size) {
241
+ await Promise.allSettled([...this.active]);
242
+ this.check();
243
+ }
244
+ await this.flushRecords();
245
+ this.check();
246
+ if (this.unconfirmed)
247
+ throw new Error('Registrazioni non ancora confermate');
248
+ }
249
+ async settle() {
250
+ await Promise.allSettled([...this.active, ...(this.recording ? [this.recording] : [])]);
251
+ this.clearTimer();
252
+ this.signatures.clear();
253
+ this.detach();
254
+ }
255
+ check() { if (this.failure !== null)
256
+ throw this.failure; checkCancelled(this.control); }
257
+ fail(error) {
258
+ if (this.failure === null)
259
+ this.failure = error;
260
+ this.clearTimer();
261
+ this.controller.abort();
262
+ this.wake();
263
+ }
264
+ clearTimer() { if (this.timer !== null) {
265
+ clearTimeout(this.timer);
266
+ this.timer = null;
267
+ } }
268
+ wake() { for (const resolve of this.waiters.splice(0))
269
+ resolve(); }
270
+ }
@@ -0,0 +1,112 @@
1
+ import { type UploadControl } from './delivery-network.js';
2
+ import { type UploadSessionContract } from './delivery-capabilities.js';
3
+ export declare const UPLOAD_COORDINATOR_ROLLOUT_ENABLED = false;
4
+ export interface UploadSessionReference {
5
+ version: 1;
6
+ id: string;
7
+ contractHash: string;
8
+ }
9
+ export interface UploadSessionSnapshot {
10
+ schemaVersion: 1;
11
+ id: string;
12
+ packageId: string;
13
+ contractHash: string;
14
+ contract: {
15
+ sessionId: string;
16
+ deliveryId: string;
17
+ storagePrefix: string;
18
+ pipelineContractVersion: 1;
19
+ capabilityRevision: string;
20
+ budgetRevision: string;
21
+ profile: 'free' | 'paid';
22
+ effectiveLimits: Record<string, Record<string, number>>;
23
+ format: {
24
+ manifestVersion: 2;
25
+ zipFormat: string;
26
+ partBytes: number;
27
+ pagePacking: string;
28
+ };
29
+ selection: {
30
+ sourceFingerprint: string;
31
+ fileCount: number;
32
+ sourceBytes: number;
33
+ galleryEnabled: boolean;
34
+ webEnabled: boolean;
35
+ webFormat: string;
36
+ };
37
+ };
38
+ nextSequence: number;
39
+ profile: string;
40
+ blocked: string | null;
41
+ negotiation: UploadSessionContract;
42
+ packageState: string;
43
+ progress: unknown;
44
+ slot: {
45
+ token: string;
46
+ expiresAt: number;
47
+ } | null;
48
+ pending: {
49
+ sequence: number;
50
+ action: string;
51
+ digest: string;
52
+ state: string;
53
+ recoverable?: boolean;
54
+ } | null;
55
+ receipt: {
56
+ sequence: number;
57
+ action: string;
58
+ digest: string;
59
+ state: string;
60
+ result: Record<string, unknown> | null;
61
+ resultRequiresProfile?: boolean;
62
+ } | null;
63
+ }
64
+ export interface UploadSessionTransport {
65
+ discover(control: UploadControl): Promise<unknown>;
66
+ status(body: Record<string, unknown>, control: UploadControl): Promise<UploadSessionSnapshot>;
67
+ unit(body: Record<string, unknown>, control: UploadControl): Promise<{
68
+ result: Record<string, unknown>;
69
+ session: UploadSessionSnapshot;
70
+ replay: boolean;
71
+ }>;
72
+ pause(body: Record<string, unknown>, control: UploadControl): Promise<{
73
+ released: boolean;
74
+ }>;
75
+ recover?(body: Record<string, unknown>, control: UploadControl): Promise<{
76
+ result: Record<string, unknown>;
77
+ session: UploadSessionSnapshot;
78
+ replay: boolean;
79
+ }>;
80
+ }
81
+ export declare const uploadSessionTransport: UploadSessionTransport;
82
+ /** Serializes control-plane units, not binary PUTs. Like the part/checkpoint
83
+ * helpers, it is directly exercised in local tests; production selection is
84
+ * separately fenced by the false rollout constant in UI/queue. */
85
+ export declare class DeliveryUploadCoordinator {
86
+ private id;
87
+ private reference;
88
+ private transport;
89
+ private current;
90
+ private capabilities;
91
+ private tail;
92
+ private queued;
93
+ private failure;
94
+ constructor(id: string, reference: UploadSessionReference, transport?: UploadSessionTransport);
95
+ get snapshot(): UploadSessionSnapshot | null;
96
+ private request;
97
+ private adopt;
98
+ private negotiated;
99
+ open(control: UploadControl): Promise<UploadSessionSnapshot>;
100
+ recover(control: UploadControl): Promise<Record<string, unknown>>;
101
+ json<T>(url: string, body: Record<string, unknown>, control: UploadControl): Promise<T>;
102
+ private execute;
103
+ drain(): Promise<void>;
104
+ pause(control: UploadControl): Promise<void>;
105
+ }
106
+ /** Production guard also runs for restored sessions while rollout is closed:
107
+ * absence of a new driver must never turn an existing contract into legacy. */
108
+ export declare function assertUploadCoordinatorSelection(reference?: UploadSessionReference): void;
109
+ export declare function validateNewUploadNegotiation(capabilities: unknown): void;
110
+ /** Admission precedes createPackage. A pending creation id survives a lost
111
+ * response/browser restart; successful explicit new uploads get a new id. */
112
+ export declare function prepareUploadSession(input: Record<string, unknown>, capabilities: unknown, control: UploadControl): Promise<UploadSessionSnapshot | null>;
@@ -0,0 +1,229 @@
1
+ import { deliveryJson, deliveryGate, checkCancelled, DeliveryRequestError } from './delivery-network.js';
2
+ import { negotiateDeliveryUpload, uploadPolicyRecovery } from './delivery-capabilities.js';
3
+ export const UPLOAD_COORDINATOR_ROLLOUT_ENABLED = false;
4
+ const endpoint = '/admin/api/deliveries';
5
+ const closed = (code = 'upload_capability_changed', message = 'La sessione è conservata. Rileggi il contratto prima di riprendere.') => new DeliveryRequestError(message, false, 0, code, 409);
6
+ const canonical = (v) => v === null || typeof v !== 'object' ? JSON.stringify(v) : Array.isArray(v) ? '[' + v.map(canonical).join(',') + ']' :
7
+ '{' + Object.keys(v).sort().map(k => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}';
8
+ const hash = async (v) => [...new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonical(v))))].map(n => n.toString(16).padStart(2, '0')).join('');
9
+ const bare = (control) => ({ writerToken: control.writerToken, signal: control.signal, gate: async () => { }, networkWaiting: control.networkWaiting });
10
+ export const uploadSessionTransport = {
11
+ discover: control => deliveryJson(endpoint, { action: 'capabilities' }, bare(control)),
12
+ status: async (body, control) => (await deliveryJson(endpoint, { ...body, action: 'uploadSessionStatus' }, bare(control), false)).session,
13
+ unit: (body, control) => deliveryJson(endpoint, { ...body, action: 'uploadSessionUnit' }, bare(control), false),
14
+ pause: (body, control) => deliveryJson(endpoint, { ...body, action: 'uploadSessionPause' }, bare(control), false),
15
+ recover: (body, control) => deliveryJson(endpoint, { ...body, action: 'uploadSessionRecover' }, bare(control), false),
16
+ };
17
+ /** Serializes control-plane units, not binary PUTs. Like the part/checkpoint
18
+ * helpers, it is directly exercised in local tests; production selection is
19
+ * separately fenced by the false rollout constant in UI/queue. */
20
+ export class DeliveryUploadCoordinator {
21
+ id;
22
+ reference;
23
+ transport;
24
+ current = null;
25
+ capabilities;
26
+ tail = Promise.resolve();
27
+ queued = 0;
28
+ failure;
29
+ constructor(id, reference, transport = uploadSessionTransport) {
30
+ this.id = id;
31
+ this.reference = reference;
32
+ this.transport = transport;
33
+ }
34
+ get snapshot() { return this.current ? structuredClone(this.current) : null; }
35
+ request(control, sequence) {
36
+ return { id: this.id, sessionId: this.reference.id, writerToken: control.writerToken, ...(sequence === undefined ? {} : { sequence }) };
37
+ }
38
+ async adopt(s) {
39
+ if (this.reference.version !== 1 || !s || s.schemaVersion !== 1 || s.id !== this.id || s.packageId !== this.reference.id || s.contractHash !== this.reference.contractHash ||
40
+ s.contract?.sessionId !== s.packageId || s.contract.deliveryId !== s.id || s.contract.pipelineContractVersion !== 1 ||
41
+ s.contract.format?.manifestVersion !== 2 || s.contract.format.partBytes !== 16777216 || s.contract.format.zipFormat !== 'store-header-v1' ||
42
+ s.contract.format.pagePacking !== 'common-v1' || !Number.isSafeInteger(s.nextSequence) || s.nextSequence < 0 ||
43
+ await hash(s.contract) !== this.reference.contractHash || this.current && s.nextSequence < this.current.nextSequence)
44
+ throw closed();
45
+ this.current = structuredClone(s);
46
+ }
47
+ negotiated() {
48
+ const result = negotiateDeliveryUpload(this.capabilities, this.current.negotiation);
49
+ if (result.mode !== 'candidate')
50
+ throw closed(result.mode === 'blocked' ? result.code : undefined);
51
+ if (this.current.blocked)
52
+ throw closed(this.current.blocked);
53
+ if (result.admission !== 'available')
54
+ throw closed(result.admission === 'exhausted' ? 'upload_quota_exhausted' : 'upload_budget_unknown');
55
+ if (!result.features.segmentedFinalize || !result.features.minimalActivate)
56
+ throw closed();
57
+ return result;
58
+ }
59
+ async open(control) {
60
+ await this.adopt(await this.transport.status(this.request(control), bare(control)));
61
+ this.capabilities = structuredClone(await this.transport.discover(bare(control)));
62
+ this.negotiated();
63
+ if (this.current.pending)
64
+ await this.recover(control);
65
+ return this.snapshot;
66
+ }
67
+ async recover(control) {
68
+ const pending = this.current?.pending;
69
+ if (pending?.state !== 'uncertain' || !pending.recoverable || !this.transport.recover || !control.writerToken)
70
+ throw closed('upload_unit_uncertain', 'Esito non dimostrato: stato conservato.');
71
+ this.negotiated();
72
+ try {
73
+ const response = await this.transport.recover({ ...this.request(control, pending.sequence), capabilityRevision: this.current.negotiation.capabilityRevision }, bare(control));
74
+ checkCancelled(control);
75
+ if (response.result?.ok !== true || response.session.nextSequence !== pending.sequence + 1)
76
+ throw closed();
77
+ await this.adopt(response.session);
78
+ return response.result;
79
+ }
80
+ catch (e) {
81
+ checkCancelled(control);
82
+ const state = await this.transport.status(this.request(control, pending.sequence), bare(control));
83
+ await this.adopt(state);
84
+ if (state.receipt?.resultRequiresProfile)
85
+ throw closed('upload_profile_required');
86
+ if (state.receipt?.state === 'committed' && state.receipt.digest === pending.digest && state.receipt.result?.ok === true)
87
+ return state.receipt.result;
88
+ throw e;
89
+ }
90
+ }
91
+ async json(url, body, control) {
92
+ if (!['/admin/api/deliveries', '/admin/api/delivery/multipart'].includes(url))
93
+ throw closed();
94
+ await deliveryGate(control);
95
+ if (this.queued >= 16)
96
+ throw closed('upload_budget_exceeded', 'Troppe operazioni di controllo pendenti');
97
+ // Receipt identity follows the actual JSON wire representation: optional
98
+ // undefined fields must not hash differently after a lost HTTP response.
99
+ const payload = JSON.parse(JSON.stringify(body));
100
+ for (const [key, value] of [['id', this.id], ['packageId', this.reference.id], ['writerToken', control.writerToken]]) {
101
+ if (payload[key] !== undefined && payload[key] !== value)
102
+ throw closed();
103
+ delete payload[key];
104
+ }
105
+ this.queued++;
106
+ const run = this.tail.catch(() => { }).then(() => { if (this.failure)
107
+ throw this.failure; return this.execute(payload, control); });
108
+ this.tail = run;
109
+ try {
110
+ return await run;
111
+ }
112
+ catch (e) {
113
+ this.failure = e;
114
+ throw e;
115
+ }
116
+ finally {
117
+ this.queued--;
118
+ }
119
+ }
120
+ async execute(payload, control) {
121
+ checkCancelled(control);
122
+ if (!this.current)
123
+ await this.open(control);
124
+ this.negotiated();
125
+ const sequence = this.current.nextSequence, digest = await hash(payload);
126
+ for (let refreshes = 0;; refreshes++) {
127
+ checkCancelled(control);
128
+ try {
129
+ const response = await this.transport.unit({ ...this.request(control, sequence), capabilityRevision: this.current.negotiation.capabilityRevision, body: payload }, bare(control));
130
+ checkCancelled(control);
131
+ if (response.result?.ok !== true || response.session.nextSequence !== sequence + 1)
132
+ throw closed();
133
+ await this.adopt(response.session);
134
+ return response.result;
135
+ }
136
+ catch (e) {
137
+ checkCancelled(control);
138
+ const recovery = uploadPolicyRecovery(e, refreshes);
139
+ const transportFailure = e instanceof DeliveryRequestError && e.retryable;
140
+ if (recovery !== 'refresh-and-reconcile' && !transportFailure)
141
+ throw e;
142
+ if (refreshes >= 2)
143
+ throw e;
144
+ // Reconcile BEFORE retry, profile adaptation or grouping. Never replace
145
+ // an uncertain payload with smaller/new batches using a different id.
146
+ const state = await this.transport.status(this.request(control, sequence), bare(control));
147
+ await this.adopt(state);
148
+ const receipt = state.receipt;
149
+ if (receipt?.sequence === sequence && receipt.state === 'committed') {
150
+ if (receipt.resultRequiresProfile)
151
+ throw closed('upload_profile_required');
152
+ if (receipt.digest !== digest || receipt.action !== payload.action || receipt.result?.ok !== true)
153
+ throw closed();
154
+ return receipt.result;
155
+ }
156
+ if (state.pending) {
157
+ if (state.pending.sequence !== sequence || state.pending.digest !== digest)
158
+ throw closed();
159
+ this.capabilities = structuredClone(await this.transport.discover(bare(control)));
160
+ this.negotiated();
161
+ return await this.recover(control);
162
+ }
163
+ if (state.nextSequence !== sequence)
164
+ throw closed('upload_unit_uncertain', 'Esito incerto: nessun nuovo invio o fallback.');
165
+ this.capabilities = structuredClone(await this.transport.discover(bare(control)));
166
+ this.negotiated();
167
+ }
168
+ }
169
+ }
170
+ async drain() { await this.tail; }
171
+ async pause(control) {
172
+ await this.drain();
173
+ const slot = this.current?.slot;
174
+ if (!slot)
175
+ return;
176
+ const response = await this.transport.pause({ ...this.request(control), slotToken: slot.token }, bare(control));
177
+ if (response.released && this.current)
178
+ this.current.slot = null;
179
+ }
180
+ }
181
+ /** Production guard also runs for restored sessions while rollout is closed:
182
+ * absence of a new driver must never turn an existing contract into legacy. */
183
+ export function assertUploadCoordinatorSelection(reference) {
184
+ if (reference && !UPLOAD_COORDINATOR_ROLLOUT_ENABLED)
185
+ throw closed();
186
+ }
187
+ export function validateNewUploadNegotiation(capabilities) {
188
+ if (!UPLOAD_COORDINATOR_ROLLOUT_ENABLED)
189
+ return;
190
+ const negotiated = negotiateDeliveryUpload(capabilities);
191
+ if (negotiated.mode === 'blocked')
192
+ throw closed(negotiated.code);
193
+ if (negotiated.mode === 'candidate' && !negotiated.canStart)
194
+ throw closed('upload_budget_unknown');
195
+ }
196
+ /** Admission precedes createPackage. A pending creation id survives a lost
197
+ * response/browser restart; successful explicit new uploads get a new id. */
198
+ export async function prepareUploadSession(input, capabilities, control) {
199
+ if (!UPLOAD_COORDINATOR_ROLLOUT_ENABLED)
200
+ return null;
201
+ validateNewUploadNegotiation(capabilities);
202
+ const negotiated = negotiateDeliveryUpload(capabilities);
203
+ if (negotiated.mode === 'legacy')
204
+ return null;
205
+ if (negotiated.mode !== 'candidate' || !negotiated.canStart)
206
+ throw closed();
207
+ const key = 'adminkit-upload-create:' + await hash(input);
208
+ let sessionId, writerToken;
209
+ try {
210
+ sessionId = localStorage.getItem(key) || crypto.randomUUID();
211
+ localStorage.setItem(key, sessionId);
212
+ const writerKey = `adminkit-delivery-writer:${sessionId}`;
213
+ writerToken = localStorage.getItem(writerKey) || crypto.randomUUID();
214
+ localStorage.setItem(writerKey, writerToken);
215
+ }
216
+ catch {
217
+ throw closed('upload_capability_changed', 'Il browser non può conservare l’identità della sessione.');
218
+ }
219
+ const result = await deliveryJson(endpoint, { ...input, sessionId, writerToken,
220
+ action: 'uploadSessionCreate', pipelineContractVersion: 1, capabilityRevision: negotiated.revision }, bare(control), false);
221
+ const reference = { version: 1, id: sessionId, contractHash: result.session.contractHash };
222
+ const check = new DeliveryUploadCoordinator(String(input.id), reference, { ...uploadSessionTransport, status: async () => result.session, discover: async () => capabilities });
223
+ await check.open(control);
224
+ try {
225
+ localStorage.removeItem(key);
226
+ }
227
+ catch { }
228
+ return check.snapshot;
229
+ }
@@ -11,10 +11,13 @@ export interface DeliveryUploadProgress {
11
11
  sourceBytes: number;
12
12
  uploadedBytes: number;
13
13
  transferredBytes: number;
14
+ /** Persistent original ZIP prefix, distinct from transferred/recorded bytes. */
15
+ checkpointBytes?: number;
14
16
  startedAt: number;
15
17
  transferStartedAt?: number;
16
18
  note?: string;
17
19
  }
20
+ export declare function deliveryProgressPercent(progress: DeliveryUploadProgress): number;
18
21
  export interface DeliveryManifestEntry {
19
22
  name: string;
20
23
  type: string;
@@ -62,6 +65,17 @@ interface MemberCheckpoint {
62
65
  date: number;
63
66
  zipFormat?: ZipFormat;
64
67
  headerCrc?: number;
68
+ headerRead?: number;
69
+ descriptorRead?: number;
70
+ metadataProtocol?: 'original-replay-v1';
71
+ }
72
+ interface DirectoryCheckpoint {
73
+ stage: 'directory';
74
+ zipFormat: ZipFormat;
75
+ directoryOffset: number;
76
+ directoryRead: number;
77
+ directoryChain: string;
78
+ metadataProtocol?: 'original-replay-v1';
65
79
  }
66
80
  export declare function uploadDeliveryPackage(deliveryId: string, packageId: string, selected: File[], options: UploadOptions, onProgress: (progress: DeliveryUploadProgress) => void, control?: UploadControl): Promise<UploadResult>;
67
81
  interface ZipSink {
@@ -70,15 +84,17 @@ interface ZipSink {
70
84
  close(): Promise<void>;
71
85
  }
72
86
  export declare class ZipStream {
87
+ private extendedCheckpoints;
73
88
  private utc;
74
89
  private sink;
75
90
  private offset;
76
91
  private entries;
77
92
  private format;
78
- constructor(sink: ZipSink, utc?: boolean, format?: ZipFormat);
79
- restore(entries: DeliveryManifestEntry[], files: File[], offset: number): void;
93
+ private directoryResume?;
94
+ constructor(sink: ZipSink, utc?: boolean, format?: ZipFormat, extendedCheckpoints?: boolean);
95
+ restore(entries: DeliveryManifestEntry[], files: File[], offset: number, directory?: DirectoryCheckpoint): void;
80
96
  add(nameValue: string, blob: Blob, progress?: (read: number, preparing?: boolean) => void, modified?: Date, checkpoint?: (current: MemberCheckpoint, offset: number) => Promise<void>, resume?: MemberCheckpoint): Promise<ZipMember>;
81
- close(): Promise<void>;
97
+ close(checkpoint?: (current: DirectoryCheckpoint, offset: number) => Promise<void>): Promise<void>;
82
98
  private sinkGate;
83
99
  private push;
84
100
  }