llm-large-files 0.5.0 → 0.7.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.
- package/CHANGELOG.md +1402 -467
- package/README.md +188 -60
- package/dist/analyze.d.ts +5 -0
- package/dist/analyze.d.ts.map +1 -1
- package/dist/analyze.js +96 -47
- package/dist/analyze.js.map +1 -1
- package/dist/anthropic/adapter.d.ts +14 -3
- package/dist/anthropic/adapter.d.ts.map +1 -1
- package/dist/anthropic/adapter.js +190 -39
- package/dist/anthropic/adapter.js.map +1 -1
- package/dist/ask.d.ts +60 -4
- package/dist/ask.d.ts.map +1 -1
- package/dist/ask.js +1068 -206
- package/dist/ask.js.map +1 -1
- package/dist/encoding.d.ts +17 -0
- package/dist/encoding.d.ts.map +1 -0
- package/dist/encoding.js +852 -0
- package/dist/encoding.js.map +1 -0
- package/dist/errors.d.ts +4 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +15 -0
- package/dist/errors.js.map +1 -1
- package/dist/events.d.ts +333 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/events.js +159 -0
- package/dist/events.js.map +1 -0
- package/dist/evidence.d.ts +2 -0
- package/dist/evidence.d.ts.map +1 -1
- package/dist/evidence.js +3 -2
- package/dist/evidence.js.map +1 -1
- package/dist/extract.d.ts +35 -3
- package/dist/extract.d.ts.map +1 -1
- package/dist/extract.js +626 -58
- package/dist/extract.js.map +1 -1
- package/dist/gemini/adapter.d.ts +17 -8
- package/dist/gemini/adapter.d.ts.map +1 -1
- package/dist/gemini/adapter.js +108 -61
- package/dist/gemini/adapter.js.map +1 -1
- package/dist/gemini/chat.d.ts +23 -3
- package/dist/gemini/chat.d.ts.map +1 -1
- package/dist/gemini/chat.js +6 -2
- package/dist/gemini/chat.js.map +1 -1
- package/dist/gemini/errors.d.ts +9 -4
- package/dist/gemini/errors.d.ts.map +1 -1
- package/dist/gemini/errors.js +32 -0
- package/dist/gemini/errors.js.map +1 -1
- package/dist/gemini/generate.d.ts +10 -2
- package/dist/gemini/generate.d.ts.map +1 -1
- package/dist/gemini/generate.js +13 -7
- package/dist/gemini/generate.js.map +1 -1
- package/dist/gemini/index.d.ts +3 -3
- package/dist/gemini/index.d.ts.map +1 -1
- package/dist/gemini/index.js +2 -2
- package/dist/gemini/index.js.map +1 -1
- package/dist/gemini/sse.d.ts +1 -1
- package/dist/gemini/sse.d.ts.map +1 -1
- package/dist/gemini/sse.js +1 -1
- package/dist/gemini/sse.js.map +1 -1
- package/dist/http.d.ts +116 -0
- package/dist/http.d.ts.map +1 -1
- package/dist/http.js +347 -1
- package/dist/http.js.map +1 -1
- package/dist/index.d.ts +11 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/library.d.ts +67 -5
- package/dist/library.d.ts.map +1 -1
- package/dist/library.js +405 -85
- package/dist/library.js.map +1 -1
- package/dist/map-reduce.d.ts +28 -1
- package/dist/map-reduce.d.ts.map +1 -1
- package/dist/map-reduce.js +240 -52
- package/dist/map-reduce.js.map +1 -1
- package/dist/model.d.ts +84 -2
- package/dist/model.d.ts.map +1 -1
- package/dist/model.js +182 -1
- package/dist/model.js.map +1 -1
- package/dist/node/handlers.d.ts +20 -4
- package/dist/node/handlers.d.ts.map +1 -1
- package/dist/node/handlers.js +122 -20
- package/dist/node/handlers.js.map +1 -1
- package/dist/node/index.d.ts +2 -0
- package/dist/node/index.d.ts.map +1 -1
- package/dist/node/index.js +1 -0
- package/dist/node/index.js.map +1 -1
- package/dist/node/sse.d.ts +59 -0
- package/dist/node/sse.d.ts.map +1 -0
- package/dist/node/sse.js +174 -0
- package/dist/node/sse.js.map +1 -0
- package/dist/openai/adapter.d.ts +29 -5
- package/dist/openai/adapter.d.ts.map +1 -1
- package/dist/openai/adapter.js +311 -37
- package/dist/openai/adapter.js.map +1 -1
- package/dist/output-limit.d.ts +14 -2
- package/dist/output-limit.d.ts.map +1 -1
- package/dist/output-limit.js +39 -10
- package/dist/output-limit.js.map +1 -1
- package/dist/pause.d.ts +24 -0
- package/dist/pause.d.ts.map +1 -0
- package/dist/pause.js +38 -0
- package/dist/pause.js.map +1 -0
- package/dist/pdf-pages.d.ts +32 -2
- package/dist/pdf-pages.d.ts.map +1 -1
- package/dist/pdf-pages.js +275 -14
- package/dist/pdf-pages.js.map +1 -1
- package/dist/pdf-pictures.d.ts +30 -3
- package/dist/pdf-pictures.d.ts.map +1 -1
- package/dist/pdf-pictures.js +50 -8
- package/dist/pdf-pictures.js.map +1 -1
- package/dist/pdf-work.d.ts +40 -0
- package/dist/pdf-work.d.ts.map +1 -0
- package/dist/pdf-work.js +734 -0
- package/dist/pdf-work.js.map +1 -0
- package/dist/plan.d.ts +22 -4
- package/dist/plan.d.ts.map +1 -1
- package/dist/plan.js +61 -12
- package/dist/plan.js.map +1 -1
- package/dist/retry.d.ts +23 -1
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +33 -3
- package/dist/retry.js.map +1 -1
- package/dist/search.d.ts +8 -2
- package/dist/search.d.ts.map +1 -1
- package/dist/search.js +60 -10
- package/dist/search.js.map +1 -1
- package/dist/sse.d.ts +35 -2
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +145 -31
- package/dist/sse.js.map +1 -1
- package/dist/stores.d.ts.map +1 -1
- package/dist/stores.js +5 -2
- package/dist/stores.js.map +1 -1
- package/dist/text-index.d.ts +6 -0
- package/dist/text-index.d.ts.map +1 -1
- package/dist/text-index.js +25 -8
- package/dist/text-index.js.map +1 -1
- package/dist/text.d.ts +62 -2
- package/dist/text.d.ts.map +1 -1
- package/dist/text.js +314 -14
- package/dist/text.js.map +1 -1
- package/dist/tools.d.ts +61 -1
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +269 -42
- package/dist/tools.js.map +1 -1
- package/dist/types.d.ts +102 -3
- package/dist/types.d.ts.map +1 -1
- package/dist/zip-directory.d.ts +43 -0
- package/dist/zip-directory.d.ts.map +1 -0
- package/dist/zip-directory.js +130 -0
- package/dist/zip-directory.js.map +1 -0
- package/docs/README.md +288 -0
- package/docs/api.md +37 -381
- package/docs/configuration.md +28 -558
- package/docs/getting-started.md +407 -223
- package/docs/guides/anthropic.md +590 -0
- package/docs/guides/conversations.md +629 -0
- package/docs/guides/costs-and-limits.md +726 -0
- package/docs/guides/deployment.md +654 -0
- package/docs/guides/errors-and-reliability.md +735 -0
- package/docs/guides/explorer-model.md +399 -0
- package/docs/guides/openai-compatible.md +602 -0
- package/docs/guides/own-adapter-and-loop.md +1169 -0
- package/docs/guides/pdfs.md +971 -0
- package/docs/guides/storage.md +731 -0
- package/docs/guides/testing.md +1199 -0
- package/docs/guides/vertex-and-gemini.md +717 -0
- package/docs/guides/web-app.md +1589 -0
- package/docs/how-it-works.md +1012 -164
- package/docs/measurements.md +881 -0
- package/docs/publishing.md +274 -46
- package/docs/reference/anthropic.md +427 -0
- package/docs/reference/ask.md +892 -0
- package/docs/reference/errors-and-retries.md +758 -0
- package/docs/reference/events.md +993 -0
- package/docs/reference/gemini.md +823 -0
- package/docs/reference/library.md +1467 -0
- package/docs/reference/node.md +528 -0
- package/docs/reference/openai.md +385 -0
- package/docs/reference/tools.md +883 -0
- package/docs/security.md +897 -103
- package/docs/troubleshooting.md +1390 -0
- package/package.json +2 -2
- package/src/analyze.ts +93 -42
- package/src/anthropic/adapter.ts +196 -39
- package/src/ask.ts +1087 -202
- package/src/encoding.ts +850 -0
- package/src/errors.ts +17 -0
- package/src/events.ts +442 -0
- package/src/evidence.ts +5 -2
- package/src/extract.ts +602 -62
- package/src/gemini/adapter.ts +118 -65
- package/src/gemini/chat.ts +28 -4
- package/src/gemini/errors.ts +34 -1
- package/src/gemini/generate.ts +23 -10
- package/src/gemini/index.ts +3 -3
- package/src/gemini/sse.ts +1 -1
- package/src/http.ts +376 -1
- package/src/index.ts +27 -5
- package/src/library.ts +459 -85
- package/src/map-reduce.ts +252 -51
- package/src/model.ts +236 -3
- package/src/node/handlers.ts +137 -22
- package/src/node/index.ts +2 -0
- package/src/node/sse.ts +198 -0
- package/src/openai/adapter.ts +306 -38
- package/src/output-limit.ts +44 -8
- package/src/pause.ts +41 -0
- package/src/pdf-pages.ts +268 -15
- package/src/pdf-pictures.ts +56 -9
- package/src/pdf-work.ts +722 -0
- package/src/plan.ts +68 -12
- package/src/retry.ts +49 -5
- package/src/search.ts +63 -10
- package/src/sse.ts +153 -28
- package/src/stores.ts +5 -2
- package/src/text-index.ts +26 -7
- package/src/text.ts +323 -13
- package/src/tools.ts +261 -42
- package/src/types.ts +107 -4
- package/src/zip-directory.ts +136 -0
package/dist/output-limit.d.ts
CHANGED
|
@@ -6,11 +6,22 @@
|
|
|
6
6
|
* 25,000 for its reasoning models.
|
|
7
7
|
*/
|
|
8
8
|
export declare const THINKING_OUTPUT_TOKENS = 32768;
|
|
9
|
+
/**
|
|
10
|
+
* Why a reply had no text, when this error is the one `completeWithinLimit` throws for it: the
|
|
11
|
+
* provider's word for why it stopped ("SAFETY", "refusal"), or "" when it did not say. Undefined
|
|
12
|
+
* for any other error. The message of that error is the package's own.
|
|
13
|
+
*/
|
|
14
|
+
export declare function noTextReason(error: unknown): string | undefined;
|
|
9
15
|
/** A reply to a plain completion. */
|
|
10
16
|
export type LimitedReply = {
|
|
11
17
|
text: string;
|
|
12
18
|
/** True when the model stopped because it reached the output limit. */
|
|
13
19
|
cutOff: boolean;
|
|
20
|
+
/**
|
|
21
|
+
* True when the provider stopped the reply before its end for another reason (its safety
|
|
22
|
+
* filters): what it wrote is kept, and said to be incomplete, as a reply cut off at the limit is.
|
|
23
|
+
*/
|
|
24
|
+
stopped?: boolean;
|
|
14
25
|
/** Why it stopped, in the provider's word, for the message when there is no text. */
|
|
15
26
|
reason?: string;
|
|
16
27
|
/** Tokens the model spent thinking, when the provider says. */
|
|
@@ -20,8 +31,9 @@ export type LimitedReply = {
|
|
|
20
31
|
* Sends a completion with an output limit, and once more with `THINKING_OUTPUT_TOKENS` when the
|
|
21
32
|
* reply was cut off with nothing written, or with half the limit or more gone on thoughts. What
|
|
22
33
|
* was learned is kept under `model` (a URL, or a URL and a model name): later requests start with
|
|
23
|
-
* the larger limit, and a model that refused it (HTTP 400
|
|
24
|
-
*
|
|
34
|
+
* the larger limit, and a model that refused it (HTTP 400, but not for a request too large for the
|
|
35
|
+
* window with it) is not asked for it again, nor is one whose window, or allowance a minute, is no
|
|
36
|
+
* larger than that limit. Requests that arrive while the first one to a model is on its way wait for it.
|
|
25
37
|
*/
|
|
26
38
|
export declare function completeWithinLimit(model: string, maxOutputTokens: number, send: (limit: number) => Promise<LimitedReply>, options?: {
|
|
27
39
|
signal?: AbortSignal | undefined;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output-limit.d.ts","sourceRoot":"","sources":["../src/output-limit.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,QAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"output-limit.d.ts","sourceRoot":"","sources":["../src/output-limit.ts"],"names":[],"mappings":"AAGA;;;;;;GAMG;AACH,eAAO,MAAM,sBAAsB,QAAS,CAAC;AAwB7C;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,SAAS,CAE/D;AAED,qCAAqC;AACrC,MAAM,MAAM,YAAY,GAAG;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,MAAM,EAAE,OAAO,CAAC;IAChB;;;OAGG;IACH,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,qFAAqF;IACrF,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,+DAA+D;IAC/D,QAAQ,EAAE,MAAM,CAAC;CAClB,CAAC;AAEF;;;;;;;GAOG;AACH,wBAAsB,mBAAmB,CAAC,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,YAAY,CAAC,EAAE,OAAO,GAAE;IACzI,MAAM,CAAC,EAAE,WAAW,GAAG,SAAS,CAAC;IACjC,WAAW,CAAC,EAAE,CAAC,MAAM,IAAI,CAAC,GAAG,SAAS,CAAC;CACnC,GAAG,OAAO,CAAC,MAAM,CAAC,CAgEvB"}
|
package/dist/output-limit.js
CHANGED
|
@@ -23,12 +23,26 @@ function remember(model, limit) {
|
|
|
23
23
|
learnedLimits.clear();
|
|
24
24
|
learnedLimits.set(model, limit);
|
|
25
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* The errors `completeWithinLimit` threw for a reply with no text, with why the reply stopped, in
|
|
28
|
+
* the provider's word ("" when it did not say).
|
|
29
|
+
*/
|
|
30
|
+
const noTextErrors = new WeakMap();
|
|
31
|
+
/**
|
|
32
|
+
* Why a reply had no text, when this error is the one `completeWithinLimit` throws for it: the
|
|
33
|
+
* provider's word for why it stopped ("SAFETY", "refusal"), or "" when it did not say. Undefined
|
|
34
|
+
* for any other error. The message of that error is the package's own.
|
|
35
|
+
*/
|
|
36
|
+
export function noTextReason(error) {
|
|
37
|
+
return typeof error === "object" && error !== null ? noTextErrors.get(error) : undefined;
|
|
38
|
+
}
|
|
26
39
|
/**
|
|
27
40
|
* Sends a completion with an output limit, and once more with `THINKING_OUTPUT_TOKENS` when the
|
|
28
41
|
* reply was cut off with nothing written, or with half the limit or more gone on thoughts. What
|
|
29
42
|
* was learned is kept under `model` (a URL, or a URL and a model name): later requests start with
|
|
30
|
-
* the larger limit, and a model that refused it (HTTP 400
|
|
31
|
-
*
|
|
43
|
+
* the larger limit, and a model that refused it (HTTP 400, but not for a request too large for the
|
|
44
|
+
* window with it) is not asked for it again, nor is one whose window, or allowance a minute, is no
|
|
45
|
+
* larger than that limit. Requests that arrive while the first one to a model is on its way wait for it.
|
|
32
46
|
*/
|
|
33
47
|
export async function completeWithinLimit(model, maxOutputTokens, send, options = {}) {
|
|
34
48
|
const { signal } = options;
|
|
@@ -70,18 +84,33 @@ export async function completeWithinLimit(model, maxOutputTokens, send, options
|
|
|
70
84
|
if (signal?.aborted)
|
|
71
85
|
throw error;
|
|
72
86
|
// A model or a gateway that refuses the larger limit (HTTP 400) is not asked for it again.
|
|
73
|
-
//
|
|
74
|
-
// the
|
|
75
|
-
|
|
76
|
-
|
|
87
|
+
// A refusal of this request as too large for the window with that limit is no such refusal,
|
|
88
|
+
// unless the window is no larger than the limit itself: a smaller part may fit. Nothing is
|
|
89
|
+
// learned from it, and the next request starts as this one did. A request too large for
|
|
90
|
+
// what the provider allows in a minute (OpenAI's or Groq's TPM, HTTP 429 or 413) is too
|
|
91
|
+
// large the same way, with that allowance as the window. Any other failure says nothing
|
|
92
|
+
// about the limit: the next request starts with it. What the first reply had is kept; with
|
|
93
|
+
// nothing in it, this error is the one to report.
|
|
94
|
+
const { status, kind, limitTokens } = (error ?? {});
|
|
95
|
+
if (status === 400 || kind === "context_overflow") {
|
|
96
|
+
const tooLarge = kind === "context_overflow" && !(typeof limitTokens === "number" && limitTokens <= THINKING_OUTPUT_TOKENS);
|
|
97
|
+
if (!tooLarge)
|
|
98
|
+
remember(model, 0);
|
|
99
|
+
else if (learnedLimits.get(model) === THINKING_OUTPUT_TOKENS)
|
|
100
|
+
learnedLimits.delete(model);
|
|
101
|
+
}
|
|
77
102
|
if (!reply.text.trim())
|
|
78
103
|
throw error;
|
|
79
104
|
}
|
|
80
105
|
}
|
|
81
|
-
if (!reply.text.trim())
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
106
|
+
if (!reply.text.trim()) {
|
|
107
|
+
const error = new Error(`The model returned no text${reply.reason ? ` (${reply.reason})` : ""}.`);
|
|
108
|
+
noTextErrors.set(error, reply.reason ?? "");
|
|
109
|
+
throw error;
|
|
110
|
+
}
|
|
111
|
+
// The text stops mid-list when the output limit is reached, or when a filter stopped it. Say so
|
|
112
|
+
// instead of passing it off as complete.
|
|
113
|
+
if (reply.cutOff || reply.stopped)
|
|
85
114
|
options.onTruncated?.();
|
|
86
115
|
return reply.text;
|
|
87
116
|
}
|
package/dist/output-limit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output-limit.js","sourceRoot":"","sources":["../src/output-limit.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,oBAAoB;AAEpB;;;;;;GAMG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAG,MAAM,CAAC;AAE7C;;;GAGG;AACH,MAAM,aAAa,GAAG,IAAI,GAAG,EAAkB,CAAC;AAChD,6FAA6F;AAC7F,MAAM,aAAa,GAAG,IAAI,GAAG,EAAyB,CAAC;AACvD,+CAA+C;AAC/C,MAAM,QAAQ,GAAG,IAAI,GAAG,EAAU,CAAC;AACnC,MAAM,eAAe,GAAG,GAAG,CAAC;AAE5B,SAAS,QAAQ,CAAC,KAAa,EAAE,KAAa;IAC5C,IAAI,aAAa,CAAC,IAAI,IAAI,eAAe,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC,KAAK,CAAC;QAAE,aAAa,CAAC,KAAK,EAAE,CAAC;IAC9F,aAAa,CAAC,GAAG,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;AAClC,CAAC;
|
|
1
|
+
{"version":3,"file":"output-limit.js","sourceRoot":"","sources":["../src/output-limit.ts"],"names":[],"mappings":"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"}
|
package/dist/pause.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** Lets other work on the server run (an answer streaming to another user) before going on. */
|
|
2
|
+
export declare const pause: () => Promise<void>;
|
|
3
|
+
/**
|
|
4
|
+
* `pause`, taken in turns: each caller waits for the pause before it, so one slice of work runs in
|
|
5
|
+
* a turn of the event loop. Ten uploads that pause at once then hold the server for one slice
|
|
6
|
+
* between two turns, not ten.
|
|
7
|
+
*/
|
|
8
|
+
export declare const fairPause: () => Promise<void>;
|
|
9
|
+
/**
|
|
10
|
+
* Splits a long piece of synchronous work into slices, so that one upload does not hold the whole
|
|
11
|
+
* server: call `maybePause()` now and then (every few thousand items), and it pauses once the
|
|
12
|
+
* current slice has run for about 12 ms. It also stops the work when `signal` is aborted.
|
|
13
|
+
*/
|
|
14
|
+
export declare class TimeSlicer {
|
|
15
|
+
private readonly signal?;
|
|
16
|
+
private sliceStart;
|
|
17
|
+
constructor(signal?: AbortSignal | undefined);
|
|
18
|
+
/** Whether the current slice has run its time: `maybePause` would pause now. */
|
|
19
|
+
get due(): boolean;
|
|
20
|
+
maybePause(): Promise<void>;
|
|
21
|
+
/** Pauses, then starts a new slice. Throws the reason of `signal` when it was aborted meanwhile. */
|
|
22
|
+
pauseNow(): Promise<void>;
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=pause.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pause.d.ts","sourceRoot":"","sources":["../src/pause.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,eAAO,MAAM,KAAK,qBAA8D,CAAC;AAIjF;;;;GAIG;AACH,eAAO,MAAM,SAAS,QAAO,OAAO,CAAC,IAAI,CAA8B,CAAC;AAKxE;;;;GAIG;AACH,qBAAa,UAAU;IAGT,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;IAFpC,OAAO,CAAC,UAAU,CAAqB;gBAEV,MAAM,CAAC,EAAE,WAAW,YAAA;IAEjD,gFAAgF;IAChF,IAAI,GAAG,IAAI,OAAO,CAEjB;IAEK,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAIjC,oGAAoG;IAC9F,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAKhC"}
|
package/dist/pause.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Lets other work on the server run (an answer streaming to another user) before going on. */
|
|
2
|
+
export const pause = () => new Promise((resolve) => setImmediate(resolve));
|
|
3
|
+
let turn = Promise.resolve();
|
|
4
|
+
/**
|
|
5
|
+
* `pause`, taken in turns: each caller waits for the pause before it, so one slice of work runs in
|
|
6
|
+
* a turn of the event loop. Ten uploads that pause at once then hold the server for one slice
|
|
7
|
+
* between two turns, not ten.
|
|
8
|
+
*/
|
|
9
|
+
export const fairPause = () => (turn = turn.then(pause));
|
|
10
|
+
/** Work done between two pauses of a long loop, in milliseconds: short enough that nobody waits. */
|
|
11
|
+
const SLICE_MS = 12;
|
|
12
|
+
/**
|
|
13
|
+
* Splits a long piece of synchronous work into slices, so that one upload does not hold the whole
|
|
14
|
+
* server: call `maybePause()` now and then (every few thousand items), and it pauses once the
|
|
15
|
+
* current slice has run for about 12 ms. It also stops the work when `signal` is aborted.
|
|
16
|
+
*/
|
|
17
|
+
export class TimeSlicer {
|
|
18
|
+
signal;
|
|
19
|
+
sliceStart = performance.now();
|
|
20
|
+
constructor(signal) {
|
|
21
|
+
this.signal = signal;
|
|
22
|
+
}
|
|
23
|
+
/** Whether the current slice has run its time: `maybePause` would pause now. */
|
|
24
|
+
get due() {
|
|
25
|
+
return performance.now() - this.sliceStart >= SLICE_MS;
|
|
26
|
+
}
|
|
27
|
+
async maybePause() {
|
|
28
|
+
if (this.due)
|
|
29
|
+
await this.pauseNow();
|
|
30
|
+
}
|
|
31
|
+
/** Pauses, then starts a new slice. Throws the reason of `signal` when it was aborted meanwhile. */
|
|
32
|
+
async pauseNow() {
|
|
33
|
+
await fairPause();
|
|
34
|
+
this.signal?.throwIfAborted();
|
|
35
|
+
this.sliceStart = performance.now();
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
//# sourceMappingURL=pause.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"pause.js","sourceRoot":"","sources":["../src/pause.ts"],"names":[],"mappings":"AAAA,+FAA+F;AAC/F,MAAM,CAAC,MAAM,KAAK,GAAG,GAAG,EAAE,CAAC,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,EAAE,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC;AAEjF,IAAI,IAAI,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;AAE5C;;;;GAIG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,GAAkB,EAAE,CAAC,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC;AAExE,oGAAoG;AACpG,MAAM,QAAQ,GAAG,EAAE,CAAC;AAEpB;;;;GAIG;AACH,MAAM,OAAO,UAAU;IAGQ;IAFrB,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IAEvC,YAA6B,MAAoB;QAApB,WAAM,GAAN,MAAM,CAAc;IAAG,CAAC;IAErD,gFAAgF;IAChF,IAAI,GAAG;QACL,OAAO,WAAW,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,UAAU,IAAI,QAAQ,CAAC;IACzD,CAAC;IAED,KAAK,CAAC,UAAU;QACd,IAAI,IAAI,CAAC,GAAG;YAAE,MAAM,IAAI,CAAC,QAAQ,EAAE,CAAC;IACtC,CAAC;IAED,oGAAoG;IACpG,KAAK,CAAC,QAAQ;QACZ,MAAM,SAAS,EAAE,CAAC;QAClB,IAAI,CAAC,MAAM,EAAE,cAAc,EAAE,CAAC;QAC9B,IAAI,CAAC,UAAU,GAAG,WAAW,CAAC,GAAG,EAAE,CAAC;IACtC,CAAC;CACF"}
|
package/dist/pdf-pages.d.ts
CHANGED
|
@@ -9,6 +9,31 @@ export type PageCut = {
|
|
|
9
9
|
/** How many pages the original has. */
|
|
10
10
|
pageCount: number;
|
|
11
11
|
};
|
|
12
|
+
/**
|
|
13
|
+
* Objects parsed between two pauses that let other work on the server run, when the parse cannot
|
|
14
|
+
* be paused by time (see `loadPdf`). A count is a poor measure: 500 objects of large arrays took
|
|
15
|
+
* 100 to 180 ms.
|
|
16
|
+
*/
|
|
17
|
+
export declare const OBJECTS_PER_TICK = 500;
|
|
18
|
+
/**
|
|
19
|
+
* The `parseSpeed` for pdf-lib: `OBJECTS_PER_TICK`, or more for a file that declares so many
|
|
20
|
+
* objects that pausing that often would add seconds of waiting (300 pauses of 15 ms for 150,000).
|
|
21
|
+
*/
|
|
22
|
+
export declare function objectsPerTick(bytes: Uint8Array): number;
|
|
23
|
+
/**
|
|
24
|
+
* Reads a PDF into objects with pdf-lib, which cannot be stopped once it has started, and pauses
|
|
25
|
+
* after every 12 to 40 ms of work so that other requests get a turn. pdf-lib itself pauses by a
|
|
26
|
+
* count of objects, and objects differ in cost a hundred times: a count of 500 held the server for
|
|
27
|
+
* 100 to 180 ms on a file of large arrays, and a file of 150,000 objects, parsed 1,500 at a time,
|
|
28
|
+
* for 0.2 to 0.55 s. What pdf-lib reads in one step still holds the server for as long as it
|
|
29
|
+
* takes, and grows with the file: one object (about 0.15 s for each MB of an array of numbers,
|
|
30
|
+
* about 0.03 s for each MB of a stream whose length the file does not give directly), and a
|
|
31
|
+
* cross-reference table written as text (0.15 s for 150,000 objects).
|
|
32
|
+
*
|
|
33
|
+
* The file is read with an empty password, which opens the many PDFs that are encrypted only to
|
|
34
|
+
* restrict printing or copying. Throws what pdf-lib throws.
|
|
35
|
+
*/
|
|
36
|
+
export declare function loadPdf(library: PdfLibrary, bytes: Uint8Array): Promise<import("@cantoo/pdf-lib").PDFDocument>;
|
|
12
37
|
/** Bytes as a string of the same length: each byte becomes the character with that code. */
|
|
13
38
|
export declare function latin1(bytes: Uint8Array): string;
|
|
14
39
|
export declare function loadPdfLibrary(): Promise<PdfLibrary>;
|
|
@@ -28,8 +53,13 @@ export declare function declaredObjectCount(bytes: Uint8Array): number | undefin
|
|
|
28
53
|
* hold; undefined when the file can be read.
|
|
29
54
|
*/
|
|
30
55
|
export declare function tooManyObjects(original: Uint8Array, most?: number): number | undefined;
|
|
31
|
-
/**
|
|
32
|
-
|
|
56
|
+
/**
|
|
57
|
+
* A PDF name as the characters it stands for, so that "#20" and a space are the same name.
|
|
58
|
+
* Undefined for a name that still changes after `NAME_DECODINGS` decodings: only a file built to
|
|
59
|
+
* hold the server writes one ("#2323...2341" loses one level a decoding, and decoding it until
|
|
60
|
+
* nothing changed took 20 s for 400,000 characters). Callers treat it as a name they cannot read.
|
|
61
|
+
*/
|
|
62
|
+
export declare function canonicalName(raw: string): string | undefined;
|
|
33
63
|
/**
|
|
34
64
|
* Cuts pages `from` to `to` (1-based, inclusive) out of a PDF. When the cut is larger than
|
|
35
65
|
* `maxBytes`, pages are left off the end until it fits; `to` in the result says where it stopped.
|
package/dist/pdf-pages.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"pdf-pages.d.ts","sourceRoot":"","sources":["../src/pdf-pages.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,UAAU,EAAW,SAAS,
|
|
1
|
+
{"version":3,"file":"pdf-pages.d.ts","sourceRoot":"","sources":["../src/pdf-pages.ts"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,UAAU,EAAW,SAAS,EAAiD,MAAM,iBAAiB,CAAC;AAIrH,KAAK,UAAU,GAAG,cAAc,iBAAiB,CAAC,CAAC;AAEnD,MAAM,MAAM,OAAO,GAAG;IACpB,uDAAuD;IACvD,KAAK,EAAE,UAAU,CAAC;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,8FAA8F;IAC9F,EAAE,EAAE,MAAM,CAAC;IACX,uCAAuC;IACvC,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,gBAAgB,MAAM,CAAC;AAKpC;;;GAGG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAGxD;AA4HD;;;;;;;;;;;;GAYG;AACH,wBAAsB,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,iBAAiB,EAAE,WAAW,CAAC,CAWpH;AAYD,4FAA4F;AAC5F,wBAAgB,MAAM,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,CAEhD;AAED,wBAAsB,cAAc,IAAI,OAAO,CAAC,UAAU,CAAC,CAM1D;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,SAAS,GAAG,SAAS,EAAE,QAAQ,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAY3I;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,UAAU,GAAG,MAAM,GAAG,SAAS,CAezE;AAED;;;;GAIG;AACH,wBAAgB,cAAc,CAAC,QAAQ,EAAE,UAAU,EAAE,IAAI,SAAc,GAAG,MAAM,GAAG,SAAS,CAM3F;AAQD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAS7D;AA0OD;;;;;;;;;GASG;AACH,wBAAsB,WAAW,CAAC,QAAQ,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,aAAa,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAiC5I"}
|
package/dist/pdf-pages.js
CHANGED
|
@@ -5,13 +5,176 @@
|
|
|
5
5
|
* Copying pages the way a PDF library offers it is not enough. A link to another page takes that
|
|
6
6
|
* page's content along, and a resource dictionary that pages share takes along every image it
|
|
7
7
|
* lists: the contents page of a report came out at 89% of its file. So, before copying:
|
|
8
|
-
* - every page that is not wanted is
|
|
8
|
+
* - every page that is not wanted is set to null, so a reference to it costs nothing;
|
|
9
9
|
* - a wanted page gets its own resource dictionary, without the images it does not paint.
|
|
10
10
|
*/
|
|
11
11
|
import { getHeapStatistics } from "node:v8";
|
|
12
|
+
import { TimeSlicer } from "./pause.js";
|
|
12
13
|
import { formatBytes } from "./plan.js";
|
|
13
|
-
/**
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Objects parsed between two pauses that let other work on the server run, when the parse cannot
|
|
16
|
+
* be paused by time (see `loadPdf`). A count is a poor measure: 500 objects of large arrays took
|
|
17
|
+
* 100 to 180 ms.
|
|
18
|
+
*/
|
|
19
|
+
export const OBJECTS_PER_TICK = 500;
|
|
20
|
+
/** Pauses while one file is parsed, at most. Each is a timer: about 15 ms on Windows, 1 ms elsewhere. */
|
|
21
|
+
const MOST_TICKS = 100;
|
|
22
|
+
const MOST_OBJECTS_PER_TICK = 4_000;
|
|
23
|
+
/**
|
|
24
|
+
* The `parseSpeed` for pdf-lib: `OBJECTS_PER_TICK`, or more for a file that declares so many
|
|
25
|
+
* objects that pausing that often would add seconds of waiting (300 pauses of 15 ms for 150,000).
|
|
26
|
+
*/
|
|
27
|
+
export function objectsPerTick(bytes) {
|
|
28
|
+
const objects = declaredObjectCount(bytes) ?? 0;
|
|
29
|
+
return Math.min(MOST_OBJECTS_PER_TICK, Math.max(OBJECTS_PER_TICK, Math.ceil(objects / MOST_TICKS)));
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Work between two pauses of a parse, at least. A slice also runs twice as long as a pause took,
|
|
33
|
+
* up to `MOST_PARSE_SLICE_MS`: a pause is a timer, which waits about 15 ms on Windows and 1 ms
|
|
34
|
+
* elsewhere, and waiting should not take most of the parse.
|
|
35
|
+
*/
|
|
36
|
+
const PARSE_SLICE_MS = 12;
|
|
37
|
+
const MOST_PARSE_SLICE_MS = 40;
|
|
38
|
+
/** The files `loadPdf` is reading, each with how many reads of it are running. */
|
|
39
|
+
const timedFiles = new WeakMap();
|
|
40
|
+
/** The documents (their contexts) that `copyPages` saves. */
|
|
41
|
+
const timedSaves = new WeakSet();
|
|
42
|
+
/** The factories of pdf-lib changed here, by class: one class for each copy of pdf-lib loaded. */
|
|
43
|
+
const changedFactories = new WeakMap();
|
|
44
|
+
/**
|
|
45
|
+
* pdf-lib asks after each object it parses or writes whether to pause, and pauses with a timer
|
|
46
|
+
* when told so. This answers by time: once a slice of work has run its length. The time of the
|
|
47
|
+
* pauses is not counted.
|
|
48
|
+
*/
|
|
49
|
+
function pauseByTime() {
|
|
50
|
+
let sliceStart = performance.now();
|
|
51
|
+
let pausedAt;
|
|
52
|
+
/** The shortest pause seen, with the one object parsed after it. */
|
|
53
|
+
let pauseMs = 0;
|
|
54
|
+
return () => {
|
|
55
|
+
const now = performance.now();
|
|
56
|
+
if (pausedAt !== undefined) {
|
|
57
|
+
pauseMs = pauseMs === 0 ? now - pausedAt : Math.min(pauseMs, now - pausedAt);
|
|
58
|
+
pausedAt = undefined;
|
|
59
|
+
sliceStart = now;
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
if (now - sliceStart < Math.min(MOST_PARSE_SLICE_MS, Math.max(PARSE_SLICE_MS, 2 * pauseMs)))
|
|
63
|
+
return false;
|
|
64
|
+
pausedAt = now;
|
|
65
|
+
return true;
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
/** Makes a parser or a writer of pdf-lib pause by time. */
|
|
69
|
+
function pauseInTime(made) {
|
|
70
|
+
const pausing = made;
|
|
71
|
+
if (typeof pausing?.shouldWaitForTick === "function")
|
|
72
|
+
pausing.shouldWaitForTick = pauseByTime();
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Has `change` look at what `owner[name]`, a static factory of one of pdf-lib's classes, creates,
|
|
76
|
+
* with the first argument it was given: once for each class. Any other use of pdf-lib in the
|
|
77
|
+
* process is left as it was. A version of pdf-lib built otherwise is left as it is: its parse and
|
|
78
|
+
* its writer pause by the count they are given.
|
|
79
|
+
*/
|
|
80
|
+
function changeFactory(owner, name, change) {
|
|
81
|
+
if (typeof owner !== "function")
|
|
82
|
+
return;
|
|
83
|
+
const factories = owner;
|
|
84
|
+
const create = factories[name];
|
|
85
|
+
const done = changedFactories.get(owner) ?? new Set();
|
|
86
|
+
if (typeof create !== "function" || done.has(name))
|
|
87
|
+
return;
|
|
88
|
+
try {
|
|
89
|
+
factories[name] = (first, ...rest) => {
|
|
90
|
+
const made = create.call(owner, first, ...rest);
|
|
91
|
+
change(first, made);
|
|
92
|
+
return made;
|
|
93
|
+
};
|
|
94
|
+
done.add(name);
|
|
95
|
+
changedFactories.set(owner, done);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// A class that cannot be changed.
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
/** Makes pdf-lib's parsers of the files in `timedFiles` pause by time. */
|
|
102
|
+
function timeParsers(library) {
|
|
103
|
+
const parsers = library.PDFParser;
|
|
104
|
+
changeFactory(parsers, "forBytesWithOptions", (bytes, parser) => {
|
|
105
|
+
if (timedFiles.has(bytes))
|
|
106
|
+
pauseInTime(parser);
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Makes pdf-lib's writers of the documents in `timedSaves` pause by time. Left to itself, a writer
|
|
111
|
+
* of a cut never paused: it counts objects, and the objects it packs into streams 50 at a time
|
|
112
|
+
* make the count miss every multiple of 50 it pauses at.
|
|
113
|
+
*
|
|
114
|
+
* The writer also adds each object to its cross-reference stream by searching all the entries
|
|
115
|
+
* added so far for where it goes, though the objects come in order: the time grows with the square
|
|
116
|
+
* of their count, 0.5 s in one block for 20,000 objects. For these documents an entry that goes
|
|
117
|
+
* after the last one is added at the end at once, which gives the same entries in the same order.
|
|
118
|
+
*/
|
|
119
|
+
function timeWriters(library) {
|
|
120
|
+
const classes = library;
|
|
121
|
+
for (const writers of [classes.PDFWriter, classes.PDFStreamWriter]) {
|
|
122
|
+
changeFactory(writers, "forContext", (context, writer) => {
|
|
123
|
+
if (timedSaves.has(context))
|
|
124
|
+
pauseInTime(writer);
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
// The writer makes its stream with a dictionary of the document it writes.
|
|
128
|
+
changeFactory(classes.PDFCrossRefStream, "create", (dictionary, stream) => {
|
|
129
|
+
const context = dictionary?.context;
|
|
130
|
+
if (typeof context === "object" && context !== null && timedSaves.has(context))
|
|
131
|
+
appendInOrder(stream);
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
/** Adds an entry that goes after the last one to the end of `stream` at once. Entries are kept by object number. */
|
|
135
|
+
function appendInOrder(stream) {
|
|
136
|
+
const references = stream;
|
|
137
|
+
const append = references?.appendEntry;
|
|
138
|
+
if (!references || typeof append !== "function" || !Array.isArray(references.entries))
|
|
139
|
+
return;
|
|
140
|
+
references.appendEntry = (entry) => {
|
|
141
|
+
const entries = references.entries;
|
|
142
|
+
const last = entries.at(-1)?.ref?.objectNumber;
|
|
143
|
+
const number = entry?.ref?.objectNumber;
|
|
144
|
+
if (typeof last === "number" && typeof number === "number" && last <= number)
|
|
145
|
+
entries.push(entry);
|
|
146
|
+
else
|
|
147
|
+
append.call(references, entry);
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
/**
|
|
151
|
+
* Reads a PDF into objects with pdf-lib, which cannot be stopped once it has started, and pauses
|
|
152
|
+
* after every 12 to 40 ms of work so that other requests get a turn. pdf-lib itself pauses by a
|
|
153
|
+
* count of objects, and objects differ in cost a hundred times: a count of 500 held the server for
|
|
154
|
+
* 100 to 180 ms on a file of large arrays, and a file of 150,000 objects, parsed 1,500 at a time,
|
|
155
|
+
* for 0.2 to 0.55 s. What pdf-lib reads in one step still holds the server for as long as it
|
|
156
|
+
* takes, and grows with the file: one object (about 0.15 s for each MB of an array of numbers,
|
|
157
|
+
* about 0.03 s for each MB of a stream whose length the file does not give directly), and a
|
|
158
|
+
* cross-reference table written as text (0.15 s for 150,000 objects).
|
|
159
|
+
*
|
|
160
|
+
* The file is read with an empty password, which opens the many PDFs that are encrypted only to
|
|
161
|
+
* restrict printing or copying. Throws what pdf-lib throws.
|
|
162
|
+
*/
|
|
163
|
+
export async function loadPdf(library, bytes) {
|
|
164
|
+
timeParsers(library);
|
|
165
|
+
timedFiles.set(bytes, (timedFiles.get(bytes) ?? 0) + 1);
|
|
166
|
+
try {
|
|
167
|
+
// parseSpeed pauses the parse by count, when it could not be timed.
|
|
168
|
+
return await library.PDFDocument.load(bytes, { updateMetadata: false, parseSpeed: objectsPerTick(bytes), password: "" });
|
|
169
|
+
}
|
|
170
|
+
finally {
|
|
171
|
+
const reads = (timedFiles.get(bytes) ?? 1) - 1;
|
|
172
|
+
if (reads > 0)
|
|
173
|
+
timedFiles.set(bytes, reads);
|
|
174
|
+
else
|
|
175
|
+
timedFiles.delete(bytes);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
15
178
|
/** Memory one parsed object takes, measured on files of 300,000 objects (1.0 to 1.6 KB). */
|
|
16
179
|
const BYTES_PER_OBJECT = 1_700;
|
|
17
180
|
/** At 13 microseconds an object, a file past this takes over 13 seconds to parse. */
|
|
@@ -88,16 +251,28 @@ export function tooManyObjects(original, most = MAX_OBJECTS) {
|
|
|
88
251
|
const free = heap.heap_size_limit - heap.used_heap_size;
|
|
89
252
|
return objects > most || objects * BYTES_PER_OBJECT > free * 0.6 ? objects : undefined;
|
|
90
253
|
}
|
|
91
|
-
/**
|
|
254
|
+
/**
|
|
255
|
+
* Decodings that may still change a name. A library may keep an escape it did not decode as
|
|
256
|
+
* literal characters, so a name is decoded again; no writer escapes a name more deeply than that.
|
|
257
|
+
*/
|
|
258
|
+
const NAME_DECODINGS = 3;
|
|
259
|
+
/**
|
|
260
|
+
* A PDF name as the characters it stands for, so that "#20" and a space are the same name.
|
|
261
|
+
* Undefined for a name that still changes after `NAME_DECODINGS` decodings: only a file built to
|
|
262
|
+
* hold the server writes one ("#2323...2341" loses one level a decoding, and decoding it until
|
|
263
|
+
* nothing changed took 20 s for 400,000 characters). Callers treat it as a name they cannot read.
|
|
264
|
+
*/
|
|
92
265
|
export function canonicalName(raw) {
|
|
93
266
|
let name = raw;
|
|
94
|
-
|
|
95
|
-
|
|
267
|
+
for (let decoding = 0; decoding <= NAME_DECODINGS; decoding++) {
|
|
268
|
+
if (!name.includes("#"))
|
|
269
|
+
return name;
|
|
96
270
|
const next = name.replace(/#([0-9a-fA-F]{2})/g, (_match, hex) => String.fromCharCode(Number.parseInt(hex, 16)));
|
|
97
271
|
if (next === name)
|
|
98
272
|
return name;
|
|
99
273
|
name = next;
|
|
100
274
|
}
|
|
275
|
+
return undefined;
|
|
101
276
|
}
|
|
102
277
|
const REGULAR_CHARACTER = "[^\\x00\\t\\n\\f\\r /\\[\\]<>(){}%]";
|
|
103
278
|
/** `/Name Do`: the operator that paints an image or a form. */
|
|
@@ -122,14 +297,23 @@ function dropUnusedImages(library, context, page) {
|
|
|
122
297
|
const entries = xobjects.entries();
|
|
123
298
|
if (entries.length < 2)
|
|
124
299
|
return;
|
|
125
|
-
const
|
|
300
|
+
const names = entries.map(([name]) => canonicalName(name.asString().slice(1)));
|
|
301
|
+
// A name that cannot be read cannot be matched with what the content paints: keep every image.
|
|
302
|
+
if (names.includes(undefined))
|
|
303
|
+
return;
|
|
304
|
+
const byName = new Map(entries.map(([, value], index) => [names[index], value]));
|
|
126
305
|
let readable = true;
|
|
127
306
|
/** Names found in content that looks them up in this page's dictionary, still to be followed. */
|
|
128
307
|
const found = [];
|
|
129
308
|
const decode = (stream) => decodeContent(library, context, stream, MAX_CONTENT_BYTES);
|
|
130
309
|
const read = (text) => {
|
|
131
|
-
for (const match of text.matchAll(PAINTED))
|
|
132
|
-
|
|
310
|
+
for (const match of text.matchAll(PAINTED)) {
|
|
311
|
+
const name = canonicalName(match[1]);
|
|
312
|
+
if (name === undefined)
|
|
313
|
+
readable = false;
|
|
314
|
+
else
|
|
315
|
+
found.push(name);
|
|
316
|
+
}
|
|
133
317
|
};
|
|
134
318
|
const readStream = (stream) => {
|
|
135
319
|
const text = decode(stream);
|
|
@@ -232,7 +416,7 @@ function dropUnusedImages(library, context, page) {
|
|
|
232
416
|
}
|
|
233
417
|
if (!readable)
|
|
234
418
|
return;
|
|
235
|
-
const kept = entries.filter((
|
|
419
|
+
const kept = entries.filter((_entry, index) => painted.has(names[index]));
|
|
236
420
|
if (kept.length === entries.length)
|
|
237
421
|
return;
|
|
238
422
|
const fewer = context.obj({});
|
|
@@ -269,6 +453,10 @@ async function copyPages(library, source, pages, from, last) {
|
|
|
269
453
|
// One copier for everything, and each page copied through its reference: an annotation's /P then
|
|
270
454
|
// points at the copied page, and the layer settings below name the layers the pages use.
|
|
271
455
|
const copier = PDFObjectCopier.for(context, target.context);
|
|
456
|
+
// Without these, a layer that the file hides would be shown.
|
|
457
|
+
const layers = source.catalog.get(PDFName.of("OCProperties"));
|
|
458
|
+
const roots = wanted.map((page) => page.ref);
|
|
459
|
+
await copyInTurns(library, copier, context, target.context, layers ? [...roots, layers] : roots);
|
|
272
460
|
for (const page of wanted) {
|
|
273
461
|
const reference = copier.copy(page.ref);
|
|
274
462
|
const node = target.context.lookup(reference);
|
|
@@ -276,12 +464,86 @@ async function copyPages(library, source, pages, from, last) {
|
|
|
276
464
|
throw new Error("A page of this PDF is not a page object.");
|
|
277
465
|
target.addPage(Page.of(node, reference, target));
|
|
278
466
|
}
|
|
279
|
-
// Without these, a layer that the file hides would be shown.
|
|
280
|
-
const layers = source.catalog.get(PDFName.of("OCProperties"));
|
|
281
467
|
if (layers)
|
|
282
468
|
target.catalog.set(PDFName.of("OCProperties"), copier.copy(layers));
|
|
469
|
+
timeWriters(library);
|
|
470
|
+
timedSaves.add(target.context);
|
|
283
471
|
return target.save();
|
|
284
472
|
}
|
|
473
|
+
/**
|
|
474
|
+
* Does the work of `copier.copy(root)` for each of `roots`, with pauses so that other requests get
|
|
475
|
+
* a turn. pdf-lib's copier follows every reference at once: a page that refers to 4,000 large
|
|
476
|
+
* arrays held the server for 0.3 s, and one that refers to 20,000 for 0.9 s. So the objects are
|
|
477
|
+
* first numbered in the order the copier would number them, which keeps the cut the same to the
|
|
478
|
+
* byte, then copied one at a time. `copier.copy(root)` afterwards finds them copied. A copier built
|
|
479
|
+
* otherwise is left to copy everything at once.
|
|
480
|
+
*/
|
|
481
|
+
async function copyInTurns(library, copier, source, target, roots) {
|
|
482
|
+
const copied = copier.traversedObjects;
|
|
483
|
+
if (!(copied instanceof Map))
|
|
484
|
+
return;
|
|
485
|
+
const { PDFArray, PDFDict, PDFName, PDFPageLeaf: Leaf, PDFRef, PDFStream } = library;
|
|
486
|
+
const slicer = new TimeSlicer();
|
|
487
|
+
/** Each object referred to, with its number in the cut, in the order the copier numbers them. */
|
|
488
|
+
const numbered = [];
|
|
489
|
+
const seen = new Set();
|
|
490
|
+
/** What the copier copies next, when it copies `object`: undefined when there is nothing more. */
|
|
491
|
+
const inside = (object) => {
|
|
492
|
+
if (object instanceof PDFRef) {
|
|
493
|
+
if (copied.has(object))
|
|
494
|
+
return undefined;
|
|
495
|
+
const reference = target.nextRef();
|
|
496
|
+
copied.set(object, reference);
|
|
497
|
+
numbered.push([object, reference]);
|
|
498
|
+
const value = source.lookup(object);
|
|
499
|
+
return value ? [value] : undefined;
|
|
500
|
+
}
|
|
501
|
+
if (object instanceof Leaf) {
|
|
502
|
+
// As the copier copies a page: with what it inherits from the page tree, without its parent.
|
|
503
|
+
const page = object.clone();
|
|
504
|
+
for (const name of Leaf.InheritableEntries) {
|
|
505
|
+
const key = PDFName.of(name);
|
|
506
|
+
const value = page.getInheritableAttribute(key);
|
|
507
|
+
if (!page.get(key) && value)
|
|
508
|
+
page.set(key, value);
|
|
509
|
+
}
|
|
510
|
+
page.delete(PDFName.of("Parent"));
|
|
511
|
+
return page.entries().map(([, value]) => value);
|
|
512
|
+
}
|
|
513
|
+
if (!(object instanceof PDFDict || object instanceof PDFArray || object instanceof PDFStream) || seen.has(object))
|
|
514
|
+
return undefined;
|
|
515
|
+
seen.add(object);
|
|
516
|
+
if (object instanceof PDFArray)
|
|
517
|
+
return object.asArray();
|
|
518
|
+
return (object instanceof PDFStream ? object.dict : object).entries().map(([, value]) => value);
|
|
519
|
+
};
|
|
520
|
+
// Depth first, each object before what it refers to, as the copier goes.
|
|
521
|
+
const stack = [];
|
|
522
|
+
const enter = (object) => {
|
|
523
|
+
const items = inside(object);
|
|
524
|
+
if (items !== undefined && items.length > 0)
|
|
525
|
+
stack.push({ items, at: 0 });
|
|
526
|
+
};
|
|
527
|
+
let steps = 0;
|
|
528
|
+
for (const root of roots) {
|
|
529
|
+
enter(root);
|
|
530
|
+
while (stack.length > 0) {
|
|
531
|
+
const top = stack[stack.length - 1];
|
|
532
|
+
if (top.at === top.items.length)
|
|
533
|
+
stack.pop();
|
|
534
|
+
else
|
|
535
|
+
enter(top.items[top.at++]);
|
|
536
|
+
if (++steps % 1_000 === 0)
|
|
537
|
+
await slicer.maybePause();
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
for (const [original, reference] of numbered) {
|
|
541
|
+
const value = source.lookup(original);
|
|
542
|
+
if (value)
|
|
543
|
+
target.assign(reference, copier.copy(value));
|
|
544
|
+
await slicer.maybePause();
|
|
545
|
+
}
|
|
546
|
+
}
|
|
285
547
|
/**
|
|
286
548
|
* Cuts pages `from` to `to` (1-based, inclusive) out of a PDF. When the cut is larger than
|
|
287
549
|
* `maxBytes`, pages are left off the end until it fits; `to` in the result says where it stopped.
|
|
@@ -301,8 +563,7 @@ export async function cutPdfPages(original, from, to, maxBytes, expectedPages) {
|
|
|
301
563
|
let source;
|
|
302
564
|
let pages;
|
|
303
565
|
try {
|
|
304
|
-
|
|
305
|
-
source = await library.PDFDocument.load(original, { updateMetadata: false, parseSpeed: OBJECTS_PER_TICK, password: "" });
|
|
566
|
+
source = await loadPdf(library, original);
|
|
306
567
|
pages = source.getPages();
|
|
307
568
|
}
|
|
308
569
|
catch (error) {
|