foldkit-media 0.3.0 → 0.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.
- package/README.md +65 -4
- package/dist/{asset-BLo8VWmd.d.mts → asset.d.ts} +10 -11
- package/dist/asset.d.ts.map +1 -0
- package/dist/asset.js +66 -0
- package/dist/asset.js.map +1 -0
- package/dist/browser/index.d.ts +15 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +69 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/{index.d.mts → upload.d.ts} +5 -16
- package/dist/browser/upload.d.ts.map +1 -0
- package/dist/browser/upload.js +87 -0
- package/dist/browser/upload.js.map +1 -0
- package/dist/cloudflare/{index.d.mts → index.d.ts} +8 -6
- package/dist/cloudflare/index.d.ts.map +1 -0
- package/dist/cloudflare/{index.mjs → index.js} +35 -15
- package/dist/cloudflare/index.js.map +1 -0
- package/dist/describe.d.ts +32 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +30 -0
- package/dist/describe.js.map +1 -0
- package/dist/format.d.ts +12 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/{format-BCRTFU9j.mjs → format.js} +2 -2
- package/dist/format.js.map +1 -0
- package/dist/{icon-BGtxExTN.d.mts → icon.d.ts} +14 -17
- package/dist/icon.d.ts.map +1 -0
- package/dist/{icon-0A2dBtqj.mjs → icon.js} +2 -12
- package/dist/icon.js.map +1 -0
- package/dist/icons/{index.d.mts → index.d.ts} +2 -2
- package/dist/icons/index.d.ts.map +1 -0
- package/dist/icons/{index.mjs → index.js} +2 -2
- package/dist/icons/index.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/layout.d.ts +60 -0
- package/dist/layout.d.ts.map +1 -0
- package/dist/layout.js +72 -0
- package/dist/layout.js.map +1 -0
- package/dist/limits.d.ts +3 -0
- package/dist/limits.d.ts.map +1 -0
- package/dist/{limits-B4hHpyfE.mjs → limits.js} +2 -2
- package/dist/limits.js.map +1 -0
- package/dist/picture.d.ts +88 -0
- package/dist/picture.d.ts.map +1 -0
- package/dist/picture.js +113 -0
- package/dist/picture.js.map +1 -0
- package/dist/placeholder.d.ts +16 -0
- package/dist/placeholder.d.ts.map +1 -0
- package/dist/placeholder.js +38 -0
- package/dist/placeholder.js.map +1 -0
- package/dist/{provider-CB0nqu0m.d.mts → provider.d.ts} +16 -19
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +93 -0
- package/dist/provider.js.map +1 -0
- package/dist/server/admission.d.ts +31 -0
- package/dist/server/admission.d.ts.map +1 -0
- package/dist/server/admission.js +41 -0
- package/dist/server/admission.js.map +1 -0
- package/dist/server/api.d.ts +14 -0
- package/dist/server/api.d.ts.map +1 -0
- package/dist/server/api.js +21 -0
- package/dist/server/api.js.map +1 -0
- package/dist/server/diagnostics.d.ts +53 -0
- package/dist/server/diagnostics.d.ts.map +1 -0
- package/dist/server/diagnostics.js +50 -0
- package/dist/server/diagnostics.js.map +1 -0
- package/dist/server/errors.d.ts +24 -0
- package/dist/server/errors.d.ts.map +1 -0
- package/dist/{errors-BhEgXJ4m.mjs → server/errors.js} +2 -2
- package/dist/server/errors.js.map +1 -0
- package/dist/server/facts.d.ts +36 -0
- package/dist/server/facts.d.ts.map +1 -0
- package/dist/server/facts.js +126 -0
- package/dist/server/facts.js.map +1 -0
- package/dist/server/fetch.d.ts +29 -0
- package/dist/server/fetch.d.ts.map +1 -0
- package/dist/server/fetch.js +32 -0
- package/dist/server/fetch.js.map +1 -0
- package/dist/server/handlers.d.ts +48 -0
- package/dist/server/handlers.d.ts.map +1 -0
- package/dist/server/handlers.js +151 -0
- package/dist/server/handlers.js.map +1 -0
- package/dist/server/headers.d.ts +47 -0
- package/dist/server/headers.d.ts.map +1 -0
- package/dist/server/headers.js +134 -0
- package/dist/server/headers.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/materialize.d.ts +36 -0
- package/dist/server/materialize.d.ts.map +1 -0
- package/dist/server/materialize.js +62 -0
- package/dist/server/materialize.js.map +1 -0
- package/dist/{services-BZoK2VOY.d.mts → server/services.d.ts} +12 -12
- package/dist/server/services.d.ts.map +1 -0
- package/dist/{services-7B4hsQM7.mjs → server/services.js} +3 -3
- package/dist/server/services.js.map +1 -0
- package/dist/server/stores.d.ts +27 -0
- package/dist/server/stores.d.ts.map +1 -0
- package/dist/server/stores.js +62 -0
- package/dist/server/stores.js.map +1 -0
- package/dist/server/upload.d.ts +113 -0
- package/dist/server/upload.d.ts.map +1 -0
- package/dist/server/upload.js +185 -0
- package/dist/server/upload.js.map +1 -0
- package/dist/sharp/{index.d.mts → index.d.ts} +3 -3
- package/dist/sharp/index.d.ts.map +1 -0
- package/dist/sharp/{index.mjs → index.js} +11 -9
- package/dist/sharp/index.js.map +1 -0
- package/dist/unpic/{index.d.mts → index.d.ts} +5 -4
- package/dist/unpic/index.d.ts.map +1 -0
- package/dist/unpic/{index.mjs → index.js} +3 -3
- package/dist/unpic/index.js.map +1 -0
- package/dist/{variant-B-vyMmFB.d.mts → variant.d.ts} +15 -18
- package/dist/variant.d.ts.map +1 -0
- package/dist/variant.js +75 -0
- package/dist/variant.js.map +1 -0
- package/dist/vite/{index.d.mts → icons.d.ts} +1 -19
- package/dist/vite/icons.d.ts.map +1 -0
- package/dist/vite/icons.js +178 -0
- package/dist/vite/icons.js.map +1 -0
- package/dist/vite/images.d.ts +20 -0
- package/dist/vite/images.d.ts.map +1 -0
- package/dist/vite/images.js +167 -0
- package/dist/vite/images.js.map +1 -0
- package/dist/vite/index.d.ts +3 -0
- package/dist/vite/index.js +3 -0
- package/dist/widths.d.ts +22 -0
- package/dist/widths.d.ts.map +1 -0
- package/dist/{widths-qp3jshiF.mjs → widths.js} +2 -8
- package/dist/widths.js.map +1 -0
- package/package.json +22 -21
- package/dist/asset-BLo8VWmd.d.mts.map +0 -1
- package/dist/browser/index.d.mts.map +0 -1
- package/dist/browser/index.mjs +0 -150
- package/dist/browser/index.mjs.map +0 -1
- package/dist/cloudflare/index.d.mts.map +0 -1
- package/dist/cloudflare/index.mjs.map +0 -1
- package/dist/describe-BOgc0xbR.d.mts +0 -52
- package/dist/describe-BOgc0xbR.d.mts.map +0 -1
- package/dist/describe-C6sWA_8p.mjs +0 -171
- package/dist/describe-C6sWA_8p.mjs.map +0 -1
- package/dist/errors-BhEgXJ4m.mjs.map +0 -1
- package/dist/format-BCRTFU9j.mjs.map +0 -1
- package/dist/icon-0A2dBtqj.mjs.map +0 -1
- package/dist/icon-BGtxExTN.d.mts.map +0 -1
- package/dist/icons/index.d.mts.map +0 -1
- package/dist/icons/index.mjs.map +0 -1
- package/dist/index.d.mts +0 -157
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -322
- package/dist/index.mjs.map +0 -1
- package/dist/limits-B4hHpyfE.mjs.map +0 -1
- package/dist/provider-CB0nqu0m.d.mts.map +0 -1
- package/dist/rolldown-runtime-BJohB4LM.mjs +0 -13
- package/dist/server/index.d.mts +0 -170
- package/dist/server/index.d.mts.map +0 -1
- package/dist/server/index.mjs +0 -231
- package/dist/server/index.mjs.map +0 -1
- package/dist/services-7B4hsQM7.mjs.map +0 -1
- package/dist/services-BZoK2VOY.d.mts.map +0 -1
- package/dist/sharp/index.d.mts.map +0 -1
- package/dist/sharp/index.mjs.map +0 -1
- package/dist/stores-CxraN3kt.mjs +0 -490
- package/dist/stores-CxraN3kt.mjs.map +0 -1
- package/dist/unpic/index.d.mts.map +0 -1
- package/dist/unpic/index.mjs.map +0 -1
- package/dist/upload-lVLMRJoC.d.mts +0 -160
- package/dist/upload-lVLMRJoC.d.mts.map +0 -1
- package/dist/variant-B-vyMmFB.d.mts.map +0 -1
- package/dist/vite/index.d.mts.map +0 -1
- package/dist/vite/index.mjs +0 -328
- package/dist/vite/index.mjs.map +0 -1
- package/dist/widths-qp3jshiF.mjs.map +0 -1
- package/dist/widths-upkgLdek.d.mts +0 -36
- package/dist/widths-upkgLdek.d.mts.map +0 -1
|
@@ -1,160 +0,0 @@
|
|
|
1
|
-
import { n as HashedAsset, r as ImageAsset } from "./asset-BLo8VWmd.mjs";
|
|
2
|
-
import { n as Inspector } from "./describe-BOgc0xbR.mjs";
|
|
3
|
-
import { Context, Duration, Effect, Layer, Option, Schema } from "effect";
|
|
4
|
-
import { HttpApi, HttpApiEndpoint, HttpApiGroup } from "effect/http-api";
|
|
5
|
-
import { HttpServerRequest } from "effect/http";
|
|
6
|
-
import { KeyValueStore, RateLimiter } from "effect/persistence";
|
|
7
|
-
declare const RateLimited_base: Schema.Class<RateLimited, Schema.TaggedStruct<"RateLimited", {
|
|
8
|
-
readonly retryAfterSeconds: Schema.Number;
|
|
9
|
-
}>, import("effect/Cause").YieldableError>;
|
|
10
|
-
/** The client has made too many variants lately; it may try again after `retryAfterSeconds`. */
|
|
11
|
-
declare class RateLimited extends RateLimited_base {}
|
|
12
|
-
declare const Admission_base: Context.ServiceClass<Admission, "foldkit-media/Admission", {
|
|
13
|
-
readonly admit: (client: string) => Effect.Effect<void, RateLimited>;
|
|
14
|
-
}>;
|
|
15
|
-
/**
|
|
16
|
-
* Whether a client may have a variant made now. Asked only on a miss, after
|
|
17
|
-
* the store and before the original is read: a variant already made costs a
|
|
18
|
-
* read, and only making one costs work. Optional: without it, every miss is
|
|
19
|
-
* admitted.
|
|
20
|
-
*/
|
|
21
|
-
declare class Admission extends Admission_base {}
|
|
22
|
-
/**
|
|
23
|
-
* Admission through Effect's `RateLimiter`, `limit` misses a client per
|
|
24
|
-
* `window`, over the limiter's store (`RateLimiter.layerStoreMemory` for one
|
|
25
|
-
* process, Redis for several). A store that fails admits the request, logged:
|
|
26
|
-
* a limiter that is down should not take the images down with it.
|
|
27
|
-
*/
|
|
28
|
-
declare const admissionRateLimiter: (options: {
|
|
29
|
-
readonly limit: number;
|
|
30
|
-
readonly window: Duration.Input;
|
|
31
|
-
readonly algorithm?: 'fixed-window' | 'token-bucket';
|
|
32
|
-
}) => Layer.Layer<Admission, never, RateLimiter.RateLimiter>;
|
|
33
|
-
declare const FactsUnavailable_base: Schema.Class<FactsUnavailable, Schema.TaggedStruct<"FactsUnavailable", {
|
|
34
|
-
readonly url: Schema.String;
|
|
35
|
-
readonly reason: Schema.String;
|
|
36
|
-
}>, import("effect/Cause").YieldableError>;
|
|
37
|
-
/** No facts could be read for the image at `url`; `reason` says why, for the build's report. */
|
|
38
|
-
declare class FactsUnavailable extends FactsUnavailable_base {}
|
|
39
|
-
interface FactsOptions {
|
|
40
|
-
/** The hosts an original may be read from, matched exactly: `cdn.example.com`, not a suffix. */
|
|
41
|
-
readonly allow: ReadonlyArray<string>;
|
|
42
|
-
/** The largest original read, in bytes, counted as it streams. */
|
|
43
|
-
readonly maxBytes?: number;
|
|
44
|
-
/** Facts kept by URL and revalidated with the original's `ETag`. */
|
|
45
|
-
readonly cache?: KeyValueStore.KeyValueStore;
|
|
46
|
-
/** How to fetch; the platform's `fetch` by default. */
|
|
47
|
-
readonly fetch?: (request: Request) => Promise<Response>;
|
|
48
|
-
}
|
|
49
|
-
/**
|
|
50
|
-
* The facts of an image a page names only by URL (a rich-text image, a CMS
|
|
51
|
-
* block), so it is drawn with its box and placeholder like any other: its
|
|
52
|
-
* original read from an allowed host and described (`describe`), with the
|
|
53
|
-
* URL as its key. Only `https` on a host in `allow`, at its default port, is read, and every
|
|
54
|
-
* redirect is checked again, so content cannot point the build at an
|
|
55
|
-
* internal address. Kept in `cache`, an unchanged original is asked for
|
|
56
|
-
* with its `ETag` and not read or inspected again.
|
|
57
|
-
*/
|
|
58
|
-
declare const factsOf: (url: string, options: FactsOptions) => Effect.Effect<ImageAsset, FactsUnavailable, Inspector>;
|
|
59
|
-
/**
|
|
60
|
-
* Where an original's facts enter, apart from `MediaApi`, so the variant server needs none of
|
|
61
|
-
* its services: an upload, and the facts of an image named by URL.
|
|
62
|
-
*/
|
|
63
|
-
declare const UploadApi: HttpApi.HttpApi<"foldkit-media-upload", HttpApiGroup.HttpApiGroup<"uploads", HttpApiEndpoint.HttpApiEndpoint<"facts", "GET", "/_media/facts", never, never, never, never, Schema.toCodecJson<import("effect/http-api/HttpApiSchema").NoContent>, never, never, never> | HttpApiEndpoint.HttpApiEndpoint<"upload", "POST", "/_media/upload", never, never, never, never, Schema.toCodecJson<import("effect/http-api/HttpApiSchema").NoContent>, never, never, never>, false>>;
|
|
64
|
-
declare const Uploads_base: Context.ServiceClass<Uploads, "foldkit-media/Uploads", {
|
|
65
|
-
readonly put: (hash: string, bytes: Uint8Array<ArrayBuffer>, facts: ImageAsset) => Effect.Effect<void>;
|
|
66
|
-
}>;
|
|
67
|
-
/**
|
|
68
|
-
* Keeps an uploaded original under its content hash, and the facts the
|
|
69
|
-
* server read from it beside it: the one writer of what `Originals` and
|
|
70
|
-
* `StoredFacts` read. The bytes are kept first, so kept facts mean kept bytes.
|
|
71
|
-
*/
|
|
72
|
-
declare class Uploads extends Uploads_base {}
|
|
73
|
-
declare const StoredFacts_base: Context.ServiceClass<StoredFacts, "foldkit-media/StoredFacts", {
|
|
74
|
-
readonly get: (hash: string) => Effect.Effect<Option.Option<HashedAsset>>;
|
|
75
|
-
}>;
|
|
76
|
-
/**
|
|
77
|
-
* The facts the upload route read from an original, by its hash: what an
|
|
78
|
-
* application stores, rather than facts a client sends back. None for a hash
|
|
79
|
-
* nobody uploaded, or one kept before facts were.
|
|
80
|
-
*/
|
|
81
|
-
declare class StoredFacts extends StoredFacts_base {}
|
|
82
|
-
declare const UploadForbidden_base: Schema.Class<UploadForbidden, Schema.TaggedStruct<"UploadForbidden", {}>, import("effect/Cause").YieldableError>;
|
|
83
|
-
/** The request may not upload. Why stays with the policy: the answer says only no. */
|
|
84
|
-
declare class UploadForbidden extends UploadForbidden_base {}
|
|
85
|
-
declare const UploadUnauthenticated_base: Schema.Class<UploadUnauthenticated, Schema.TaggedStruct<"UploadUnauthenticated", {}>, import("effect/Cause").YieldableError>;
|
|
86
|
-
/**
|
|
87
|
-
* The policy could not tell who is asking (an untrusted origin, a session
|
|
88
|
-
* that ended), so the client should sign in again rather than give up.
|
|
89
|
-
*/
|
|
90
|
-
declare class UploadUnauthenticated extends UploadUnauthenticated_base {}
|
|
91
|
-
/** Which route the policy is asked about: an upload, or the facts of an image named by URL. */
|
|
92
|
-
type UploadRoute = 'Upload' | 'DescribeUrl';
|
|
93
|
-
declare const UploadPolicy_base: Context.ServiceClass<UploadPolicy, "foldkit-media/UploadPolicy", {
|
|
94
|
-
readonly admit: (request: HttpServerRequest.HttpServerRequest, route: UploadRoute) => Effect.Effect<void, UploadForbidden | UploadUnauthenticated>;
|
|
95
|
-
}>;
|
|
96
|
-
/**
|
|
97
|
-
* Who may upload, asked of every request before its body is read, with the
|
|
98
|
-
* route it is for. The route has no default: an application that serves
|
|
99
|
-
* uploads says who may (`foldkit-guard/media` over the session, a secret), so
|
|
100
|
-
* a server is never open to every upload by omission.
|
|
101
|
-
*/
|
|
102
|
-
declare class UploadPolicy extends UploadPolicy_base {}
|
|
103
|
-
interface UploadOptions {
|
|
104
|
-
/** The largest upload read, in bytes; a larger one is a 413, read no further. */
|
|
105
|
-
readonly maxBytes?: number;
|
|
106
|
-
/**
|
|
107
|
-
* How `GET /_media/facts?url=` reads an image named by URL (`factsOf`): the hosts it may
|
|
108
|
-
* fetch from, and a cache. No hosts unless given, so a server names every host it reads.
|
|
109
|
-
*/
|
|
110
|
-
readonly facts?: Omit<FactsOptions, 'allow'> & {
|
|
111
|
-
readonly allow?: ReadonlyArray<string>;
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
/**
|
|
115
|
-
* The upload route's handler. It asks the `UploadPolicy` first; takes only
|
|
116
|
-
* an `image/*` body, which a browser cannot send to another origin without a
|
|
117
|
-
* preflight this route never answers, so a cookie alone cannot upload from
|
|
118
|
-
* another site; reads at most `maxBytes`; and refuses what the `Inspector`
|
|
119
|
-
* cannot read as an image (415). Its answer is the facts, with the hash as
|
|
120
|
-
* the key, `201`.
|
|
121
|
-
*/
|
|
122
|
-
declare const uploadHandlers: (options?: UploadOptions) => Layer.Layer<HttpApiGroup.Service<"foldkit-media-upload", "uploads">, never, Inspector | UploadPolicy | Uploads>;
|
|
123
|
-
/**
|
|
124
|
-
* The upload route as an Effect HTTP application, registered with the
|
|
125
|
-
* `HttpRouter` beside the variant server's, needing `Uploads`, an
|
|
126
|
-
* `Inspector` and the `UploadPolicy`.
|
|
127
|
-
*/
|
|
128
|
-
declare const uploadLayer: (options?: UploadOptions) => Layer.Layer<never, never, import("effect/FileSystem").FileSystem | import("effect/http/Etag").Generator | import("effect/http/HttpPlatform").HttpPlatform | import("effect/http/HttpRouter").HttpRouter | Inspector | import("effect/Path").Path | UploadPolicy | Uploads>;
|
|
129
|
-
/**
|
|
130
|
-
* Policies tried in turn, the first to admit winning: a deployment's secret
|
|
131
|
-
* for scripts beside sessions for editors. A refusal tries the next; when
|
|
132
|
-
* every one refuses, the last refusal is the answer. Each is built once, with
|
|
133
|
-
* the combined layer, and closes with it.
|
|
134
|
-
*/
|
|
135
|
-
declare const uploadPolicyAny: <E, R>(...policies: readonly [Layer.Layer<UploadPolicy, E, R>, Layer.Layer<UploadPolicy, E, R>, ...ReadonlyArray<Layer.Layer<UploadPolicy, E, R>>]) => Layer.Layer<UploadPolicy, E, R>;
|
|
136
|
-
/**
|
|
137
|
-
* Admits a request whose `Authorization` is `Bearer <token>`, and with no
|
|
138
|
-
* token (unset or empty) admits nobody, whatever it sends. The two are
|
|
139
|
-
* compared by digest, every byte, so the time taken says nothing of the
|
|
140
|
-
* token. For a deployment's secret (`wrangler secret put`); who may upload
|
|
141
|
-
* by session is the application's own `UploadPolicy`.
|
|
142
|
-
*/
|
|
143
|
-
declare const uploadPolicyBearer: (token: string | undefined) => Layer.Layer<UploadPolicy>;
|
|
144
|
-
/**
|
|
145
|
-
* Uploads kept in the application's `KeyValueStore`, each under its content
|
|
146
|
-
* hash after `prefix`: the same keys `originalsKeyValueStore` reads, with the
|
|
147
|
-
* same `prefix`. A store that fails is a defect: an upload it dropped is lost.
|
|
148
|
-
*/
|
|
149
|
-
declare const uploadsKeyValueStore: (options?: {
|
|
150
|
-
readonly prefix?: string;
|
|
151
|
-
}) => Layer.Layer<Uploads, never, KeyValueStore.KeyValueStore>;
|
|
152
|
-
/**
|
|
153
|
-
* Upload facts read back from the application's `KeyValueStore`, under the
|
|
154
|
-
* same `prefix` as `uploadsKeyValueStore`. A store that fails is a defect.
|
|
155
|
-
*/
|
|
156
|
-
declare const storedFactsKeyValueStore: (options?: {
|
|
157
|
-
readonly prefix?: string;
|
|
158
|
-
}) => Layer.Layer<StoredFacts, never, KeyValueStore.KeyValueStore>;
|
|
159
|
-
export { factsOf as _, UploadPolicy as a, admissionRateLimiter as b, Uploads as c, uploadLayer as d, uploadPolicyAny as f, FactsUnavailable as g, FactsOptions as h, UploadOptions as i, storedFactsKeyValueStore as l, uploadsKeyValueStore as m, UploadApi as n, UploadRoute as o, uploadPolicyBearer as p, UploadForbidden as r, UploadUnauthenticated as s, StoredFacts as t, uploadHandlers as u, Admission as v, RateLimited as y };
|
|
160
|
-
//# sourceMappingURL=upload-lVLMRJoC.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"upload-lVLMRJoC.d.mts","names":[],"sources":["../src/server/admission.ts","../src/server/facts.ts","../src/server/upload.ts"],"mappings":";;;;;;;;;;cAIa,oBAAoB;;WAcb,QAAC,mBAAmB,OAAO,aAAa;;;;;;;;cAF/C,kBAAkB;;;;;;;cAWlB,uBAAoB;WACtB;WACA,QAAQ,SAAS;WACjB;MACP,MAAM,MAAM,kBAAkB,YAAY;;;;;;cCxBjC,yBAAyB;UAiBrB;;WAEN,OAAO;;WAEP;;WAEA,QAAQ,cAAc;;WAEtB,SAAS,SAAS,YAAY,QAAQ;;;;;;;;;;;cAYpC,UAAO,aACP,SACF,iBACR,OAAO,OAAO,YAAY,kBAAkB;;;;;cCzBlC,WAAS,QAAA,gCAAA,aAAA,wBAAA,gBAAA,6EA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;;WAEA,QAAQ,OAAO,MAAM;;WAErB;;;;;;cAYE,QAAK;WAEL,SAASA;WACT,UAAU,cAAc;WACxB,YAAY;WACZ;MAEV;;cA2DU,UAAU"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":["Widths.Widths"],"sources":["../../src/vite/images.ts","../../src/vite/index.ts"],"mappings":";;UA8BiB;;WAEN,SAASA;;WAET,UAAU,cAAc;;WAExB,WAAW;;WAEX;;;;;;;qBAoCE,SAAM,UAAa,kBAAqB;iBCtDpC;;WAEN,UAAU;;WAEV,UAAU,SAAS;;WAEnB;;;qBAWE,aAAU;;;;;;;qBAwDV,QAAK,UAAa,iBAAoB"}
|
package/dist/vite/index.mjs
DELETED
|
@@ -1,328 +0,0 @@
|
|
|
1
|
-
import { r as standard } from "../widths-qp3jshiF.mjs";
|
|
2
|
-
import { a as ImageAsset, n as describe } from "../describe-C6sWA_8p.mjs";
|
|
3
|
-
import { IconifySet, fromIconify, namesOf, parse } from "../icons/index.mjs";
|
|
4
|
-
import { n as Transformer } from "../services-7B4hsQM7.mjs";
|
|
5
|
-
import { createRequire } from "node:module";
|
|
6
|
-
import { Cause, Exit, Layer, ManagedRuntime, Option, Schema, Semaphore } from "effect";
|
|
7
|
-
import { availableParallelism } from "node:os";
|
|
8
|
-
import { readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
9
|
-
import { extname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
10
|
-
import { createHash, randomUUID } from "node:crypto";
|
|
11
|
-
import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
|
|
12
|
-
// src/vite/images.ts
|
|
13
|
-
/**
|
|
14
|
-
* Images as imports: `import hero from './hero.jpg?image'` gives `{ asset,
|
|
15
|
-
* provider }`, ready for `Picture.derive` or `foldkit-mixins-ui`'s `Image.view`.
|
|
16
|
-
* The build reads the file's facts once (`describe`, through sharp), writes a
|
|
17
|
-
* file for each ladder width up to the original's own in each format, and
|
|
18
|
-
* names them by content, so a host may keep them for good. The development
|
|
19
|
-
* server makes the same variants when a page asks for them.
|
|
20
|
-
*/
|
|
21
|
-
const QUERY = "image";
|
|
22
|
-
const CACHE_REVISION = "r2";
|
|
23
|
-
const DEV_PREFIX = "/@foldkit-media/image/";
|
|
24
|
-
const DEV_PATH = /^\/@foldkit-media\/image\/([0-9a-f]{64})\/w(\d+)\.(avif|webp|jpeg|png)$/;
|
|
25
|
-
/** The widths a build writes of an original: the ladder's below its own, then its own. */
|
|
26
|
-
const widthsFor = (ladder, width) => [...ladder.values.filter((value) => value < width), width];
|
|
27
|
-
/**
|
|
28
|
-
* Keeps `bytes` at `file` whole or not at all: written beside it, then moved in, so a build
|
|
29
|
-
* stopped halfway leaves no cut-short file that a later build would trust.
|
|
30
|
-
*/
|
|
31
|
-
const keep = async (file, bytes) => {
|
|
32
|
-
const partial = `${file}.${randomUUID()}.partial`;
|
|
33
|
-
await writeFile(partial, bytes);
|
|
34
|
-
await rename(partial, file);
|
|
35
|
-
};
|
|
36
|
-
const run = async (media, effect, what) => {
|
|
37
|
-
const exit = await media.runPromiseExit(effect);
|
|
38
|
-
if (Exit.isSuccess(exit)) return exit.value;
|
|
39
|
-
throw new Error(`foldkit-media/vite: ${what}: ${Cause.pretty(exit.cause)}`);
|
|
40
|
-
};
|
|
41
|
-
/**
|
|
42
|
-
* The plugin: an import with `?image` becomes the image's facts and a
|
|
43
|
-
* provider over its variants. sharp is read on the first such import, so an
|
|
44
|
-
* application that imports none needs no sharp.
|
|
45
|
-
*/
|
|
46
|
-
const images = (options = {}) => {
|
|
47
|
-
const ladder = options.widths ?? standard;
|
|
48
|
-
const sources = options.sources ?? ["avif"];
|
|
49
|
-
const fallback = options.fallback ?? "webp";
|
|
50
|
-
const formats = [.../* @__PURE__ */ new Set([...sources, fallback])];
|
|
51
|
-
const quality = Option.fromNullishOr(options.quality);
|
|
52
|
-
if (Option.isSome(quality) && !(Number.isInteger(quality.value) && quality.value >= 1 && quality.value <= 100)) throw new Error(`foldkit-media/vite: a quality is a whole number from 1 to 100, not ${quality.value}.`);
|
|
53
|
-
let root = process.cwd();
|
|
54
|
-
let cache = join(root, "node_modules", ".vite", "foldkit-media", CACHE_REVISION);
|
|
55
|
-
let serving = false;
|
|
56
|
-
/** The originals the development server has been asked to vary, by content hash. */
|
|
57
|
-
const originals = /* @__PURE__ */ new Map();
|
|
58
|
-
const inspecting = Semaphore.makeUnsafe(availableParallelism());
|
|
59
|
-
let media;
|
|
60
|
-
const mediaOf = () => media ??= import("../sharp/index.mjs").then(({ inspectorSharp, transformerSharp }) => ManagedRuntime.make(Layer.mergeAll(inspectorSharp(), transformerSharp())), (cause) => {
|
|
61
|
-
throw new Error(`foldkit-media/vite: a ?image import needs sharp; add it to the application. (${String(cause)})`);
|
|
62
|
-
});
|
|
63
|
-
const factsOf = async (key, bytes, hash) => {
|
|
64
|
-
const file = join(cache, hash, "asset.json");
|
|
65
|
-
try {
|
|
66
|
-
return Schema.decodeUnknownSync(ImageAsset)({
|
|
67
|
-
...JSON.parse(await readFile(file, "utf8")),
|
|
68
|
-
key
|
|
69
|
-
});
|
|
70
|
-
} catch {
|
|
71
|
-
const asset = await run(await mediaOf(), Semaphore.withPermit(inspecting)(describe(key, bytes)), `${key} could not be read`);
|
|
72
|
-
await mkdir(join(cache, hash), { recursive: true });
|
|
73
|
-
await keep(file, JSON.stringify(Schema.encodeSync(ImageAsset)(asset)));
|
|
74
|
-
return asset;
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
const variantOf = async (key, bytes, hash, width, format) => {
|
|
78
|
-
const name = `w${width}${Option.match(quality, {
|
|
79
|
-
onNone: () => "",
|
|
80
|
-
onSome: (q) => `q${q}`
|
|
81
|
-
})}.${format}`;
|
|
82
|
-
const file = join(cache, hash, name);
|
|
83
|
-
try {
|
|
84
|
-
return new Uint8Array(await readFile(file));
|
|
85
|
-
} catch {
|
|
86
|
-
const variant = {
|
|
87
|
-
width,
|
|
88
|
-
format,
|
|
89
|
-
quality
|
|
90
|
-
};
|
|
91
|
-
const made = await run(await mediaOf(), Transformer.use((transformer) => transformer.transform({
|
|
92
|
-
body: new Blob([bytes]).stream(),
|
|
93
|
-
size: bytes.byteLength
|
|
94
|
-
}, variant)), `${key} could not be made ${width} wide in ${format}`);
|
|
95
|
-
await mkdir(join(cache, hash), { recursive: true });
|
|
96
|
-
await keep(file, made.bytes);
|
|
97
|
-
return made.bytes;
|
|
98
|
-
}
|
|
99
|
-
};
|
|
100
|
-
return {
|
|
101
|
-
name: "foldkit-media:images",
|
|
102
|
-
enforce: "pre",
|
|
103
|
-
configResolved(config) {
|
|
104
|
-
root = config.root;
|
|
105
|
-
cache = join(config.cacheDir, "foldkit-media", CACHE_REVISION);
|
|
106
|
-
serving = config.command === "serve";
|
|
107
|
-
},
|
|
108
|
-
async load(id) {
|
|
109
|
-
const [file, query] = id.split("?");
|
|
110
|
-
if (query === void 0 || !new URLSearchParams(query).has(QUERY)) return void 0;
|
|
111
|
-
const bytes = new Uint8Array(await readFile(file));
|
|
112
|
-
const hash = createHash("sha256").update(bytes).digest("hex");
|
|
113
|
-
const key = relative(root, file).split(sep).join("/");
|
|
114
|
-
const asset = await factsOf(key, bytes, hash);
|
|
115
|
-
const widths = widthsFor(ladder, asset.width);
|
|
116
|
-
if (serving) originals.set(hash, {
|
|
117
|
-
bytes,
|
|
118
|
-
widths
|
|
119
|
-
});
|
|
120
|
-
const stem = key.split("/").pop().replace(/\.[^.]+$/, "");
|
|
121
|
-
const files = await Promise.all(widths.flatMap((width) => formats.map(async (format) => {
|
|
122
|
-
let url;
|
|
123
|
-
if (serving) url = JSON.stringify(`${DEV_PREFIX}${hash}/w${width}.${format}`);
|
|
124
|
-
else {
|
|
125
|
-
const source = await variantOf(key, bytes, hash, width, format);
|
|
126
|
-
const contentHash = createHash("sha256").update(source).digest("hex");
|
|
127
|
-
url = `import.meta.ROLLUP_FILE_URL_${this.emitFile({
|
|
128
|
-
type: "asset",
|
|
129
|
-
fileName: `${stem}-${width}-${contentHash}.${format}`,
|
|
130
|
-
source
|
|
131
|
-
})}`;
|
|
132
|
-
}
|
|
133
|
-
return `{ width: ${width}, format: ${JSON.stringify(format)}, url: ${url} }`;
|
|
134
|
-
})));
|
|
135
|
-
return [
|
|
136
|
-
`import { Schema } from 'effect'`,
|
|
137
|
-
`import { HashedAsset, Provider } from 'foldkit-media'`,
|
|
138
|
-
`export default {`,
|
|
139
|
-
` asset: Schema.decodeUnknownSync(HashedAsset)(${JSON.stringify(Schema.encodeSync(ImageAsset)(asset))}),`,
|
|
140
|
-
` provider: Provider.fromFiles([${files.join(", ")}], ${JSON.stringify({
|
|
141
|
-
sources,
|
|
142
|
-
fallback
|
|
143
|
-
})}),`,
|
|
144
|
-
`}`
|
|
145
|
-
].join("\n");
|
|
146
|
-
},
|
|
147
|
-
configureServer(server) {
|
|
148
|
-
server.middlewares.use((request, response, next) => {
|
|
149
|
-
const match = DEV_PATH.exec(request.url?.split("?")[0] ?? "");
|
|
150
|
-
if (match === null) return next();
|
|
151
|
-
const [, hash, width, asked] = match;
|
|
152
|
-
const original = originals.get(hash);
|
|
153
|
-
const format = formats.find((offered) => offered === asked);
|
|
154
|
-
if (original === void 0 || format === void 0 || !original.widths.includes(Number(width))) {
|
|
155
|
-
response.statusCode = 404;
|
|
156
|
-
return response.end();
|
|
157
|
-
}
|
|
158
|
-
variantOf(hash, original.bytes, hash, Number(width), format).then((bytes) => {
|
|
159
|
-
response.setHeader("Content-Type", `image/${format}`);
|
|
160
|
-
response.setHeader("Cache-Control", "no-store");
|
|
161
|
-
response.end(bytes);
|
|
162
|
-
}, next);
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
};
|
|
166
|
-
};
|
|
167
|
-
// src/vite/index.ts
|
|
168
|
-
/**
|
|
169
|
-
* Icons as imports: `import { arrowLeft } from 'virtual:foldkit-icons/lucide'`
|
|
170
|
-
* gives the icon's `IconData`, read from an Iconify set or a folder of the
|
|
171
|
-
* application's own SVG files when the build reads the import. The import is
|
|
172
|
-
* the selection, and the bundler drops what nothing imports. A declaration
|
|
173
|
-
* file names every icon of every set, so a misspelt name is a type error.
|
|
174
|
-
*/
|
|
175
|
-
const PREFIX = "virtual:foldkit-icons/";
|
|
176
|
-
const RESOLVED = `${String.fromCharCode(0)}${PREFIX}`;
|
|
177
|
-
const SET_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/;
|
|
178
|
-
/** `arrow-left` is `arrowLeft`, and `1-circle` `_1Circle`; JavaScript's reserved words export as they are. */
|
|
179
|
-
const exportName = (name) => {
|
|
180
|
-
const camel = name.replace(/[-_:.]+([a-zA-Z0-9])/g, (_, next) => next.toUpperCase());
|
|
181
|
-
return /^[0-9]/.test(camel) ? `_${camel}` : camel;
|
|
182
|
-
};
|
|
183
|
-
const named = (set, entries) => {
|
|
184
|
-
const seen = /* @__PURE__ */ new Map();
|
|
185
|
-
return entries.map(([name, icon]) => {
|
|
186
|
-
const exported = exportName(name);
|
|
187
|
-
if (!/^[A-Za-z_$][\w$]*$/.test(exported)) throw new Error(`foldkit-media/vite: the icon "${set}:${name}" has no name to import it by.`);
|
|
188
|
-
const earlier = seen.get(exported);
|
|
189
|
-
if (earlier !== void 0) throw new Error(`foldkit-media/vite: the icons "${set}:${earlier}" and "${set}:${name}" would both be imported as ${exported}.`);
|
|
190
|
-
seen.set(exported, name);
|
|
191
|
-
return [exported, icon];
|
|
192
|
-
});
|
|
193
|
-
};
|
|
194
|
-
const moduleOf = ({ icons }) => [...icons.map(([, icon], at) => `const i${at} = ${JSON.stringify(icon)}`), `export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(", ")} }`].join("\n");
|
|
195
|
-
const declarationOf = (sets) => [
|
|
196
|
-
"// Written by foldkit-media/vite from the icon sets it is given. Do not edit.",
|
|
197
|
-
...[...sets].map(([name, { icons, refused }]) => [
|
|
198
|
-
`declare module '${PREFIX}${name}' {`,
|
|
199
|
-
" import type { IconData } from 'foldkit-media'",
|
|
200
|
-
...refused.map(([icon, reason]) => ` // Left out, ${icon}: ${reason.replace(/\s+/g, " ")}`),
|
|
201
|
-
...icons.map((_, at) => ` const i${at}: IconData`),
|
|
202
|
-
` export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(", ")} }`,
|
|
203
|
-
"}"
|
|
204
|
-
].join("\n")),
|
|
205
|
-
""
|
|
206
|
-
].join("\n");
|
|
207
|
-
/**
|
|
208
|
-
* The plugin: give it the sets the application imports from. An SVG in a
|
|
209
|
-
* folder that the parser refuses fails the build, naming the file; an icon of
|
|
210
|
-
* an Iconify set that it refuses is left out of the set, and its declaration
|
|
211
|
-
* says why, so only importing that icon fails.
|
|
212
|
-
*/
|
|
213
|
-
const icons = (options = {}) => {
|
|
214
|
-
const iconify = options.iconify ?? [];
|
|
215
|
-
const folders = Object.entries(options.folders ?? {});
|
|
216
|
-
for (const name of [...iconify, ...folders.map(([name]) => name)]) if (!SET_NAME.test(name)) throw new Error(`foldkit-media/vite: "${name}" is not a set name (lowercase words and hyphens).`);
|
|
217
|
-
const twice = [...iconify, ...folders.map(([name]) => name)].find((name, at, all) => all.indexOf(name) !== at);
|
|
218
|
-
if (twice !== void 0) throw new Error(`foldkit-media/vite: the set "${twice}" is given twice.`);
|
|
219
|
-
let root = process.cwd();
|
|
220
|
-
const read = /* @__PURE__ */ new Map();
|
|
221
|
-
const folderDirs = new Map(folders);
|
|
222
|
-
const folderOf = (name) => resolve(root, folderDirs.get(name));
|
|
223
|
-
const readIconify = (prefix) => {
|
|
224
|
-
const require = createRequire(join(root, "package.json"));
|
|
225
|
-
let file;
|
|
226
|
-
try {
|
|
227
|
-
file = require.resolve(`@iconify-json/${prefix}/icons.json`);
|
|
228
|
-
} catch {
|
|
229
|
-
throw new Error(`foldkit-media/vite: the Iconify set "${prefix}" is not installed: add @iconify-json/${prefix}.`);
|
|
230
|
-
}
|
|
231
|
-
let set;
|
|
232
|
-
try {
|
|
233
|
-
set = Schema.decodeUnknownSync(IconifySet)(JSON.parse(readFileSync(file, "utf8")));
|
|
234
|
-
} catch (error) {
|
|
235
|
-
throw new Error(`foldkit-media/vite: ${file} is not an Iconify set: ${error instanceof Error ? error.message : String(error)}`);
|
|
236
|
-
}
|
|
237
|
-
const icons = [];
|
|
238
|
-
const refused = [];
|
|
239
|
-
for (const name of namesOf(set)) try {
|
|
240
|
-
icons.push([name, fromIconify(set, name)]);
|
|
241
|
-
} catch (error) {
|
|
242
|
-
refused.push([name, error instanceof Error ? error.message : String(error)]);
|
|
243
|
-
}
|
|
244
|
-
return {
|
|
245
|
-
icons: named(prefix, icons),
|
|
246
|
-
refused
|
|
247
|
-
};
|
|
248
|
-
};
|
|
249
|
-
const readFolder = (name) => {
|
|
250
|
-
const folder = folderOf(name);
|
|
251
|
-
const files = readdirSync(folder).filter((file) => extname(file) === ".svg").sort();
|
|
252
|
-
return {
|
|
253
|
-
icons: named(name, files.map((file) => {
|
|
254
|
-
const path = join(folder, file);
|
|
255
|
-
return [file.slice(0, -4), parse(readFileSync(path, "utf8"), relative(root, path))];
|
|
256
|
-
})),
|
|
257
|
-
refused: []
|
|
258
|
-
};
|
|
259
|
-
};
|
|
260
|
-
const setOf = (name) => {
|
|
261
|
-
const known = read.get(name);
|
|
262
|
-
if (known !== void 0) return known;
|
|
263
|
-
const made = iconify.includes(name) ? readIconify(name) : readFolder(name);
|
|
264
|
-
read.set(name, made);
|
|
265
|
-
return made;
|
|
266
|
-
};
|
|
267
|
-
const all = () => [...iconify, ...folders.map(([name]) => name)];
|
|
268
|
-
const writeDeclaration = () => {
|
|
269
|
-
if (options.dts === false) return;
|
|
270
|
-
const path = resolve(root, options.dts ?? "foldkit-icons.d.ts");
|
|
271
|
-
const text = declarationOf(new Map(all().map((name) => [name, setOf(name)])));
|
|
272
|
-
let current;
|
|
273
|
-
try {
|
|
274
|
-
current = readFileSync(path, "utf8");
|
|
275
|
-
} catch {
|
|
276
|
-
current = void 0;
|
|
277
|
-
}
|
|
278
|
-
if (current !== text) writeFileSync(path, text);
|
|
279
|
-
};
|
|
280
|
-
return {
|
|
281
|
-
name: "foldkit-media:icons",
|
|
282
|
-
configResolved(config) {
|
|
283
|
-
root = config.root;
|
|
284
|
-
},
|
|
285
|
-
buildStart() {
|
|
286
|
-
read.clear();
|
|
287
|
-
writeDeclaration();
|
|
288
|
-
for (const [name] of folders) this.addWatchFile(folderOf(name));
|
|
289
|
-
},
|
|
290
|
-
resolveId(id) {
|
|
291
|
-
if (!id.startsWith(PREFIX)) return void 0;
|
|
292
|
-
const name = id.slice(22);
|
|
293
|
-
if (!all().includes(name)) throw new Error(`foldkit-media/vite: there is no icon set "${name}"; the sets given are ${all().join(", ") || "none"}.`);
|
|
294
|
-
return `${RESOLVED}${name}`;
|
|
295
|
-
},
|
|
296
|
-
load(id) {
|
|
297
|
-
if (!id.startsWith(RESOLVED)) return void 0;
|
|
298
|
-
const name = id.slice(RESOLVED.length);
|
|
299
|
-
if (folders.some(([folder]) => folder === name)) for (const file of readdirSync(folderOf(name))) this.addWatchFile(join(folderOf(name), file));
|
|
300
|
-
return moduleOf(setOf(name));
|
|
301
|
-
},
|
|
302
|
-
configureServer(server) {
|
|
303
|
-
const dirs = folders.map(([name]) => [name, folderOf(name)]);
|
|
304
|
-
server.watcher.add(dirs.map(([, dir]) => dir));
|
|
305
|
-
server.watcher.on("all", (_, file) => {
|
|
306
|
-
const changed = dirs.find(([, dir]) => {
|
|
307
|
-
const path = relative(dir, file);
|
|
308
|
-
return !isAbsolute(path) && !path.startsWith("..");
|
|
309
|
-
});
|
|
310
|
-
if (changed === void 0 || extname(file) !== ".svg") return;
|
|
311
|
-
read.delete(changed[0]);
|
|
312
|
-
try {
|
|
313
|
-
writeDeclaration();
|
|
314
|
-
} catch (error) {
|
|
315
|
-
server.config.logger.error(error instanceof Error ? error.message : String(error));
|
|
316
|
-
}
|
|
317
|
-
for (const environment of Object.values(server.environments)) {
|
|
318
|
-
const module = environment.moduleGraph.getModuleById(`${RESOLVED}${changed[0]}`);
|
|
319
|
-
if (module !== void 0) environment.moduleGraph.invalidateModule(module);
|
|
320
|
-
}
|
|
321
|
-
server.ws.send({ type: "full-reload" });
|
|
322
|
-
});
|
|
323
|
-
}
|
|
324
|
-
};
|
|
325
|
-
};
|
|
326
|
-
export { exportName, icons, images };
|
|
327
|
-
|
|
328
|
-
//# sourceMappingURL=index.mjs.map
|
package/dist/vite/index.mjs.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["Widths.standard"],"sources":["../../src/vite/images.ts","../../src/vite/index.ts"],"sourcesContent":["/**\n * Images as imports: `import hero from './hero.jpg?image'` gives `{ asset,\n * provider }`, ready for `Picture.derive` or `foldkit-mixins-ui`'s `Image.view`.\n * The build reads the file's facts once (`describe`, through sharp), writes a\n * file for each ladder width up to the original's own in each format, and\n * names them by content, so a host may keep them for good. The development\n * server makes the same variants when a page asks for them.\n */\nimport { createHash, randomUUID } from 'node:crypto'\nimport { mkdir, readFile, rename, writeFile } from 'node:fs/promises'\nimport { availableParallelism } from 'node:os'\nimport { join, relative, sep } from 'node:path'\nimport { Cause, Effect, Exit, Layer, ManagedRuntime, Option, Schema, Semaphore } from 'effect'\nimport type { Plugin } from 'vite'\nimport { ImageAsset } from '../asset.js'\nimport type { Format } from '../format.js'\nimport type { Variant } from '../variant.js'\nimport * as Widths from '../widths.js'\nimport { describe, type Inspector } from '../describe.js'\nimport { Transformer } from '../server/services.js'\n\nconst QUERY = 'image'\n// The kept facts' and variants' generation: raised when what `describe` reads or the encoder\n// makes changes, so every build re-reads once, and one that changes neither encodes nothing\n// again. sharp's own version is not in it: a patch release would re-encode every AVIF for\n// nothing anyone sees. r2: an original is read as its EXIF orientation shows it.\nconst CACHE_REVISION = 'r2'\nconst DEV_PREFIX = '/@foldkit-media/image/'\nconst DEV_PATH = /^\\/@foldkit-media\\/image\\/([0-9a-f]{64})\\/w(\\d+)\\.(avif|webp|jpeg|png)$/\n\nexport interface ImagesOptions {\n /** The widths offered, up to each original's own: `Widths.standard` unless given. */\n readonly widths?: Widths.Widths | undefined\n /** Formats offered as `source`s, most preferred first: `['avif']` unless given. */\n readonly sources?: ReadonlyArray<Format> | undefined\n /** The `img`'s own format: `webp` unless given. */\n readonly fallback?: Format | undefined\n /** The encoder's quality, 1 to 100; its own default unless given. */\n readonly quality?: number | undefined\n}\n\ntype Media = ManagedRuntime.ManagedRuntime<Inspector | Transformer, never>\n\n/** The widths a build writes of an original: the ladder's below its own, then its own. */\nconst widthsFor = (ladder: Widths.Widths, width: number): ReadonlyArray<number> => [\n ...ladder.values.filter(value => value < width),\n width,\n]\n\n/**\n * Keeps `bytes` at `file` whole or not at all: written beside it, then moved in, so a build\n * stopped halfway leaves no cut-short file that a later build would trust.\n */\nconst keep = async (file: string, bytes: Uint8Array | string) => {\n const partial = `${file}.${randomUUID()}.partial`\n await writeFile(partial, bytes)\n await rename(partial, file)\n}\n\nconst run = async <A, E>(\n media: Media,\n effect: Effect.Effect<A, E, Inspector | Transformer>,\n what: string,\n) => {\n const exit = await media.runPromiseExit(effect)\n if (Exit.isSuccess(exit)) return exit.value\n throw new Error(`foldkit-media/vite: ${what}: ${Cause.pretty(exit.cause)}`)\n}\n\n/**\n * The plugin: an import with `?image` becomes the image's facts and a\n * provider over its variants. sharp is read on the first such import, so an\n * application that imports none needs no sharp.\n */\nexport const images = (options: ImagesOptions = {}): Plugin => {\n const ladder = options.widths ?? Widths.standard\n const sources = options.sources ?? ['avif']\n const fallback = options.fallback ?? 'webp'\n const formats = [...new Set([...sources, fallback])]\n const quality = Option.fromNullishOr(options.quality)\n if (\n Option.isSome(quality) &&\n !(Number.isInteger(quality.value) && quality.value >= 1 && quality.value <= 100)\n ) {\n throw new Error(\n `foldkit-media/vite: a quality is a whole number from 1 to 100, not ${quality.value}.`,\n )\n }\n\n let root = process.cwd()\n let cache = join(root, 'node_modules', '.vite', 'foldkit-media', CACHE_REVISION)\n let serving = false\n /** The originals the development server has been asked to vary, by content hash. */\n const originals = new Map<\n string,\n { readonly bytes: Uint8Array<ArrayBuffer>; readonly widths: ReadonlyArray<number> }\n >()\n\n // Each read decodes a whole original, and a build loads every import at once: as many at a\n // time as there are cores, as the Transformer's own bound.\n const inspecting = Semaphore.makeUnsafe(availableParallelism())\n let media: Promise<Media> | undefined\n const mediaOf = () =>\n (media ??= import('../sharp/index.js').then(\n ({ inspectorSharp, transformerSharp }) =>\n ManagedRuntime.make(Layer.mergeAll(inspectorSharp(), transformerSharp())),\n cause => {\n throw new Error(\n `foldkit-media/vite: a ?image import needs sharp; add it to the application. (${String(cause)})`,\n )\n },\n ))\n\n const factsOf = async (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n hash: string,\n ): Promise<ImageAsset> => {\n const file = join(cache, hash, 'asset.json')\n try {\n return Schema.decodeUnknownSync(ImageAsset)({\n ...JSON.parse(await readFile(file, 'utf8')),\n key,\n })\n } catch {\n // Not kept yet, or kept by an older version: the facts are made again, as a cache's are.\n const asset = await run(\n await mediaOf(),\n Semaphore.withPermit(inspecting)(describe(key, bytes)),\n `${key} could not be read`,\n )\n await mkdir(join(cache, hash), { recursive: true })\n await keep(file, JSON.stringify(Schema.encodeSync(ImageAsset)(asset)))\n return asset\n }\n }\n\n const variantOf = async (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n hash: string,\n width: number,\n format: Format,\n ): Promise<Uint8Array<ArrayBuffer>> => {\n const name = `w${width}${Option.match(quality, { onNone: () => '', onSome: q => `q${q}` })}.${format}`\n const file = join(cache, hash, name)\n try {\n return new Uint8Array(await readFile(file))\n } catch {\n // Not kept yet: made, and kept for the next build.\n const variant: Variant = { width, format, quality }\n const made = await run(\n await mediaOf(),\n Transformer.use(transformer =>\n transformer.transform(\n { body: new Blob([bytes]).stream(), size: bytes.byteLength },\n variant,\n ),\n ),\n `${key} could not be made ${width} wide in ${format}`,\n )\n await mkdir(join(cache, hash), { recursive: true })\n await keep(file, made.bytes)\n return made.bytes\n }\n }\n\n return {\n name: 'foldkit-media:images',\n // Before Vite's own asset handling, which takes a `.jpg` import of any query as a URL.\n enforce: 'pre',\n configResolved(config) {\n root = config.root\n cache = join(config.cacheDir, 'foldkit-media', CACHE_REVISION)\n serving = config.command === 'serve'\n },\n async load(id) {\n const [file, query] = id.split('?')\n if (query === undefined || !new URLSearchParams(query).has(QUERY)) return undefined\n const bytes = new Uint8Array(await readFile(file!))\n const hash = createHash('sha256').update(bytes).digest('hex')\n const key = relative(root, file!).split(sep).join('/')\n const asset = await factsOf(key, bytes, hash)\n const widths = widthsFor(ladder, asset.width)\n if (serving) originals.set(hash, { bytes, widths })\n const stem = key\n .split('/')\n .pop()!\n .replace(/\\.[^.]+$/, '')\n // Made together: the Transformer bounds how many run at once, and AVIF is slow one by one.\n const files = await Promise.all(\n widths.flatMap(width =>\n formats.map(async format => {\n let url: string\n if (serving) {\n url = JSON.stringify(`${DEV_PREFIX}${hash}/w${width}.${format}`)\n } else {\n const source = await variantOf(key, bytes, hash, width, format)\n const contentHash = createHash('sha256').update(source).digest('hex')\n url = `import.meta.ROLLUP_FILE_URL_${this.emitFile({\n type: 'asset',\n fileName: `${stem}-${width}-${contentHash}.${format}`,\n source,\n })}`\n }\n return `{ width: ${width}, format: ${JSON.stringify(format)}, url: ${url} }`\n }),\n ),\n )\n return [\n `import { Schema } from 'effect'`,\n `import { HashedAsset, Provider } from 'foldkit-media'`,\n `export default {`,\n ` asset: Schema.decodeUnknownSync(HashedAsset)(${JSON.stringify(Schema.encodeSync(ImageAsset)(asset))}),`,\n ` provider: Provider.fromFiles([${files.join(', ')}], ${JSON.stringify({ sources, fallback })}),`,\n `}`,\n ].join('\\n')\n },\n configureServer(server) {\n server.middlewares.use((request, response, next) => {\n const match = DEV_PATH.exec(request.url?.split('?')[0] ?? '')\n if (match === null) return next()\n const [, hash, width, asked] = match\n const original = originals.get(hash!)\n const format = formats.find(offered => offered === asked)\n if (\n original === undefined ||\n format === undefined ||\n !original.widths.includes(Number(width))\n ) {\n response.statusCode = 404\n return response.end()\n }\n variantOf(hash!, original.bytes, hash!, Number(width), format).then(bytes => {\n response.setHeader('Content-Type', `image/${format}`)\n response.setHeader('Cache-Control', 'no-store')\n response.end(bytes)\n }, next)\n })\n },\n }\n}\n","/**\n * Icons as imports: `import { arrowLeft } from 'virtual:foldkit-icons/lucide'`\n * gives the icon's `IconData`, read from an Iconify set or a folder of the\n * application's own SVG files when the build reads the import. The import is\n * the selection, and the bundler drops what nothing imports. A declaration\n * file names every icon of every set, so a misspelt name is a type error.\n */\nimport { readdirSync, readFileSync, writeFileSync } from 'node:fs'\nimport { createRequire } from 'node:module'\nimport { extname, isAbsolute, join, relative, resolve } from 'node:path'\nimport { Schema } from 'effect'\nimport type { Plugin } from 'vite'\nimport type { IconData } from '../icon.js'\nimport { fromIconify, IconifySet, namesOf, parse } from '../icons/index.js'\n\nconst PREFIX = 'virtual:foldkit-icons/'\n// Rollup's mark for a module no file holds, which other plugins leave alone.\nconst RESOLVED = `${String.fromCharCode(0)}${PREFIX}`\nconst SET_NAME = /^[a-z0-9]+(-[a-z0-9]+)*$/\n\nexport interface IconsOptions {\n /** Iconify sets by prefix (`lucide`, `uil`), each read from the application's `@iconify-json/<prefix>`. */\n readonly iconify?: ReadonlyArray<string> | undefined\n /** The application's own sets: a name, and a folder whose SVG files are its icons, each named by its file. */\n readonly folders?: Readonly<Record<string, string>> | undefined\n /** Where the declaration of every set is written, from the root: `foldkit-icons.d.ts` unless given; `false` writes none. */\n readonly dts?: string | false | undefined\n}\n\n/** An icon set ready to be a module: each icon under the name it is imported by. */\ninterface ReadSet {\n readonly icons: ReadonlyArray<readonly [exported: string, icon: IconData]>\n /** The icons of an Iconify set the parser refused, and why: left out, so importing one fails. */\n readonly refused: ReadonlyArray<readonly [name: string, reason: string]>\n}\n\n/** `arrow-left` is `arrowLeft`, and `1-circle` `_1Circle`; JavaScript's reserved words export as they are. */\nexport const exportName = (name: string): string => {\n const camel = name.replace(/[-_:.]+([a-zA-Z0-9])/g, (_, next: string) => next.toUpperCase())\n return /^[0-9]/.test(camel) ? `_${camel}` : camel\n}\n\nconst named = (\n set: string,\n entries: ReadonlyArray<readonly [name: string, icon: IconData]>,\n): ReadSet['icons'] => {\n const seen = new Map<string, string>()\n return entries.map(([name, icon]) => {\n const exported = exportName(name)\n if (!/^[A-Za-z_$][\\w$]*$/.test(exported)) {\n throw new Error(`foldkit-media/vite: the icon \"${set}:${name}\" has no name to import it by.`)\n }\n const earlier = seen.get(exported)\n if (earlier !== undefined) {\n throw new Error(\n `foldkit-media/vite: the icons \"${set}:${earlier}\" and \"${set}:${name}\" would both be imported as ${exported}.`,\n )\n }\n seen.set(exported, name)\n return [exported, icon] as const\n })\n}\n\nconst moduleOf = ({ icons }: ReadSet): string =>\n [\n ...icons.map(([, icon], at) => `const i${at} = ${JSON.stringify(icon)}`),\n `export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(', ')} }`,\n ].join('\\n')\n\nconst declarationOf = (sets: ReadonlyMap<string, ReadSet>): string =>\n [\n '// Written by foldkit-media/vite from the icon sets it is given. Do not edit.',\n ...[...sets].map(([name, { icons, refused }]) =>\n [\n `declare module '${PREFIX}${name}' {`,\n \" import type { IconData } from 'foldkit-media'\",\n ...refused.map(\n ([icon, reason]) => ` // Left out, ${icon}: ${reason.replace(/\\s+/g, ' ')}`,\n ),\n ...icons.map((_, at) => ` const i${at}: IconData`),\n ` export { ${icons.map(([exported], at) => `i${at} as ${exported}`).join(', ')} }`,\n '}',\n ].join('\\n'),\n ),\n '',\n ].join('\\n')\n\n/**\n * The plugin: give it the sets the application imports from. An SVG in a\n * folder that the parser refuses fails the build, naming the file; an icon of\n * an Iconify set that it refuses is left out of the set, and its declaration\n * says why, so only importing that icon fails.\n */\nexport const icons = (options: IconsOptions = {}): Plugin => {\n const iconify = options.iconify ?? []\n const folders = Object.entries(options.folders ?? {})\n for (const name of [...iconify, ...folders.map(([name]) => name)]) {\n if (!SET_NAME.test(name)) {\n throw new Error(\n `foldkit-media/vite: \"${name}\" is not a set name (lowercase words and hyphens).`,\n )\n }\n }\n const twice = [...iconify, ...folders.map(([name]) => name)].find(\n (name, at, all) => all.indexOf(name) !== at,\n )\n if (twice !== undefined) throw new Error(`foldkit-media/vite: the set \"${twice}\" is given twice.`)\n\n let root = process.cwd()\n const read = new Map<string, ReadSet>()\n const folderDirs = new Map(folders)\n const folderOf = (name: string) => resolve(root, folderDirs.get(name)!)\n\n const readIconify = (prefix: string): ReadSet => {\n const require = createRequire(join(root, 'package.json'))\n let file: string\n try {\n file = require.resolve(`@iconify-json/${prefix}/icons.json`)\n } catch {\n throw new Error(\n `foldkit-media/vite: the Iconify set \"${prefix}\" is not installed: add @iconify-json/${prefix}.`,\n )\n }\n let set: IconifySet\n try {\n set = Schema.decodeUnknownSync(IconifySet)(JSON.parse(readFileSync(file, 'utf8')))\n } catch (error) {\n throw new Error(\n `foldkit-media/vite: ${file} is not an Iconify set: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n const icons: Array<readonly [string, IconData]> = []\n const refused: Array<readonly [string, string]> = []\n for (const name of namesOf(set)) {\n try {\n icons.push([name, fromIconify(set, name)])\n } catch (error) {\n refused.push([name, error instanceof Error ? error.message : String(error)])\n }\n }\n return { icons: named(prefix, icons), refused }\n }\n\n const readFolder = (name: string): ReadSet => {\n const folder = folderOf(name)\n const files = readdirSync(folder)\n .filter(file => extname(file) === '.svg')\n .sort()\n return {\n icons: named(\n name,\n files.map(file => {\n const path = join(folder, file)\n return [\n file.slice(0, -4),\n parse(readFileSync(path, 'utf8'), relative(root, path)),\n ] as const\n }),\n ),\n refused: [],\n }\n }\n\n const setOf = (name: string): ReadSet => {\n const known = read.get(name)\n if (known !== undefined) return known\n const made = iconify.includes(name) ? readIconify(name) : readFolder(name)\n read.set(name, made)\n return made\n }\n\n const all = () => [...iconify, ...folders.map(([name]) => name)]\n\n const writeDeclaration = () => {\n if (options.dts === false) return\n const path = resolve(root, options.dts ?? 'foldkit-icons.d.ts')\n const text = declarationOf(new Map(all().map(name => [name, setOf(name)])))\n let current: string | undefined\n try {\n current = readFileSync(path, 'utf8')\n } catch {\n current = undefined\n }\n // Written only when it changes, so a watcher on the file does not see a write of every build.\n if (current !== text) writeFileSync(path, text)\n }\n\n return {\n name: 'foldkit-media:icons',\n configResolved(config) {\n root = config.root\n },\n buildStart() {\n read.clear()\n writeDeclaration()\n for (const [name] of folders) this.addWatchFile(folderOf(name))\n },\n resolveId(id) {\n if (!id.startsWith(PREFIX)) return undefined\n const name = id.slice(PREFIX.length)\n if (!all().includes(name)) {\n throw new Error(\n `foldkit-media/vite: there is no icon set \"${name}\"; the sets given are ${all().join(', ') || 'none'}.`,\n )\n }\n return `${RESOLVED}${name}`\n },\n load(id) {\n if (!id.startsWith(RESOLVED)) return undefined\n const name = id.slice(RESOLVED.length)\n if (folders.some(([folder]) => folder === name)) {\n for (const file of readdirSync(folderOf(name)))\n this.addWatchFile(join(folderOf(name), file))\n }\n return moduleOf(setOf(name))\n },\n configureServer(server) {\n const dirs = folders.map(([name]) => [name, folderOf(name)] as const)\n server.watcher.add(dirs.map(([, dir]) => dir))\n server.watcher.on('all', (_, file) => {\n const changed = dirs.find(([, dir]) => {\n const path = relative(dir, file)\n return !isAbsolute(path) && !path.startsWith('..')\n })\n if (changed === undefined || extname(file) !== '.svg') return\n read.delete(changed[0])\n try {\n writeDeclaration()\n } catch (error) {\n // A throw here would end the server; the set's next load fails with it, where the page shows it.\n server.config.logger.error(error instanceof Error ? error.message : String(error))\n }\n for (const environment of Object.values(server.environments)) {\n const module = environment.moduleGraph.getModuleById(`${RESOLVED}${changed[0]}`)\n if (module !== undefined) environment.moduleGraph.invalidateModule(module)\n }\n server.ws.send({ type: 'full-reload' })\n })\n },\n }\n}\n\nexport { images, type ImagesOptions } from './images.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAqBA,MAAM,QAAQ;AAKd,MAAM,iBAAiB;AACvB,MAAM,aAAa;AACnB,MAAM,WAAW;;AAgBjB,MAAM,aAAa,QAAuB,UAAyC,CACjF,GAAG,O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,OAAO;KAEd,OAAO,OAAO,OAAO,MAAM,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,CAAC;IACnF;IACA,KAAK,MAAM,eAAe,OAAO,OAAO,OAAO,YAAY,GAAG;KAC5D,MAAM,SAAS,YAAY,YAAY,cAAc,GAAG,WAAW,QAAQ,IAAI;KAC/E,IAAI,WAAW,KAAA,GAAW,YAAY,YAAY,iBAAiB,MAAM;IAC3E;IACA,OAAO,GAAG,KAAK,EAAE,MAAM,cAAc,CAAC;GACxC,CAAC;EACH;CACF;AACF"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"widths-qp3jshiF.mjs","names":[],"sources":["../src/widths.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/**\n * The widths an image is made at, ascending. The view takes candidates from\n * it, a server's request Schema accepts only these, and a build emits only\n * these, so the three cannot disagree.\n */\nexport interface Widths {\n readonly values: ReadonlyArray<number>\n /** Decodes a width on the ladder and refuses any other. */\n readonly Schema: Schema.Codec<number>\n}\n\n/**\n * A ladder from its widths. Refuses an empty list, a width that is not a\n * positive integer, and a repeated width: each is a mistake in the\n * declaration, not something to repair quietly.\n */\nexport const make = (values: ReadonlyArray<number>): Widths => {\n if (values.length === 0) throw new Error('Widths.make: a ladder needs at least one width')\n for (const width of values) {\n if (!Number.isInteger(width) || width <= 0) {\n throw new Error(`Widths.make: ${width} is not a positive integer width`)\n }\n }\n const sorted = [...values].sort((a, b) => a - b)\n for (let index = 1; index < sorted.length; index++) {\n if (sorted[index] === sorted[index - 1]) {\n throw new Error(`Widths.make: ${sorted[index]} appears twice`)\n }\n }\n return { values: sorted, Schema: Schema.Literals(sorted) }\n}\n\n/** Phones through a 2560px screen at 1x, and 1280px at 2x. */\nexport const standard: Widths = make([320, 480, 640, 828, 1080, 1280, 1920, 2560])\n\n/** The smallest width at or above `width`, or the largest when none is. */\nexport const atLeast = (widths: Widths, width: number): number =>\n widths.values.find(value => value >= width) ?? widths.values[widths.values.length - 1]!\n"],"mappings":";;;;;;;;;;;;;AAkBA,MAAa,QAAQ,WAA0C;CAC7D,IAAI,OAAO,WAAW,GAAG,MAAM,IAAI,MAAM,gDAAgD;CACzF,KAAK,MAAM,SAAS,QAClB,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,SAAS,GACvC,MAAM,IAAI,MAAM,gBAAgB,MAAM,iCAAiC;CAG3E,MAAM,SAAS,CAAC,GAAG,MAAM,CAAC,CAAC,MAAM,GAAG,MAAM,IAAI,CAAC;CAC/C,KAAK,IAAI,QAAQ,GAAG,QAAQ,OAAO,QAAQ,SACzC,IAAI,OAAO,WAAW,OAAO,QAAQ,IACnC,MAAM,IAAI,MAAM,gBAAgB,OAAO,OAAO,eAAe;CAGjE,OAAO;EAAE,QAAQ;EAAQ,QAAQ,OAAO,SAAS,MAAM;CAAE;AAC3D;;AAGA,MAAa,WAAmB,KAAK;CAAC;CAAK;CAAK;CAAK;CAAK;CAAM;CAAM;CAAM;AAAI,CAAC;;AAGjF,MAAa,WAAW,QAAgB,UACtC,OAAO,OAAO,MAAK,UAAS,SAAS,KAAK,KAAK,OAAO,OAAO,OAAO,OAAO,SAAS"}
|
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { Schema } from "effect";
|
|
2
|
-
/** An encoding a variant can be written in. */
|
|
3
|
-
declare const Format: Schema.Literals<readonly ["avif", "webp", "jpeg", "png"]>;
|
|
4
|
-
type Format = typeof Format.Type;
|
|
5
|
-
/**
|
|
6
|
-
* What a provider is asked for: a format, or `auto` for a provider that picks
|
|
7
|
-
* the format itself from the request's `Accept`.
|
|
8
|
-
*/
|
|
9
|
-
type Encoding = Format | 'auto';
|
|
10
|
-
/** The media type a `source` element names. */
|
|
11
|
-
declare const mimeType: (format: Format) => string;
|
|
12
|
-
declare namespace widths_d_exports {
|
|
13
|
-
export { Widths, atLeast, make, standard };
|
|
14
|
-
}
|
|
15
|
-
/**
|
|
16
|
-
* The widths an image is made at, ascending. The view takes candidates from
|
|
17
|
-
* it, a server's request Schema accepts only these, and a build emits only
|
|
18
|
-
* these, so the three cannot disagree.
|
|
19
|
-
*/
|
|
20
|
-
interface Widths {
|
|
21
|
-
readonly values: ReadonlyArray<number>;
|
|
22
|
-
/** Decodes a width on the ladder and refuses any other. */
|
|
23
|
-
readonly Schema: Schema.Codec<number>;
|
|
24
|
-
}
|
|
25
|
-
/**
|
|
26
|
-
* A ladder from its widths. Refuses an empty list, a width that is not a
|
|
27
|
-
* positive integer, and a repeated width: each is a mistake in the
|
|
28
|
-
* declaration, not something to repair quietly.
|
|
29
|
-
*/
|
|
30
|
-
declare const make: (values: ReadonlyArray<number>) => Widths;
|
|
31
|
-
/** Phones through a 2560px screen at 1x, and 1280px at 2x. */
|
|
32
|
-
declare const standard: Widths;
|
|
33
|
-
/** The smallest width at or above `width`, or the largest when none is. */
|
|
34
|
-
declare const atLeast: (widths: Widths, width: number) => number;
|
|
35
|
-
export { mimeType as a, Format as i, widths_d_exports as n, Encoding as r, Widths as t };
|
|
36
|
-
//# sourceMappingURL=widths-upkgLdek.d.mts.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"widths-upkgLdek.d.mts","names":[],"sources":["../src/format.ts","../src/widths.ts"],"mappings":";;cAGa,QAAM,OAAA;KACP,gBAAgB,OAAO;;;;;KAMvB,WAAW;;cAUV,WAAQ,QAAY;;;;;;;;;UCbhB;WACN,QAAQ;;WAER,QAAQ,OAAO;;;;;;;cAQb,OAAI,QAAY,0BAAwB;;cAiBxC,UAAU;;cAGV,UAAO,QAAY,QAAM"}
|