foldkit-media 0.2.0 → 0.3.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 +92 -28
- package/dist/{asset-Dlkss5qp.d.mts → asset-BLo8VWmd.d.mts} +1 -3
- package/dist/asset-BLo8VWmd.d.mts.map +1 -0
- package/dist/browser/index.d.mts +86 -4
- package/dist/browser/index.d.mts.map +1 -1
- package/dist/browser/index.mjs +88 -7
- package/dist/browser/index.mjs.map +1 -1
- package/dist/cloudflare/index.d.mts +9 -6
- package/dist/cloudflare/index.d.mts.map +1 -1
- package/dist/cloudflare/index.mjs +19 -9
- package/dist/cloudflare/index.mjs.map +1 -1
- package/dist/{describe-CivKHl4x.d.mts → describe-BOgc0xbR.d.mts} +2 -6
- package/dist/describe-BOgc0xbR.d.mts.map +1 -0
- package/dist/{describe-h9F5stgR.mjs → describe-C6sWA_8p.mjs} +6 -9
- package/dist/{describe-h9F5stgR.mjs.map → describe-C6sWA_8p.mjs.map} +1 -1
- package/dist/{errors-qETj7Pgi.mjs → errors-BhEgXJ4m.mjs} +2 -3
- package/dist/{errors-qETj7Pgi.mjs.map → errors-BhEgXJ4m.mjs.map} +1 -1
- package/dist/{format-BmfnR4jg.mjs → format-BCRTFU9j.mjs} +2 -3
- package/dist/{format-BmfnR4jg.mjs.map → format-BCRTFU9j.mjs.map} +1 -1
- package/dist/{icon-CowP8fQ0.mjs → icon-0A2dBtqj.mjs} +3 -4
- package/dist/{icon-CowP8fQ0.mjs.map → icon-0A2dBtqj.mjs.map} +1 -1
- package/dist/{icon-ClqtprHT.d.mts → icon-BGtxExTN.d.mts} +1 -2
- package/dist/{icon-ClqtprHT.d.mts.map → icon-BGtxExTN.d.mts.map} +1 -1
- package/dist/icons/index.d.mts +1 -3
- package/dist/icons/index.d.mts.map +1 -1
- package/dist/icons/index.mjs +2 -3
- package/dist/index.d.mts +6 -9
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +9 -13
- package/dist/index.mjs.map +1 -1
- package/dist/{limits-B6C9OOLl.mjs → limits-B4hHpyfE.mjs} +2 -3
- package/dist/{limits-B6C9OOLl.mjs.map → limits-B4hHpyfE.mjs.map} +1 -1
- package/dist/{provider-g0Vlvlrb.d.mts → provider-CB0nqu0m.d.mts} +4 -5
- package/dist/{provider-g0Vlvlrb.d.mts.map → provider-CB0nqu0m.d.mts.map} +1 -1
- package/dist/{rolldown-runtime-8H4AJuhK.mjs → rolldown-runtime-BJohB4LM.mjs} +1 -2
- package/dist/server/index.d.mts +8 -19
- package/dist/server/index.d.mts.map +1 -1
- package/dist/server/index.mjs +11 -15
- package/dist/server/index.mjs.map +1 -1
- package/dist/{services-BeakQl7F.mjs → services-7B4hsQM7.mjs} +3 -4
- package/dist/{services-BeakQl7F.mjs.map → services-7B4hsQM7.mjs.map} +1 -1
- package/dist/{services-8_h0ubLB.d.mts → services-BZoK2VOY.d.mts} +3 -5
- package/dist/services-BZoK2VOY.d.mts.map +1 -0
- package/dist/sharp/index.d.mts +2 -4
- package/dist/sharp/index.d.mts.map +1 -1
- package/dist/sharp/index.mjs +5 -6
- package/dist/{stores-BtmSl8X3.mjs → stores-CxraN3kt.mjs} +73 -31
- package/dist/stores-CxraN3kt.mjs.map +1 -0
- package/dist/unpic/index.d.mts +2 -4
- package/dist/unpic/index.d.mts.map +1 -1
- package/dist/unpic/index.mjs +2 -3
- package/dist/{upload-kp0_oK76.d.mts → upload-lVLMRJoC.d.mts} +47 -18
- package/dist/upload-lVLMRJoC.d.mts.map +1 -0
- package/dist/{variant-BOg1M0Wj.d.mts → variant-B-vyMmFB.d.mts} +2 -3
- package/dist/{variant-BOg1M0Wj.d.mts.map → variant-B-vyMmFB.d.mts.map} +1 -1
- package/dist/vite/index.d.mts +1 -5
- package/dist/vite/index.d.mts.map +1 -1
- package/dist/vite/index.mjs +5 -7
- package/dist/vite/index.mjs.map +1 -1
- package/dist/{widths-BEa9odY6.mjs → widths-qp3jshiF.mjs} +3 -4
- package/dist/{widths-BEa9odY6.mjs.map → widths-qp3jshiF.mjs.map} +1 -1
- package/dist/{widths-Cg7-x89y.d.mts → widths-upkgLdek.d.mts} +1 -3
- package/dist/widths-upkgLdek.d.mts.map +1 -0
- package/package.json +6 -6
- package/dist/asset-Dlkss5qp.d.mts.map +0 -1
- package/dist/describe-CivKHl4x.d.mts.map +0 -1
- package/dist/services-8_h0ubLB.d.mts.map +0 -1
- package/dist/stores-BtmSl8X3.mjs.map +0 -1
- package/dist/upload-kp0_oK76.d.mts.map +0 -1
- package/dist/widths-Cg7-x89y.d.mts.map +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-
|
|
2
|
-
import { r as standard$1 } from "./widths-
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
|
+
import { r as standard$1 } from "./widths-qp3jshiF.mjs";
|
|
3
3
|
import { Context, Effect, Option, Schema, SchemaGetter } from "effect";
|
|
4
4
|
import { rgbaToThumbHash } from "thumbhash";
|
|
5
|
-
|
|
5
|
+
// src/variant.ts
|
|
6
6
|
var variant_exports = /* @__PURE__ */ __exportAll({
|
|
7
7
|
ContentHash: () => ContentHash,
|
|
8
8
|
PATH: () => PATH,
|
|
@@ -81,8 +81,7 @@ const space = (options = {}) => {
|
|
|
81
81
|
};
|
|
82
82
|
/** The standard ladder, AVIF and WebP, and no quality in any URL: 16 variants an original. */
|
|
83
83
|
const standard = space();
|
|
84
|
-
|
|
85
|
-
//#region src/asset.ts
|
|
84
|
+
// src/asset.ts
|
|
86
85
|
const CSS_COLOR = /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\([0-9a-z%.,\s/+-]*\))$/i;
|
|
87
86
|
const coefficientCount = (x, y) => {
|
|
88
87
|
let count = 0;
|
|
@@ -143,8 +142,7 @@ const ImageAsset = Schema.Struct({
|
|
|
143
142
|
const isHashed = (asset) => Option.isSome(asset.hash);
|
|
144
143
|
/** `ImageAsset`, refusing facts with no content hash. */
|
|
145
144
|
const HashedAsset = ImageAsset.pipe(Schema.refine(isHashed));
|
|
146
|
-
|
|
147
|
-
//#region src/describe.ts
|
|
145
|
+
// src/describe.ts
|
|
148
146
|
/** Reads an original's facts: its size, its alpha, and a thumbnail. */
|
|
149
147
|
var Inspector = class extends Context.Service()("foldkit-media/Inspector") {};
|
|
150
148
|
const hex = (buffer) => Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
@@ -168,7 +166,6 @@ const describe = (key, bytes) => Effect.gen(function* () {
|
|
|
168
166
|
focus: Option.none()
|
|
169
167
|
};
|
|
170
168
|
});
|
|
171
|
-
//#endregion
|
|
172
169
|
export { ImageAsset as a, ContentHash as c, Spelling as d, respell as f, variant_exports as h, HashedAsset as i, PATH as l, standard as m, describe as n, Placeholder as o, revisionOf as p, Focus as r, isHashed as s, Inspector as t, Quality as u };
|
|
173
170
|
|
|
174
|
-
//# sourceMappingURL=describe-
|
|
171
|
+
//# sourceMappingURL=describe-C6sWA_8p.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"describe-h9F5stgR.mjs","names":["Widths.standard"],"sources":["../src/variant.ts","../src/asset.ts","../src/describe.ts"],"sourcesContent":["import { Option, Schema, SchemaGetter } from 'effect'\nimport { Format } from './format.js'\nimport * as Widths from './widths.js'\n\n/**\n * Where a hosted variant lives: the original's content hash, then the variant.\n * The server routes this path and `Provider.hosted` fills it in, so the two\n * read one string. It ends in the format's extension, so a variant written\n * out as a file is served with its type by any static host.\n */\nexport const PATH = '/_image/:hash/:variant'\n\n/** An original's SHA-256, in lowercase hex: its name in the store. */\nexport const ContentHash = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/))\n\n/** A quality from 1 to 100. */\nexport const Quality = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))\n\n// No leading zero anywhere: one request has one spelling, so one cache key. The output's\n// revision is written only above 0, so every URL written before revisions keeps its spelling.\nconst SPELLING = /^w([1-9]\\d{0,4})(?:q([1-9]\\d?|100))?(?:\\.r([1-9]\\d{0,3}))?\\.(avif|webp|jpeg|png)$/\n\n/**\n * The grammar every release reads, whatever its space: a spelling it matches\n * may be one another release offers, so refusing it says nothing for good.\n */\nexport const Spelling = Schema.String.check(Schema.isPattern(SPELLING))\n\n/** The output revision a spelling names: `w640.r2.avif` is 2, and one naming none is 0. */\nexport const revisionOf = (spelling: string): number => Number(SPELLING.exec(spelling)?.[3] ?? 0)\n\n/** `spelling` at `revision`: the same variant, as that revision writes it. */\nexport const respell = (spelling: string, revision: number): string =>\n spelling.replace(/(?:\\.r\\d+)?(\\.[a-z]+)$/, revision === 0 ? '$1' : `.r${revision}$1`)\n\n/** A variant as its server reads it. */\nexport interface Variant {\n readonly width: number\n readonly format: Format\n /** None: the encoder's own default. */\n readonly quality: Option.Option<number>\n}\n\n/**\n * Every variant a server will make: the widths, the formats and the qualities\n * it accepts, and the Schema that reads a variant's spelling against them. A\n * request outside it is refused before any work, so an original has at most\n * `size` variants, whoever asks.\n */\nexport interface Space {\n readonly widths: Widths.Widths\n readonly formats: ReadonlyArray<Format>\n /** Qualities a URL may name; empty, no URL names one. */\n readonly qualities: ReadonlyArray<number>\n /**\n * The generation of what its variants are: raised when the output changes (the encoder's\n * settings, its resizing), so a changed variant has a new URL rather than new bytes behind\n * an old one. 0 writes no revision.\n */\n readonly revision: number\n /** `w640.avif`, `w640q75.webp` or `w640.r1.avif`, decoded to a `Variant` of this space's revision. */\n readonly schema: Schema.Codec<Variant, string>\n /** How many variants one original can have. */\n readonly size: number\n}\n\nconst distinct = <A>(label: string, values: ReadonlyArray<A>) => {\n if (new Set(values).size !== values.length)\n throw new Error(`Variant.space: a ${label} appears twice`)\n}\n\n/**\n * A space from its ladders. Refuses no formats, a repeated format or\n * quality, and a quality outside 1 to 100.\n */\nexport const space = (\n options: {\n readonly widths?: Widths.Widths\n readonly formats?: ReadonlyArray<Format>\n readonly qualities?: ReadonlyArray<number>\n readonly revision?: number\n } = {},\n): Space => {\n const {\n widths = Widths.standard,\n formats = ['avif', 'webp'],\n qualities = [],\n revision = 0,\n } = options\n if (!(Number.isInteger(revision) && revision >= 0 && revision <= 9999)) {\n throw new Error(`Variant.space: revision ${revision} is not an integer from 0 to 9999`)\n }\n const unspellableWidth = widths.values.find(width => width > 99_999)\n if (unspellableWidth !== undefined) {\n throw new Error(`Variant.space: width ${unspellableWidth} cannot be spelled in a variant URL`)\n }\n if (formats.length === 0) throw new Error('Variant.space: a space needs at least one format')\n distinct('format', formats)\n distinct('quality', qualities)\n for (const quality of qualities) {\n if (!Schema.is(Quality)(quality)) {\n throw new Error(`Variant.space: quality ${quality} is not an integer from 1 to 100`)\n }\n }\n const schema = Spelling.check(\n Schema.makeFilter(spelling => revisionOf(spelling) === revision || `not revision ${revision}`),\n ).pipe(\n Schema.decodeTo(\n Schema.Struct({\n width: widths.Schema,\n format: Schema.Literals(formats),\n quality: Schema.Option(Schema.Literals(qualities)),\n }),\n {\n decode: SchemaGetter.transform(spelling => {\n const [, width, quality, , format] = SPELLING.exec(spelling)!\n return {\n width: Number(width),\n // The spelling's pattern admits only formats; the struct checks this space's.\n format: format as Format,\n quality: Option.map(Option.fromNullishOr(quality), Number),\n }\n }),\n encode: SchemaGetter.transform(\n ({ width, format, quality }) =>\n `w${width}${Option.match(quality, { onNone: () => '', onSome: value => `q${value}` })}${revision === 0 ? '' : `.r${revision}`}.${format}`,\n ),\n },\n ),\n )\n return {\n widths,\n formats,\n qualities,\n revision,\n schema,\n size: widths.values.length * formats.length * (1 + qualities.length),\n }\n}\n\n/** The standard ladder, AVIF and WebP, and no quality in any URL: 16 variants an original. */\nexport const standard: Space = space()\n","import { Option, Schema } from 'effect'\nimport { ContentHash } from './variant.js'\n\n// A placeholder's color lands in a style the page writes, so it is a color\n// and nothing else: no `;`, no `url(`, no second declaration.\nconst CSS_COLOR =\n /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\\([0-9a-z%.,\\s/+-]*\\))$/i\n\nconst coefficientCount = (x: number, y: number): number => {\n let count = 0\n for (let cy = 0; cy < y; cy++)\n for (let cx = cy === 0 ? 1 : 0; cx * y < x * (y - cy); cx++) count++\n return count\n}\n\n// A ThumbHash's header decides exactly how many coefficient bytes follow it.\n// Checking that layout here keeps malformed stored data out of the renderer.\nconst isThumbHash = (encoded: string): boolean => {\n try {\n const bytes = Uint8Array.from(atob(encoded), character => character.charCodeAt(0))\n if (bytes.length < 5) return false\n const hasAlpha = (bytes[2]! & 0x80) !== 0\n const landscape = (bytes[4]! & 0x80) !== 0\n const shorter = bytes[3]! & 7\n if (shorter === 0) return false\n const long = hasAlpha ? 5 : 7\n const lx = landscape ? long : shorter\n const ly = landscape ? shorter : long\n const coefficients =\n coefficientCount(lx, ly) +\n coefficientCount(3, 3) * 2 +\n (hasAlpha ? coefficientCount(5, 5) : 0)\n return bytes.length === (hasAlpha ? 6 : 5) + Math.ceil(coefficients / 2)\n } catch {\n return false\n }\n}\n\n/** What stands in an image's place until it loads. */\nexport const Placeholder = Schema.TaggedUnion({\n /** A flat color, such as one taken from a logo. */\n Color: { value: Schema.String.check(Schema.isPattern(CSS_COLOR)) },\n /** A ThumbHash: a blurred likeness, alpha and aspect ratio included. */\n ThumbHash: {\n hash: Schema.String.check(\n Schema.makeFilter(encoded => isThumbHash(encoded) || 'not a valid ThumbHash'),\n ),\n },\n /** The provider's smallest width of the image itself, scaled up. */\n LowRes: {},\n})\nexport type Placeholder = typeof Placeholder.Type\n\nconst Pixels = Schema.Int.check(Schema.isGreaterThan(0))\n\nconst Share = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 }))\n\n/** Where an image's subject is, from its top left (0, 0) to its bottom right (1, 1). */\nexport const Focus = Schema.Struct({ x: Share, y: Share })\nexport type Focus = typeof Focus.Type\n\n/**\n * The facts of one original image, derived from it once and stored beside it.\n * `key` is where the original lives, as its provider reads it. `hash` is the\n * original's content hash, absent for an image never read; `alpha` says\n * whether it has transparent pixels. `focus`, the one fact an editor sets\n * rather than one derived, is where a crop keeps the subject; a stored asset\n * without it reads as none.\n */\nexport const ImageAsset = Schema.Struct({\n key: Schema.String.check(Schema.isNonEmpty()),\n width: Pixels,\n height: Pixels,\n alpha: Schema.Boolean,\n hash: Schema.OptionFromNullOr(ContentHash),\n placeholder: Schema.OptionFromNullOr(Placeholder),\n focus: Schema.OptionFromOptionalNullOr(Focus),\n})\nexport type ImageAsset = typeof ImageAsset.Type\n\n/**\n * Facts that name the original by its content hash: what a build or an upload\n * answers, and what `Provider.hosted` needs to write a URL.\n */\nexport type HashedAsset = ImageAsset & { readonly hash: Option.Some<string> }\n\nexport const isHashed = (asset: ImageAsset): asset is HashedAsset => Option.isSome(asset.hash)\n\n/** `ImageAsset`, refusing facts with no content hash. */\nexport const HashedAsset = ImageAsset.pipe(Schema.refine(isHashed))\n","import { Context, Effect, Option } from 'effect'\nimport { rgbaToThumbHash } from 'thumbhash'\nimport { Placeholder, type ImageAsset } from './asset.js'\nimport type { OriginalTooLarge, TransformFailed } from './server/errors.js'\n\n/** A picture at most 100 pixels a side, as raw RGBA: what a ThumbHash is made from. */\nexport interface Thumbnail {\n readonly width: number\n readonly height: number\n readonly rgba: Uint8Array\n}\n\n/** What an inspector reads of an original. */\nexport interface Inspected {\n readonly width: number\n readonly height: number\n /** Whether it may have transparent pixels; an inspector that cannot tell says yes. */\n readonly alpha: boolean\n /** None where the inspector cannot make one (the Images binding offline makes no raw pixels). */\n readonly thumbnail: Option.Option<Thumbnail>\n}\n\n/** Reads an original's facts: its size, its alpha, and a thumbnail. */\nexport class Inspector extends Context.Service<\n Inspector,\n {\n readonly inspect: (\n bytes: Uint8Array<ArrayBuffer>,\n ) => Effect.Effect<Inspected, TransformFailed | OriginalTooLarge>\n }\n>()('foldkit-media/Inspector') {}\n\nconst hex = (buffer: ArrayBuffer) =>\n Array.from(new Uint8Array(buffer), byte => byte.toString(16).padStart(2, '0')).join('')\n\nconst base64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes))\n\n/**\n * An original's facts, as an `ImageAsset` under `key`: its size and alpha\n * from the `Inspector`, its SHA-256, and a ThumbHash placeholder where the\n * inspector made a thumbnail. Where an original enters (an upload, a build, a\n * page's content naming a URL), so its facts are derived once and stored.\n */\nexport const describe = (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n): Effect.Effect<ImageAsset, TransformFailed | OriginalTooLarge, Inspector> =>\n Effect.gen(function* () {\n const inspected = yield* Inspector.use(inspector => inspector.inspect(bytes))\n const digest = yield* Effect.promise(() => crypto.subtle.digest('SHA-256', bytes))\n return {\n key,\n width: inspected.width,\n height: inspected.height,\n alpha: inspected.alpha,\n hash: Option.some(hex(digest)),\n placeholder: Option.map(inspected.thumbnail, ({ width, height, rgba }) =>\n Placeholder.cases.ThumbHash.make({ hash: base64(rgbaToThumbHash(width, height, rgba)) }),\n ),\n focus: Option.none(),\n }\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAUA,MAAa,OAAO;;AAGpB,MAAa,cAAc,OAAO,OAAO,MAAM,OAAO,UAAU,gBAAgB,CAAC;;AAGjF,MAAa,UAAU,OAAO,IAAI,MAAM,OAAO,UAAU;CAAE,SAAS;CAAG,SAAS;AAAI,CAAC,CAAC;AAItF,MAAM,WAAW;;;;;AAMjB,MAAa,WAAW,OAAO,OAAO,MAAM,OAAO,UAAU,QAAQ,CAAC;;AAGtE,MAAa,cAAc,aAA6B,OAAO,SAAS,KAAK,QAAQ,CAAC,GAAG,MAAM,CAAC;;AAGhG,MAAa,WAAW,UAAkB,aACxC,SAAS,QAAQ,0BAA0B,aAAa,IAAI,OAAO,KAAK,SAAS,GAAG;AAiCtF,MAAM,YAAe,OAAe,WAA6B;CAC/D,IAAI,IAAI,IAAI,MAAM,CAAC,CAAC,SAAS,OAAO,QAClC,MAAM,IAAI,MAAM,oBAAoB,MAAM,eAAe;AAC7D;;;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F;EACA,OAAO,OAAO,KAAK;CACrB;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"describe-C6sWA_8p.mjs","names":["Widths.standard"],"sources":["../src/variant.ts","../src/asset.ts","../src/describe.ts"],"sourcesContent":["import { Option, Schema, SchemaGetter } from 'effect'\nimport { Format } from './format.js'\nimport * as Widths from './widths.js'\n\n/**\n * Where a hosted variant lives: the original's content hash, then the variant.\n * The server routes this path and `Provider.hosted` fills it in, so the two\n * read one string. It ends in the format's extension, so a variant written\n * out as a file is served with its type by any static host.\n */\nexport const PATH = '/_image/:hash/:variant'\n\n/** An original's SHA-256, in lowercase hex: its name in the store. */\nexport const ContentHash = Schema.String.check(Schema.isPattern(/^[0-9a-f]{64}$/))\n\n/** A quality from 1 to 100. */\nexport const Quality = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 100 }))\n\n// No leading zero anywhere: one request has one spelling, so one cache key. The output's\n// revision is written only above 0, so every URL written before revisions keeps its spelling.\nconst SPELLING = /^w([1-9]\\d{0,4})(?:q([1-9]\\d?|100))?(?:\\.r([1-9]\\d{0,3}))?\\.(avif|webp|jpeg|png)$/\n\n/**\n * The grammar every release reads, whatever its space: a spelling it matches\n * may be one another release offers, so refusing it says nothing for good.\n */\nexport const Spelling = Schema.String.check(Schema.isPattern(SPELLING))\n\n/** The output revision a spelling names: `w640.r2.avif` is 2, and one naming none is 0. */\nexport const revisionOf = (spelling: string): number => Number(SPELLING.exec(spelling)?.[3] ?? 0)\n\n/** `spelling` at `revision`: the same variant, as that revision writes it. */\nexport const respell = (spelling: string, revision: number): string =>\n spelling.replace(/(?:\\.r\\d+)?(\\.[a-z]+)$/, revision === 0 ? '$1' : `.r${revision}$1`)\n\n/** A variant as its server reads it. */\nexport interface Variant {\n readonly width: number\n readonly format: Format\n /** None: the encoder's own default. */\n readonly quality: Option.Option<number>\n}\n\n/**\n * Every variant a server will make: the widths, the formats and the qualities\n * it accepts, and the Schema that reads a variant's spelling against them. A\n * request outside it is refused before any work, so an original has at most\n * `size` variants, whoever asks.\n */\nexport interface Space {\n readonly widths: Widths.Widths\n readonly formats: ReadonlyArray<Format>\n /** Qualities a URL may name; empty, no URL names one. */\n readonly qualities: ReadonlyArray<number>\n /**\n * The generation of what its variants are: raised when the output changes (the encoder's\n * settings, its resizing), so a changed variant has a new URL rather than new bytes behind\n * an old one. 0 writes no revision.\n */\n readonly revision: number\n /** `w640.avif`, `w640q75.webp` or `w640.r1.avif`, decoded to a `Variant` of this space's revision. */\n readonly schema: Schema.Codec<Variant, string>\n /** How many variants one original can have. */\n readonly size: number\n}\n\nconst distinct = <A>(label: string, values: ReadonlyArray<A>) => {\n if (new Set(values).size !== values.length)\n throw new Error(`Variant.space: a ${label} appears twice`)\n}\n\n/**\n * A space from its ladders. Refuses no formats, a repeated format or\n * quality, and a quality outside 1 to 100.\n */\nexport const space = (\n options: {\n readonly widths?: Widths.Widths\n readonly formats?: ReadonlyArray<Format>\n readonly qualities?: ReadonlyArray<number>\n readonly revision?: number\n } = {},\n): Space => {\n const {\n widths = Widths.standard,\n formats = ['avif', 'webp'],\n qualities = [],\n revision = 0,\n } = options\n if (!(Number.isInteger(revision) && revision >= 0 && revision <= 9999)) {\n throw new Error(`Variant.space: revision ${revision} is not an integer from 0 to 9999`)\n }\n const unspellableWidth = widths.values.find(width => width > 99_999)\n if (unspellableWidth !== undefined) {\n throw new Error(`Variant.space: width ${unspellableWidth} cannot be spelled in a variant URL`)\n }\n if (formats.length === 0) throw new Error('Variant.space: a space needs at least one format')\n distinct('format', formats)\n distinct('quality', qualities)\n for (const quality of qualities) {\n if (!Schema.is(Quality)(quality)) {\n throw new Error(`Variant.space: quality ${quality} is not an integer from 1 to 100`)\n }\n }\n const schema = Spelling.check(\n Schema.makeFilter(spelling => revisionOf(spelling) === revision || `not revision ${revision}`),\n ).pipe(\n Schema.decodeTo(\n Schema.Struct({\n width: widths.Schema,\n format: Schema.Literals(formats),\n quality: Schema.Option(Schema.Literals(qualities)),\n }),\n {\n decode: SchemaGetter.transform(spelling => {\n const [, width, quality, , format] = SPELLING.exec(spelling)!\n return {\n width: Number(width),\n // The spelling's pattern admits only formats; the struct checks this space's.\n format: format as Format,\n quality: Option.map(Option.fromNullishOr(quality), Number),\n }\n }),\n encode: SchemaGetter.transform(\n ({ width, format, quality }) =>\n `w${width}${Option.match(quality, { onNone: () => '', onSome: value => `q${value}` })}${revision === 0 ? '' : `.r${revision}`}.${format}`,\n ),\n },\n ),\n )\n return {\n widths,\n formats,\n qualities,\n revision,\n schema,\n size: widths.values.length * formats.length * (1 + qualities.length),\n }\n}\n\n/** The standard ladder, AVIF and WebP, and no quality in any URL: 16 variants an original. */\nexport const standard: Space = space()\n","import { Option, Schema } from 'effect'\nimport { ContentHash } from './variant.js'\n\n// A placeholder's color lands in a style the page writes, so it is a color\n// and nothing else: no `;`, no `url(`, no second declaration.\nconst CSS_COLOR =\n /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\\([0-9a-z%.,\\s/+-]*\\))$/i\n\nconst coefficientCount = (x: number, y: number): number => {\n let count = 0\n for (let cy = 0; cy < y; cy++)\n for (let cx = cy === 0 ? 1 : 0; cx * y < x * (y - cy); cx++) count++\n return count\n}\n\n// A ThumbHash's header decides exactly how many coefficient bytes follow it.\n// Checking that layout here keeps malformed stored data out of the renderer.\nconst isThumbHash = (encoded: string): boolean => {\n try {\n const bytes = Uint8Array.from(atob(encoded), character => character.charCodeAt(0))\n if (bytes.length < 5) return false\n const hasAlpha = (bytes[2]! & 0x80) !== 0\n const landscape = (bytes[4]! & 0x80) !== 0\n const shorter = bytes[3]! & 7\n if (shorter === 0) return false\n const long = hasAlpha ? 5 : 7\n const lx = landscape ? long : shorter\n const ly = landscape ? shorter : long\n const coefficients =\n coefficientCount(lx, ly) +\n coefficientCount(3, 3) * 2 +\n (hasAlpha ? coefficientCount(5, 5) : 0)\n return bytes.length === (hasAlpha ? 6 : 5) + Math.ceil(coefficients / 2)\n } catch {\n return false\n }\n}\n\n/** What stands in an image's place until it loads. */\nexport const Placeholder = Schema.TaggedUnion({\n /** A flat color, such as one taken from a logo. */\n Color: { value: Schema.String.check(Schema.isPattern(CSS_COLOR)) },\n /** A ThumbHash: a blurred likeness, alpha and aspect ratio included. */\n ThumbHash: {\n hash: Schema.String.check(\n Schema.makeFilter(encoded => isThumbHash(encoded) || 'not a valid ThumbHash'),\n ),\n },\n /** The provider's smallest width of the image itself, scaled up. */\n LowRes: {},\n})\nexport type Placeholder = typeof Placeholder.Type\n\nconst Pixels = Schema.Int.check(Schema.isGreaterThan(0))\n\nconst Share = Schema.Finite.check(Schema.isBetween({ minimum: 0, maximum: 1 }))\n\n/** Where an image's subject is, from its top left (0, 0) to its bottom right (1, 1). */\nexport const Focus = Schema.Struct({ x: Share, y: Share })\nexport type Focus = typeof Focus.Type\n\n/**\n * The facts of one original image, derived from it once and stored beside it.\n * `key` is where the original lives, as its provider reads it. `hash` is the\n * original's content hash, absent for an image never read; `alpha` says\n * whether it has transparent pixels. `focus`, the one fact an editor sets\n * rather than one derived, is where a crop keeps the subject; a stored asset\n * without it reads as none.\n */\nexport const ImageAsset = Schema.Struct({\n key: Schema.String.check(Schema.isNonEmpty()),\n width: Pixels,\n height: Pixels,\n alpha: Schema.Boolean,\n hash: Schema.OptionFromNullOr(ContentHash),\n placeholder: Schema.OptionFromNullOr(Placeholder),\n focus: Schema.OptionFromOptionalNullOr(Focus),\n})\nexport type ImageAsset = typeof ImageAsset.Type\n\n/**\n * Facts that name the original by its content hash: what a build or an upload\n * answers, and what `Provider.hosted` needs to write a URL.\n */\nexport type HashedAsset = ImageAsset & { readonly hash: Option.Some<string> }\n\nexport const isHashed = (asset: ImageAsset): asset is HashedAsset => Option.isSome(asset.hash)\n\n/** `ImageAsset`, refusing facts with no content hash. */\nexport const HashedAsset = ImageAsset.pipe(Schema.refine(isHashed))\n","import { Context, Effect, Option } from 'effect'\nimport { rgbaToThumbHash } from 'thumbhash'\nimport { Placeholder, type ImageAsset } from './asset.js'\nimport type { OriginalTooLarge, TransformFailed } from './server/errors.js'\n\n/** A picture at most 100 pixels a side, as raw RGBA: what a ThumbHash is made from. */\nexport interface Thumbnail {\n readonly width: number\n readonly height: number\n readonly rgba: Uint8Array\n}\n\n/** What an inspector reads of an original. */\nexport interface Inspected {\n readonly width: number\n readonly height: number\n /** Whether it may have transparent pixels; an inspector that cannot tell says yes. */\n readonly alpha: boolean\n /** None where the inspector cannot make one (the Images binding offline makes no raw pixels). */\n readonly thumbnail: Option.Option<Thumbnail>\n}\n\n/** Reads an original's facts: its size, its alpha, and a thumbnail. */\nexport class Inspector extends Context.Service<\n Inspector,\n {\n readonly inspect: (\n bytes: Uint8Array<ArrayBuffer>,\n ) => Effect.Effect<Inspected, TransformFailed | OriginalTooLarge>\n }\n>()('foldkit-media/Inspector') {}\n\nconst hex = (buffer: ArrayBuffer) =>\n Array.from(new Uint8Array(buffer), byte => byte.toString(16).padStart(2, '0')).join('')\n\nconst base64 = (bytes: Uint8Array) => btoa(String.fromCharCode(...bytes))\n\n/**\n * An original's facts, as an `ImageAsset` under `key`: its size and alpha\n * from the `Inspector`, its SHA-256, and a ThumbHash placeholder where the\n * inspector made a thumbnail. Where an original enters (an upload, a build, a\n * page's content naming a URL), so its facts are derived once and stored.\n */\nexport const describe = (\n key: string,\n bytes: Uint8Array<ArrayBuffer>,\n): Effect.Effect<ImageAsset, TransformFailed | OriginalTooLarge, Inspector> =>\n Effect.gen(function* () {\n const inspected = yield* Inspector.use(inspector => inspector.inspect(bytes))\n const digest = yield* Effect.promise(() => crypto.subtle.digest('SHA-256', bytes))\n return {\n key,\n width: inspected.width,\n height: inspected.height,\n alpha: inspected.alpha,\n hash: Option.some(hex(digest)),\n placeholder: Option.map(inspected.thumbnail, ({ width, height, rgba }) =>\n Placeholder.cases.ThumbHash.make({ hash: base64(rgbaToThumbHash(width, height, rgba)) }),\n ),\n focus: Option.none(),\n }\n })\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;A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S,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;AAExF,MAAM,UAAU,UAAsB,KAAK,OAAO,aAAa,GAAG,KAAK,CAAC;;;;;;;AAQxE,MAAa,YACX,KACA,UAEA,OAAO,IAAI,aAAa;CACtB,MAAM,YAAY,OAAO,UAAU,KAAI,cAAa,UAAU,QAAQ,KAAK,CAAC;CAC5E,MAAM,SAAS,OAAO,OAAO,cAAc,OAAO,OAAO,OAAO,WAAW,KAAK,CAAC;CACjF,OAAO;EACL;EACA,OAAO,UAAU;EACjB,QAAQ,UAAU;EAClB,OAAO,UAAU;EACjB,MAAM,OAAO,KAAK,IAAI,MAAM,CAAC;EAC7B,aAAa,OAAO,IAAI,UAAU,YAAY,EAAE,OAAO,QAAQ,WAC7D,YAAY,MAAM,UAAU,KAAK,EAAE,MAAM,OAAO,gBAAgB,OAAO,QAAQ,IAAI,CAAC,EAAE,CAAC,CACzF;EACA,OAAO,OAAO,KAAK;CACrB;AACF,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
|
-
|
|
2
|
+
// src/server/errors.ts
|
|
3
3
|
/** No original is stored under this hash. */
|
|
4
4
|
var OriginalNotFound = class extends Schema.TaggedError()("OriginalNotFound", { hash: Schema.String }, { httpApiStatus: 404 }) {};
|
|
5
5
|
/** The original is larger than the server will read: in bytes, or in pixels once decoded. */
|
|
@@ -15,7 +15,6 @@ var OriginalTooLarge = class extends Schema.TaggedError()("OriginalTooLarge", {
|
|
|
15
15
|
var TransformFailed = class extends Schema.TaggedError()("TransformFailed", {}, { httpApiStatus: 502 }) {};
|
|
16
16
|
/** The host's transformation allowance is spent; variants already made still serve. */
|
|
17
17
|
var QuotaExhausted = class extends Schema.TaggedError()("QuotaExhausted", {}, { httpApiStatus: 503 }) {};
|
|
18
|
-
//#endregion
|
|
19
18
|
export { TransformFailed as i, OriginalTooLarge as n, QuotaExhausted as r, OriginalNotFound as t };
|
|
20
19
|
|
|
21
|
-
//# sourceMappingURL=errors-
|
|
20
|
+
//# sourceMappingURL=errors-BhEgXJ4m.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors-
|
|
1
|
+
{"version":3,"file":"errors-BhEgXJ4m.mjs","names":[],"sources":["../src/server/errors.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** No original is stored under this hash. */\nexport class OriginalNotFound extends Schema.TaggedError<OriginalNotFound>()(\n 'OriginalNotFound',\n { hash: Schema.String },\n { httpApiStatus: 404 },\n) {}\n\n/** The original is larger than the server will read: in bytes, or in pixels once decoded. */\nexport class OriginalTooLarge extends Schema.TaggedError<OriginalTooLarge>()(\n 'OriginalTooLarge',\n { size: Schema.Number, limit: Schema.Number, unit: Schema.Literals(['bytes', 'pixels']) },\n { httpApiStatus: 413 },\n) {}\n\n/**\n * The transformer could not make the variant: the original is not an image it\n * reads, or it failed. Its reason stays in the server's log, not the response.\n */\nexport class TransformFailed extends Schema.TaggedError<TransformFailed>()(\n 'TransformFailed',\n {},\n { httpApiStatus: 502 },\n) {}\n\n/** The host's transformation allowance is spent; variants already made still serve. */\nexport class QuotaExhausted extends Schema.TaggedError<QuotaExhausted>()(\n 'QuotaExhausted',\n {},\n { httpApiStatus: 503 },\n) {}\n"],"mappings":";;;AAGA,IAAa,mBAAb,cAAsC,OAAO,YAA8B,CAAC,CAC1E,oBACA,EAAE,MAAM,OAAO,OAAO,GACtB,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;AAGH,IAAa,mBAAb,cAAsC,OAAO,YAA8B,CAAC,CAC1E,oBACA;CAAE,MAAM,OAAO;CAAQ,OAAO,OAAO;CAAQ,MAAM,OAAO,SAAS,CAAC,SAAS,QAAQ,CAAC;AAAE,GACxF,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;;;;AAMH,IAAa,kBAAb,cAAqC,OAAO,YAA6B,CAAC,CACxE,mBACA,CAAC,GACD,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC;;AAGH,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CACtE,kBACA,CAAC,GACD,EAAE,eAAe,IAAI,CACvB,CAAC,CAAC,CAAC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
|
-
|
|
2
|
+
// src/format.ts
|
|
3
3
|
/** An encoding a variant can be written in. */
|
|
4
4
|
const Format = Schema.Literals([
|
|
5
5
|
"avif",
|
|
@@ -15,7 +15,6 @@ const mimeTypes = {
|
|
|
15
15
|
};
|
|
16
16
|
/** The media type a `source` element names. */
|
|
17
17
|
const mimeType = (format) => mimeTypes[format];
|
|
18
|
-
//#endregion
|
|
19
18
|
export { mimeType as n, Format as t };
|
|
20
19
|
|
|
21
|
-
//# sourceMappingURL=format-
|
|
20
|
+
//# sourceMappingURL=format-BCRTFU9j.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format-
|
|
1
|
+
{"version":3,"file":"format-BCRTFU9j.mjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { Schema } from 'effect'\n\n/** An encoding a variant can be written in. */\nexport const Format = Schema.Literals(['avif', 'webp', 'jpeg', 'png'])\nexport type Format = typeof Format.Type\n\n/**\n * What a provider is asked for: a format, or `auto` for a provider that picks\n * the format itself from the request's `Accept`.\n */\nexport type Encoding = Format | 'auto'\n\nconst mimeTypes: Readonly<Record<Format, string>> = {\n avif: 'image/avif',\n webp: 'image/webp',\n jpeg: 'image/jpeg',\n png: 'image/png',\n}\n\n/** The media type a `source` element names. */\nexport const mimeType = (format: Format): string => mimeTypes[format]\n"],"mappings":";;;AAGA,MAAa,SAAS,OAAO,SAAS;CAAC;CAAQ;CAAQ;CAAQ;AAAK,CAAC;AASrE,MAAM,YAA8C;CAClD,MAAM;CACN,MAAM;CACN,MAAM;CACN,KAAK;AACP;;AAGA,MAAa,YAAY,WAA2B,UAAU"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-
|
|
2
|
-
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
|
+
// src/icon.ts
|
|
3
3
|
var icon_exports = /* @__PURE__ */ __exportAll({
|
|
4
4
|
TAGS: () => TAGS,
|
|
5
5
|
draw: () => draw,
|
|
@@ -179,7 +179,6 @@ const draw = (icon, h, options = {}) => {
|
|
|
179
179
|
...written(attributes)
|
|
180
180
|
], nodes.map(drawn));
|
|
181
181
|
};
|
|
182
|
-
//#endregion
|
|
183
182
|
export { icon_exports as n, TAGS as t };
|
|
184
183
|
|
|
185
|
-
//# sourceMappingURL=icon-
|
|
184
|
+
//# sourceMappingURL=icon-0A2dBtqj.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icon-CowP8fQ0.mjs","names":[],"sources":["../src/icon.ts"],"sourcesContent":["/**\n * An icon as data: what a build reads from an icon set or an SVG file, parsed\n * (`foldkit-media/icons`), not markup to set as HTML. A view draws it\n * (`draw`), and a style masks with it (`maskUrl`),\n * from the one value.\n */\n\n/** The elements an icon may hold: presentational SVG, nothing that runs, loads or holds text. */\nexport const TAGS = [\n 'g',\n 'path',\n 'circle',\n 'ellipse',\n 'rect',\n 'line',\n 'polyline',\n 'polygon',\n 'defs',\n 'linearGradient',\n 'radialGradient',\n 'stop',\n 'clipPath',\n 'mask',\n 'use',\n] as const\nexport type SvgTag = (typeof TAGS)[number]\n\n/** One element of an icon's drawing, and its children. */\nexport interface SvgNode {\n readonly tag: SvgTag\n readonly attributes: Readonly<Record<string, string>>\n readonly children: ReadonlyArray<SvgNode>\n}\n\n/** An icon: its `viewBox`, the attributes its root `svg` carries (its fill and stroke), and its drawing. */\nexport interface IconData {\n readonly viewBox: string\n readonly attributes: Readonly<Record<string, string>>\n readonly nodes: ReadonlyArray<SvgNode>\n}\n\nconst escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>')\n\nconst attributesOf = (attributes: Readonly<Record<string, string>>): string =>\n Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('')\n\nconst nodeMarkup = ({ tag, attributes, children }: SvgNode): string =>\n children.length === 0\n ? `<${tag}${attributesOf(attributes)}/>`\n : `<${tag}${attributesOf(attributes)}>${children.map(nodeMarkup).join('')}</${tag}>`\n\n/** The icon as one standalone `svg` document. */\nexport const serialize = (icon: IconData): string =>\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"${escapeAttribute(icon.viewBox)}\"${attributesOf(icon.attributes)}>${icon.nodes.map(nodeMarkup).join('')}</svg>`\n\n/**\n * The icon as a CSS `url()`, for a mask (`Icons.byAttribute`, `Icons.glyph`):\n * a mask reads only the drawing's shape, so its colours do not matter, and\n * the element it masks paints in `currentColor`.\n */\nexport const maskUrl = (icon: IconData): string =>\n // Only what a data URL in a quoted CSS `url()` cannot hold is escaped (a line break ends a CSS\n // string): a theme writes every chrome icon this way, and escaping the spaces, `=` and `/`\n // too adds a quarter to each.\n `url(\"data:image/svg+xml,${serialize(icon).replace(/[%#<>\"\\n\\r\\t]/g, unsafe => `%${unsafe.charCodeAt(0).toString(16).padStart(2, '0').toUpperCase()}`)}\")`\n\nconst keys = new WeakMap<IconData, string>()\n\n/**\n * A short name for the icon, from its content: the same drawing has the same\n * key on a server and in the browser, and two drawings almost never share\n * one. A drawing's ids are prefixed with it, and a sprite names its symbol by it.\n */\nexport const key = (icon: IconData): string => {\n const known = keys.get(icon)\n if (known !== undefined) return known\n // 64-bit FNV-1a over the serialized drawing.\n let hash = 0xcbf29ce484222325n\n for (const unit of serialize(icon)) {\n hash ^= BigInt(unit.codePointAt(0)!)\n hash = BigInt.asUintN(64, hash * 0x100000001b3n)\n }\n const made = `i${hash.toString(36)}`\n keys.set(icon, made)\n return made\n}\n\nconst idsOf = (nodes: ReadonlyArray<SvgNode>, into: Set<string>): Set<string> => {\n for (const node of nodes) {\n if (node.attributes['id'] !== undefined) into.add(node.attributes['id'])\n idsOf(node.children, into)\n }\n return into\n}\n\ninterface Prefixed {\n readonly ids: ReadonlySet<string>\n readonly byPrefix: Map<string, IconData>\n}\n\nconst prefixed = new WeakMap<IconData, Prefixed>()\n\nconst idPrefix = (prefix: string): string => {\n if (/^(?!fk_)[A-Za-z0-9_-]+$/.test(prefix)) return prefix\n let encoded = ''\n for (let at = 0; at < prefix.length; at++) {\n encoded += prefix.charCodeAt(at).toString(16).padStart(4, '0')\n }\n return `fk_${encoded}`\n}\n\n/**\n * The icon with each id it defines, and each `href` and `url()` naming one,\n * prefixed: two icons drawn inline on one page share the document's ids, and\n * an exported SVG's `id=\"a\"` would otherwise paint another icon's gradient.\n * A prefix outside an identifier's safe characters is encoded before it\n * reaches a CSS `url()`. An icon with no ids is returned as it was given.\n * Kept per icon and prefix, since a view asks again on every render.\n */\nexport const prefixIds = (icon: IconData, prefix: string): IconData => {\n const memo = prefixed.get(icon) ?? { ids: idsOf(icon.nodes, new Set()), byPrefix: new Map() }\n prefixed.set(icon, memo)\n const { ids, byPrefix } = memo\n if (ids.size === 0) return icon\n const known = byPrefix.get(prefix)\n if (known !== undefined) return known\n const writtenPrefix = idPrefix(prefix)\n const rename = (id: string) => (ids.has(id) ? `${writtenPrefix}-${id}` : id)\n const rewriteValue = (name: string, value: string): string => {\n if (name === 'id') return rename(value)\n // The parser admits only a fragment `href`.\n if (name === 'href') return `#${rename(value.slice(1))}`\n return value.replace(\n /url\\(\\s*(['\"]?)#([^)'\"\\s]*)\\1\\s*\\)/gi,\n (_, quote: string, id: string) => `url(${quote}#${rename(id)}${quote})`,\n )\n }\n const rewrite = (attributes: Readonly<Record<string, string>>) =>\n Object.fromEntries(\n Object.entries(attributes).map(([name, value]) => [name, rewriteValue(name, value)]),\n )\n const walk = (node: SvgNode): SvgNode => ({\n tag: node.tag,\n attributes: rewrite(node.attributes),\n children: node.children.map(walk),\n })\n const made: IconData = {\n viewBox: icon.viewBox,\n attributes: rewrite(icon.attributes),\n nodes: icon.nodes.map(walk),\n }\n byPrefix.set(prefix, made)\n return made\n}\n\n/** How a drawing's strokes are drawn: their width, and whether their ends and joins are round. */\nexport interface Stroke {\n readonly width?: number | undefined\n readonly corners?: 'round' | 'square' | undefined\n}\n\n/**\n * The icon with its strokes redrawn: every `stroke-width`, `stroke-linecap`\n * and `stroke-linejoin` it sets replaced, or set on its root where it sets\n * none. A filled icon draws no stroke, so it is unchanged in what shows. For\n * a mask, whose drawing CSS cannot reach once it is a `url()`.\n */\nexport const withStroke = (icon: IconData, stroke: Stroke): IconData => {\n const set: Record<string, string> = {}\n if (stroke.width !== undefined) set['stroke-width'] = String(stroke.width)\n if (stroke.corners !== undefined) {\n set['stroke-linecap'] = stroke.corners\n set['stroke-linejoin'] = stroke.corners === 'round' ? 'round' : 'miter'\n }\n const names = Object.keys(set)\n const found = new Set<string>()\n const restroke = (attributes: Readonly<Record<string, string>>) => {\n const written = { ...attributes }\n for (const name of names) {\n if (Object.hasOwn(attributes, name)) {\n written[name] = set[name]!\n found.add(name)\n }\n }\n return written\n }\n const walk = (node: SvgNode): SvgNode => ({\n tag: node.tag,\n attributes: restroke(node.attributes),\n children: node.children.map(walk),\n })\n const nodes = icon.nodes.map(walk)\n const attributes = restroke(icon.attributes)\n // A property the drawing never sets is set once on the root, which every node inherits.\n for (const name of names) if (!found.has(name)) attributes[name] = set[name]!\n return { viewBox: icon.viewBox, attributes, nodes }\n}\n\ntype Element<Node, Attribute> = (\n attributes: ReadonlyArray<Attribute>,\n children: ReadonlyArray<Node>,\n) => Node\n\n/**\n * What `draw` needs of a view's builder: an element per tag an icon may hold,\n * and raw attributes. Foldkit's `HtmlBuilder` is one, so this package needs\n * no view library of its own.\n */\nexport type SvgBuilder<Node, Attribute> = {\n readonly svg: Element<Node, Attribute>\n readonly Attribute: (name: string, value: string) => Attribute\n readonly AriaHidden: (value: boolean) => Attribute\n} & { readonly [Tag in SvgTag]: Element<Node, Attribute> }\n\n/**\n * The icon as inline SVG, through a view's builder (`h`): `size` square\n * (`1em` unless given, so it stands as tall as its text; `foldkit-mixins-ui`'s\n * `Icon.view` fills its glyph with it), kept so in a squeezed flex row, and\n * hidden from assistive technology,\n * since the control it sits in carries the name. Every attribute is written as\n * an attribute, so a server render writes the same markup. Ids are prefixed by\n * `key(icon)`; `options.key` sets one drawing's ids apart from another of the\n * same icon, since a gradient defined in a copy that is hidden paints nothing\n * for the copy that shows. Each key's drawing is kept for the icon's life, so\n * take keys from a small fixed set (a place on the page), not one per row.\n */\nexport const draw = <Node, Attribute>(\n icon: IconData,\n h: SvgBuilder<Node, Attribute>,\n options: { readonly key?: string; readonly size?: string } = {},\n): Node => {\n const prefix = key(icon) + (options.key === undefined ? '' : `-${options.key}`)\n const { viewBox, attributes, nodes } = prefixIds(icon, prefix)\n const size = options.size ?? '1em'\n const written = (from: Readonly<Record<string, string>>) =>\n Object.entries(from).map(([name, value]) => h.Attribute(name, value))\n const drawn = ({ tag, attributes, children }: SvgNode): Node =>\n h[tag](written(attributes), children.map(drawn))\n return h.svg(\n [\n h.Attribute('viewBox', viewBox),\n h.Attribute('width', size),\n h.Attribute('height', size),\n // A flex row squeezed narrower than its content shrinks an svg to nothing, width or not.\n h.Attribute('style', 'flex-shrink: 0'),\n h.AriaHidden(true),\n ...written(attributes),\n ],\n nodes.map(drawn),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,MAAa,OAAO;CAClB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAiBA,MAAM,mBAAmB,UACvB,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,QAAQ,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;AAEjG,MAAM,gBAAgB,eACpB,OAAO,QAAQ,UAAU,CAAC,CACvB,KAAK,CAAC,MAAM,WAAW,IAAI,KAAK,IA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C,MAAM,WAAW,EAAE,UAAU,MAAM,KAAK,CAAC;CACtE,MAAM,SAAS,EAAE,KAAK,YAAY,eAChC,EAAE,IAAI,CAAC,QAAQ,UAAU,GAAG,SAAS,IAAI,KAAK,CAAC;CACjD,OAAO,EAAE,IACP;EACE,EAAE,UAAU,WAAW,OAAO;EAC9B,EAAE,UAAU,SAAS,IAAI;EACzB,EAAE,UAAU,UAAU,IAAI;EAE1B,EAAE,UAAU,SAAS,gBAAgB;EACrC,EAAE,WAAW,IAAI;EACjB,GAAG,QAAQ,UAAU;CACvB,GACA,MAAM,IAAI,KAAK,CACjB;AACF"}
|
|
1
|
+
{"version":3,"file":"icon-0A2dBtqj.mjs","names":[],"sources":["../src/icon.ts"],"sourcesContent":["/**\n * An icon as data: what a build reads from an icon set or an SVG file, parsed\n * (`foldkit-media/icons`), not markup to set as HTML. A view draws it\n * (`draw`), and a style masks with it (`maskUrl`),\n * from the one value.\n */\n\n/** The elements an icon may hold: presentational SVG, nothing that runs, loads or holds text. */\nexport const TAGS = [\n 'g',\n 'path',\n 'circle',\n 'ellipse',\n 'rect',\n 'line',\n 'polyline',\n 'polygon',\n 'defs',\n 'linearGradient',\n 'radialGradient',\n 'stop',\n 'clipPath',\n 'mask',\n 'use',\n] as const\nexport type SvgTag = (typeof TAGS)[number]\n\n/** One element of an icon's drawing, and its children. */\nexport interface SvgNode {\n readonly tag: SvgTag\n readonly attributes: Readonly<Record<string, string>>\n readonly children: ReadonlyArray<SvgNode>\n}\n\n/** An icon: its `viewBox`, the attributes its root `svg` carries (its fill and stroke), and its drawing. */\nexport interface IconData {\n readonly viewBox: string\n readonly attributes: Readonly<Record<string, string>>\n readonly nodes: ReadonlyArray<SvgNode>\n}\n\nconst escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>')\n\nconst attributesOf = (attributes: Readonly<Record<string, string>>): string =>\n Object.entries(attributes)\n .map(([name, value]) => ` ${name}=\"${escapeAttribute(value)}\"`)\n .join('')\n\nconst nodeMarkup = ({ tag, attributes, children }: SvgNode): string =>\n children.length === 0\n ? `<${tag}${attributesOf(attributes)}/>`\n : `<${tag}${attributesOf(attributes)}>${children.map(nodeMarkup).join('')}</${tag}>`\n\n/** The icon as one standalone `svg` document. */\nexport const serialize = (icon: IconData): string =>\n `<svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"${escapeAttribute(icon.viewBox)}\"${attributesOf(icon.attributes)}>${icon.nodes.map(nodeMarkup).join('')}</svg>`\n\n/**\n * The icon as a CSS `url()`, for a mask (`Icons.byAttribute`, `Icons.glyph`):\n * a mask reads only the drawing's shape, so its colours do not matter, and\n * the element it masks paints in `currentColor`.\n */\nexport const maskUrl = (icon: IconData): string =>\n // Only what a data URL in a quoted CSS `url()` cannot hold is escaped (a line break ends a CSS\n // string): a theme writes every chrome icon this way, and escaping the spaces, `=` and `/`\n // too adds a quarter to each.\n `url(\"data:image/svg+xml,${serialize(icon).replace(/[%#<>\"\\n\\r\\t]/g, unsafe => `%${unsafe.charCodeAt(0).toString(16).padStart(2, '0').toUpperCase()}`)}\")`\n\nconst keys = new WeakMap<IconData, string>()\n\n/**\n * A short name for the icon, from its content: the same drawing has the same\n * key on a server and in the browser, and two drawings almost never share\n * one. A drawing's ids are prefixed with it, and a sprite names its symbol by it.\n */\nexport const key = (icon: IconData): string => {\n const known = keys.get(icon)\n if (known !== undefined) return known\n // 64-bit FNV-1a over the serialized drawing.\n let hash = 0xcbf29ce484222325n\n for (const unit of serialize(icon)) {\n hash ^= BigInt(unit.codePointAt(0)!)\n hash = BigInt.asUintN(64, hash * 0x100000001b3n)\n }\n const made = `i${hash.toString(36)}`\n keys.set(icon, made)\n return made\n}\n\nconst idsOf = (nodes: ReadonlyArray<SvgNode>, into: Set<string>): Set<string> => {\n for (const node of nodes) {\n if (node.attributes['id'] !== undefined) into.add(node.attributes['id'])\n idsOf(node.children, into)\n }\n return into\n}\n\ninterface Prefixed {\n readonly ids: ReadonlySet<string>\n readonly byPrefix: Map<string, IconData>\n}\n\nconst prefixed = new WeakMap<IconData, Prefixed>()\n\nconst idPrefix = (prefix: string): string => {\n if (/^(?!fk_)[A-Za-z0-9_-]+$/.test(prefix)) return prefix\n let encoded = ''\n for (let at = 0; at < prefix.length; at++) {\n encoded += prefix.charCodeAt(at).toString(16).padStart(4, '0')\n }\n return `fk_${encoded}`\n}\n\n/**\n * The icon with each id it defines, and each `href` and `url()` naming one,\n * prefixed: two icons drawn inline on one page share the document's ids, and\n * an exported SVG's `id=\"a\"` would otherwise paint another icon's gradient.\n * A prefix outside an identifier's safe characters is encoded before it\n * reaches a CSS `url()`. An icon with no ids is returned as it was given.\n * Kept per icon and prefix, since a view asks again on every render.\n */\nexport const prefixIds = (icon: IconData, prefix: string): IconData => {\n const memo = prefixed.get(icon) ?? { ids: idsOf(icon.nodes, new Set()), byPrefix: new Map() }\n prefixed.set(icon, memo)\n const { ids, byPrefix } = memo\n if (ids.size === 0) return icon\n const known = byPrefix.get(prefix)\n if (known !== undefined) return known\n const writtenPrefix = idPrefix(prefix)\n const rename = (id: string) => (ids.has(id) ? `${writtenPrefix}-${id}` : id)\n const rewriteValue = (name: string, value: string): string => {\n if (name === 'id') return rename(value)\n // The parser admits only a fragment `href`.\n if (name === 'href') return `#${rename(value.slice(1))}`\n return value.replace(\n /url\\(\\s*(['\"]?)#([^)'\"\\s]*)\\1\\s*\\)/gi,\n (_, quote: string, id: string) => `url(${quote}#${rename(id)}${quote})`,\n )\n }\n const rewrite = (attributes: Readonly<Record<string, string>>) =>\n Object.fromEntries(\n Object.entries(attributes).map(([name, value]) => [name, rewriteValue(name, value)]),\n )\n const walk = (node: SvgNode): SvgNode => ({\n tag: node.tag,\n attributes: rewrite(node.attributes),\n children: node.children.map(walk),\n })\n const made: IconData = {\n viewBox: icon.viewBox,\n attributes: rewrite(icon.attributes),\n nodes: icon.nodes.map(walk),\n }\n byPrefix.set(prefix, made)\n return made\n}\n\n/** How a drawing's strokes are drawn: their width, and whether their ends and joins are round. */\nexport interface Stroke {\n readonly width?: number | undefined\n readonly corners?: 'round' | 'square' | undefined\n}\n\n/**\n * The icon with its strokes redrawn: every `stroke-width`, `stroke-linecap`\n * and `stroke-linejoin` it sets replaced, or set on its root where it sets\n * none. A filled icon draws no stroke, so it is unchanged in what shows. For\n * a mask, whose drawing CSS cannot reach once it is a `url()`.\n */\nexport const withStroke = (icon: IconData, stroke: Stroke): IconData => {\n const set: Record<string, string> = {}\n if (stroke.width !== undefined) set['stroke-width'] = String(stroke.width)\n if (stroke.corners !== undefined) {\n set['stroke-linecap'] = stroke.corners\n set['stroke-linejoin'] = stroke.corners === 'round' ? 'round' : 'miter'\n }\n const names = Object.keys(set)\n const found = new Set<string>()\n const restroke = (attributes: Readonly<Record<string, string>>) => {\n const written = { ...attributes }\n for (const name of names) {\n if (Object.hasOwn(attributes, name)) {\n written[name] = set[name]!\n found.add(name)\n }\n }\n return written\n }\n const walk = (node: SvgNode): SvgNode => ({\n tag: node.tag,\n attributes: restroke(node.attributes),\n children: node.children.map(walk),\n })\n const nodes = icon.nodes.map(walk)\n const attributes = restroke(icon.attributes)\n // A property the drawing never sets is set once on the root, which every node inherits.\n for (const name of names) if (!found.has(name)) attributes[name] = set[name]!\n return { viewBox: icon.viewBox, attributes, nodes }\n}\n\ntype Element<Node, Attribute> = (\n attributes: ReadonlyArray<Attribute>,\n children: ReadonlyArray<Node>,\n) => Node\n\n/**\n * What `draw` needs of a view's builder: an element per tag an icon may hold,\n * and raw attributes. Foldkit's `HtmlBuilder` is one, so this package needs\n * no view library of its own.\n */\nexport type SvgBuilder<Node, Attribute> = {\n readonly svg: Element<Node, Attribute>\n readonly Attribute: (name: string, value: string) => Attribute\n readonly AriaHidden: (value: boolean) => Attribute\n} & { readonly [Tag in SvgTag]: Element<Node, Attribute> }\n\n/**\n * The icon as inline SVG, through a view's builder (`h`): `size` square\n * (`1em` unless given, so it stands as tall as its text; `foldkit-mixins-ui`'s\n * `Icon.view` fills its glyph with it), kept so in a squeezed flex row, and\n * hidden from assistive technology,\n * since the control it sits in carries the name. Every attribute is written as\n * an attribute, so a server render writes the same markup. Ids are prefixed by\n * `key(icon)`; `options.key` sets one drawing's ids apart from another of the\n * same icon, since a gradient defined in a copy that is hidden paints nothing\n * for the copy that shows. Each key's drawing is kept for the icon's life, so\n * take keys from a small fixed set (a place on the page), not one per row.\n */\nexport const draw = <Node, Attribute>(\n icon: IconData,\n h: SvgBuilder<Node, Attribute>,\n options: { readonly key?: string; readonly size?: string } = {},\n): Node => {\n const prefix = key(icon) + (options.key === undefined ? '' : `-${options.key}`)\n const { viewBox, attributes, nodes } = prefixIds(icon, prefix)\n const size = options.size ?? '1em'\n const written = (from: Readonly<Record<string, string>>) =>\n Object.entries(from).map(([name, value]) => h.Attribute(name, value))\n const drawn = ({ tag, attributes, children }: SvgNode): Node =>\n h[tag](written(attributes), children.map(drawn))\n return h.svg(\n [\n h.Attribute('viewBox', viewBox),\n h.Attribute('width', size),\n h.Attribute('height', size),\n // A flex row squeezed narrower than its content shrinks an svg to nothing, width or not.\n h.Attribute('style', 'flex-shrink: 0'),\n h.AriaHidden(true),\n ...written(attributes),\n ],\n nodes.map(drawn),\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAQA,MAAa,OAAO;CAClB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAiBA,MAAM,mBAAmB,UACvB,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,QAAQ,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM;AAEjG,MAAM,gBAAgB,eACpB,OAAO,QAAQ,UAAU,CAAC,CACvB,KAAK,CAAC,MAAM,WAAW,IAAI,KAAK,IAAI,gBAAgB,KAAK,EAAE,EAAE,CAAC,CAC9D,KAAK,EAAE;AAEZ,MAAM,cAAc,EAAE,KAAK,YAAY,eACrC,SAAS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,QAAQ,UAAU,GAAG,SAAS,IAAI,KAAK,CAAC;CACjD,OAAO,EAAE,IACP;EACE,EAAE,UAAU,WAAW,OAAO;EAC9B,EAAE,UAAU,SAAS,IAAI;EACzB,EAAE,UAAU,UAAU,IAAI;EAE1B,EAAE,UAAU,SAAS,gBAAgB;EACrC,EAAE,WAAW,IAAI;EACjB,GAAG,QAAQ,UAAU;CACvB,GACA,MAAM,IAAI,KAAK,CACjB;AACF"}
|
|
@@ -84,6 +84,5 @@ declare const draw: <Node, Attribute>(icon: IconData, h: SvgBuilder<Node, Attrib
|
|
|
84
84
|
readonly key?: string;
|
|
85
85
|
readonly size?: string;
|
|
86
86
|
}) => Node;
|
|
87
|
-
//#endregion
|
|
88
87
|
export { SvgTag as a, SvgNode as i, Stroke as n, icon_d_exports as o, SvgBuilder as r, IconData as t };
|
|
89
|
-
//# sourceMappingURL=icon-
|
|
88
|
+
//# sourceMappingURL=icon-BGtxExTN.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"icon-
|
|
1
|
+
{"version":3,"file":"icon-BGtxExTN.d.mts","names":[],"sources":["../src/icon.ts"],"mappings":";;;;;;;;;;cAQa;KAiBD,iBAAiB;;UAGZ;WACN,KAAK;WACL,YAAY,SAAS;WACrB,UAAU,cAAc;;;UAIlB;WACN;WACA,YAAY,SAAS;WACrB,OAAO,cAAc;;;cAiBnB,YAAS,MAAU;;;;;;cAQnB,UAAO,MAAU;;;;;;cAajB,MAAG,MAAU;;;;;;;;;cA8Cb,YAAS,MAAU,UAAQ,mBAAmB;;UAqC1C;WACN;WACA;;;;;;;;cASE,aAAU,MAAU,UAAQ,QAAU,WAAS;KA+BvD,QAAQ,MAAM,cACjB,YAAY,cAAc,YAC1B,UAAU,cAAc,UACrB;;;;;;KAOO,WAAW,MAAM;WAClB,KAAK,QAAQ,MAAM;WACnB,YAAY,cAAc,kBAAkB;WAC5C,aAAa,mBAAmB;gBAC3B,OAAO,SAAS,QAAQ,MAAM;;;;;;;;;;;;;cAcjC,OAAQ,MAAM,WAAS,MAC5B,UAAQ,GACX,WAAW,MAAM,YAAU;WACV;WAAuB;MAC1C"}
|
package/dist/icons/index.d.mts
CHANGED
|
@@ -1,6 +1,5 @@
|
|
|
1
|
-
import { t as IconData } from "../icon-
|
|
1
|
+
import { t as IconData } from "../icon-BGtxExTN.mjs";
|
|
2
2
|
import { Schema } from "effect";
|
|
3
|
-
//#region src/icons/index.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* The icon in `svg`, one whole SVG document, as `IconData`; `name` says which
|
|
6
5
|
* icon a refusal is about. Throws on anything outside the allowlist.
|
|
@@ -47,5 +46,4 @@ export declare const namesOf: (set: IconifySet) => ReadonlyArray<string>;
|
|
|
47
46
|
* rather than drawn as a second, transformed drawing.
|
|
48
47
|
*/
|
|
49
48
|
export declare const fromIconify: (set: IconifySet, name: string) => IconData;
|
|
50
|
-
//#endregion
|
|
51
49
|
//# sourceMappingURL=index.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/icons/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/icons/index.ts"],"mappings":";;;;;;qBA0Ha,QAAK,aAAe,iBAAiB;;;;;;qBAgMrC,YAAU,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;YAQX,oBAAoB,WAAW;;qBAG9B,UAAO,KAAS,eAAa;;;;;;qBAU7B,cAAW,KAAS,YAAU,iBAAiB"}
|
package/dist/icons/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { t as TAGS } from "../icon-
|
|
1
|
+
import { t as TAGS } from "../icon-0A2dBtqj.mjs";
|
|
2
2
|
import { Schema } from "effect";
|
|
3
|
-
|
|
3
|
+
// src/icons/index.ts
|
|
4
4
|
/**
|
|
5
5
|
* SVG to `IconData`, for builds and generator scripts: a Vite plugin reading
|
|
6
6
|
* an icon set, a script writing a package's icon constants. The parse is where
|
|
@@ -314,7 +314,6 @@ const fromIconify = (set, name) => {
|
|
|
314
314
|
const read = (key, otherwise) => nearest.find((box) => box[key] !== void 0)?.[key] ?? otherwise;
|
|
315
315
|
return parse(`<svg viewBox="${read("left", 0)} ${read("top", 0)} ${read("width", 16)} ${read("height", 16)}">${icon.body}</svg>`, label);
|
|
316
316
|
};
|
|
317
|
-
//#endregion
|
|
318
317
|
export { IconifySet, fromIconify, namesOf, parse };
|
|
319
318
|
|
|
320
319
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.d.mts
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import { a as isHashed, i as Placeholder, n as HashedAsset, r as ImageAsset, t as Focus } from "./asset-
|
|
2
|
-
import { i as describe, n as Inspector, r as Thumbnail, t as Inspected } from "./describe-
|
|
3
|
-
import { a as mimeType, i as Format, n as widths_d_exports, r as Encoding, t as Widths } from "./widths-
|
|
4
|
-
import { r as variant_d_exports } from "./variant-
|
|
5
|
-
import { a as SvgTag, i as SvgNode, n as Stroke, o as icon_d_exports, r as SvgBuilder, t as IconData } from "./icon-
|
|
6
|
-
import { n as Provider, r as provider_d_exports } from "./provider-
|
|
1
|
+
import { a as isHashed, i as Placeholder, n as HashedAsset, r as ImageAsset, t as Focus } from "./asset-BLo8VWmd.mjs";
|
|
2
|
+
import { i as describe, n as Inspector, r as Thumbnail, t as Inspected } from "./describe-BOgc0xbR.mjs";
|
|
3
|
+
import { a as mimeType, i as Format, n as widths_d_exports, r as Encoding, t as Widths } from "./widths-upkgLdek.mjs";
|
|
4
|
+
import { r as variant_d_exports } from "./variant-B-vyMmFB.mjs";
|
|
5
|
+
import { a as SvgTag, i as SvgNode, n as Stroke, o as icon_d_exports, r as SvgBuilder, t as IconData } from "./icon-BGtxExTN.mjs";
|
|
6
|
+
import { n as Provider, r as provider_d_exports } from "./provider-CB0nqu0m.mjs";
|
|
7
7
|
import { Option, Schema } from "effect";
|
|
8
8
|
declare namespace layout_d_exports {
|
|
9
9
|
export { Candidate, Constrained, Fixed, FullWidth, Layout, LayoutSchema as Schema, box, candidates, ratio, sizes$1 as sizes };
|
|
@@ -63,8 +63,6 @@ declare const box: (layout: Layout, asset: Pick<ImageAsset, 'width' | 'height'>)
|
|
|
63
63
|
readonly width: number;
|
|
64
64
|
readonly height: number;
|
|
65
65
|
};
|
|
66
|
-
//#endregion
|
|
67
|
-
//#region src/placeholder.d.ts
|
|
68
66
|
/**
|
|
69
67
|
* How much of a ThumbHash a placeholder paints: its blurred picture
|
|
70
68
|
* (`detail`), or its average color (`average`).
|
|
@@ -155,6 +153,5 @@ declare const preload: ({ sources, img }: Picture) => string;
|
|
|
155
153
|
* such variant.
|
|
156
154
|
*/
|
|
157
155
|
declare const ogImage: <Asset extends ImageAsset>(asset: Asset, provider: Provider<NoInfer<Asset>>, origin: string) => Option.Option<string>;
|
|
158
|
-
//#endregion
|
|
159
156
|
export { type Encoding, Focus, Format, HashedAsset, icon_d_exports as Icon, type IconData, ImageAsset, type Inspected, Inspector, layout_d_exports as Layout, picture_d_exports as Picture, Placeholder, provider_d_exports as Provider, type Stroke, type SvgBuilder, type SvgNode, type SvgTag, type Thumbnail, variant_d_exports as Variant, widths_d_exports as Widths, describe, isHashed, mimeType };
|
|
160
157
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":["sizes","Layout.Layout"],"sources":["../src/layout.ts","../src/placeholder.ts","../src/picture.ts"],"mappings":";;;;;;;;;;;cAOM,cAAY,OAAA;;;;;;;;;KASN,gBAAgB,aAAa;cAE5B,QAAK
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":["sizes","Layout.Layout"],"sources":["../src/layout.ts","../src/placeholder.ts","../src/picture.ts"],"mappings":";;;;;;;;;;;cAOM,cAAY,OAAA;;;;;;;;;KASN,gBAAgB,aAAa;cAE5B,QAAK;;;;;;;cACL,cAAW;;;;;;;cACX,iBAAgB;;;;;;UAOZ;WACN;WACA;;;;;;;;cASE,aAAU,QACb,QAAM,QACN,QAAM,sBAEb,cAAc;;cAkBJA,UAAK,QAAY;;cAQjB,QAAK,OAAW,KAAK;;;;;;cAQrB,MAAG,QACN,QAAM,OACP,KAAK;WACA;WAAwB;;;;;;KC3C1B;;;;;UC3BK;WACN;WACA;;;UAIM;WACN;WACA;WACA;WACA;WACA;WACA;WACA,UAAU,OAAO;WACjB,eAAe,OAAO;;;;;;UAOhB;;WAEN,SAAS,cAAc;WACvB,KAAK;;WAEL;;WAEA,OAAO,OAAO;;;;;WAKd,aAAa,OAAO;;;UAId,MAAM,cAAc,aAAa;WACvC,OAAO;WACP,UAAU,SAAS,QAAQ;WAC3B,QAAQC;;WAER;;WAEA;;;;;;WAMA,cAAc;;;;;;;;cASZ,SAAU,cAAc,YAAU,OAAS,MAAM,WAAS,OAAO,OAAO;;UA0DpE;;WAEN,MAAM,OAAO;WACb;WACA;;;cAIE,gBAAW,MAAA,QAAA,SAA6B;;;;;;;;;cAoBxC,YAAO,SAAA,OAAsB;;;;;;;cAkB7B,UAAW,cAAc,YAAU,OACvC,OAAK,UACF,SAAS,QAAQ,SAAO,mBAEjC,OAAO"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-
|
|
2
|
-
import { n as mimeType, t as Format } from "./format-
|
|
3
|
-
import { i as widths_exports, n as make, r as standard, t as atLeast } from "./widths-
|
|
4
|
-
import { a as ImageAsset, h as variant_exports, i as HashedAsset, l as PATH, m as standard$1, n as describe, o as Placeholder, r as Focus, s as isHashed, t as Inspector, u as Quality } from "./describe-
|
|
5
|
-
import { n as icon_exports } from "./icon-
|
|
1
|
+
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
|
+
import { n as mimeType, t as Format } from "./format-BCRTFU9j.mjs";
|
|
3
|
+
import { i as widths_exports, n as make, r as standard, t as atLeast } from "./widths-qp3jshiF.mjs";
|
|
4
|
+
import { a as ImageAsset, h as variant_exports, i as HashedAsset, l as PATH, m as standard$1, n as describe, o as Placeholder, r as Focus, s as isHashed, t as Inspector, u as Quality } from "./describe-C6sWA_8p.mjs";
|
|
5
|
+
import { n as icon_exports } from "./icon-0A2dBtqj.mjs";
|
|
6
6
|
import { Option, Schema } from "effect";
|
|
7
7
|
import { thumbHashToAverageRGBA, thumbHashToDataURL } from "thumbhash";
|
|
8
|
-
|
|
8
|
+
// src/layout.ts
|
|
9
9
|
var layout_exports = /* @__PURE__ */ __exportAll({
|
|
10
10
|
Constrained: () => Constrained,
|
|
11
11
|
Fixed: () => Fixed,
|
|
@@ -82,8 +82,7 @@ const box = (layout, asset) => {
|
|
|
82
82
|
})
|
|
83
83
|
});
|
|
84
84
|
};
|
|
85
|
-
|
|
86
|
-
//#region src/placeholder.ts
|
|
85
|
+
// src/placeholder.ts
|
|
87
86
|
const DECODED_LIMIT = 256;
|
|
88
87
|
const decoded = /* @__PURE__ */ new Map();
|
|
89
88
|
const bytesOf = (hash) => Uint8Array.from(atob(hash), (char) => char.charCodeAt(0));
|
|
@@ -115,8 +114,7 @@ const background = (asset, provider, level) => Option.flatMap(asset.placeholder,
|
|
|
115
114
|
encoding: provider.fallback
|
|
116
115
|
}), cssUrl)
|
|
117
116
|
}));
|
|
118
|
-
|
|
119
|
-
//#region src/picture.ts
|
|
117
|
+
// src/picture.ts
|
|
120
118
|
var picture_exports = /* @__PURE__ */ __exportAll({
|
|
121
119
|
derive: () => derive,
|
|
122
120
|
ogImage: () => ogImage,
|
|
@@ -227,8 +225,7 @@ const ogImage = (asset, provider, origin) => {
|
|
|
227
225
|
encoding
|
|
228
226
|
}))), (url) => new URL(url, origin).href);
|
|
229
227
|
};
|
|
230
|
-
|
|
231
|
-
//#region src/provider.ts
|
|
228
|
+
// src/provider.ts
|
|
232
229
|
var provider_exports = /* @__PURE__ */ __exportAll({
|
|
233
230
|
cdnCgi: () => cdnCgi,
|
|
234
231
|
fromFiles: () => fromFiles,
|
|
@@ -320,7 +317,6 @@ const hosted = (options = {}) => {
|
|
|
320
317
|
}
|
|
321
318
|
};
|
|
322
319
|
};
|
|
323
|
-
//#endregion
|
|
324
320
|
export { Focus, Format, HashedAsset, icon_exports as Icon, ImageAsset, Inspector, layout_exports as Layout, picture_exports as Picture, Placeholder, provider_exports as Provider, variant_exports as Variant, widths_exports as Widths, describe, isHashed, mimeType };
|
|
325
321
|
|
|
326
322
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":["candidates","Layout.candidates","sizes","Layout.sizes","box","Layout.box","Layout.ratio","Widths.atLeast","Widths.make","Widths.standard","Variant.Quality","Variant.standard"],"sources":["../src/layout.ts","../src/placeholder.ts","../src/picture.ts","../src/provider.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport { atLeast, type Widths } from './widths.js'\n\nconst CssPixels = Schema.Finite.check(Schema.isGreaterThan(0))\n\n/** How wide an image is drawn, from which its candidates and `sizes` follow. */\nconst LayoutSchema = Schema.TaggedUnion({\n /** Always this many CSS pixels wide. */\n Fixed: { width: CssPixels },\n /** At most this wide, and the viewport's width when that is narrower. */\n Constrained: { width: CssPixels },\n /** The viewport's width. */\n FullWidth: {},\n})\nexport { LayoutSchema as Schema }\nexport type Layout = typeof LayoutSchema.Type\n\nexport const Fixed = LayoutSchema.cases.Fixed.make\nexport const Constrained = LayoutSchema.cases.Constrained.make\nexport const FullWidth = (): Layout => LayoutSchema.cases.FullWidth.make({})\n\n/**\n * One `srcset` entry: the ladder width asked of the provider, and the width\n * the answer has. They differ only above the original's own width, where a\n * provider that does not enlarge answers with the original's.\n */\nexport interface Candidate {\n readonly request: number\n readonly described: number\n}\n\n/**\n * The widths worth offering for `layout`: for a fixed image its 1x and 2x,\n * for a constrained one every width up to its 2x, for a full-width one the\n * whole ladder. Widths above the original fetch the original's pixels, so\n * only the first of them is kept.\n */\nexport const candidates = (\n layout: Layout,\n widths: Widths,\n intrinsic: number,\n): ReadonlyArray<Candidate> => {\n const wanted = LayoutSchema.match(layout, {\n Fixed: ({ width }) => [atLeast(widths, width), atLeast(widths, 2 * width)],\n Constrained: ({ width }) => {\n const top = atLeast(widths, 2 * width)\n return widths.values.filter(value => value <= top)\n },\n FullWidth: () => widths.values,\n })\n const result: Array<Candidate> = []\n for (const request of wanted) {\n const described = Math.min(request, intrinsic)\n if (result.at(-1)?.described !== described) result.push({ request, described })\n }\n return result\n}\n\n/** The `sizes` a layout implies: how wide the image is drawn at each viewport. */\nexport const sizes = (layout: Layout): string =>\n LayoutSchema.match(layout, {\n Fixed: ({ width }) => `${width}px`,\n Constrained: ({ width }) => `(min-width: ${width}px) ${width}px, 100vw`,\n FullWidth: () => '100vw',\n })\n\n/** The original's aspect ratio, as CSS writes one. */\nexport const ratio = (asset: Pick<ImageAsset, 'width' | 'height'>): string =>\n `${asset.width} / ${asset.height}`\n\n/**\n * The `width` and `height` attributes: the drawn size where the layout fixes\n * one, the original's where it does not. Either way their ratio is the\n * original's, which is what reserves the box before a byte arrives.\n */\nexport const box = (\n layout: Layout,\n asset: Pick<ImageAsset, 'width' | 'height'>,\n): { readonly width: number; readonly height: number } => {\n const pixel = (value: number) => Math.max(1, Math.round(value))\n const scaled = (width: number) => ({\n width: pixel(width),\n height: pixel((width * asset.height) / asset.width),\n })\n return LayoutSchema.match(layout, {\n Fixed: ({ width }) => scaled(width),\n Constrained: ({ width }) => scaled(width),\n FullWidth: () => ({ width: asset.width, height: asset.height }),\n })\n}\n","import { Option } from 'effect'\nimport { thumbHashToAverageRGBA, thumbHashToDataURL } from 'thumbhash'\nimport { Placeholder, type ImageAsset } from './asset.js'\nimport type { Provider } from './provider.js'\n\n// A list redraws the same images, and decoding draws a PNG each time; a few\n// hundred recent ones cover a page without growing for the life of the app.\nconst DECODED_LIMIT = 256\nconst decoded = new Map<string, string>()\n\nconst bytesOf = (hash: string) => Uint8Array.from(atob(hash), char => char.charCodeAt(0))\n\nconst decode = (hash: string): string => {\n const cached = decoded.get(hash)\n if (cached !== undefined) return cached\n const url = thumbHashToDataURL(bytesOf(hash))\n if (decoded.size >= DECODED_LIMIT) decoded.delete(decoded.keys().next().value!)\n decoded.set(hash, url)\n return url\n}\n\n// Percent-encode what would end or escape a quoted CSS `url()`.\nconst cssUrl = (url: string): string =>\n `url(\"${url.replace(/[\"\\\\\\n\\r]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`)}\")`\n\n// A ThumbHash's average color, which costs a few bytes of HTML where its picture costs kilobytes.\nconst average = (hash: string): string => {\n const { r, g, b, a } = thumbHashToAverageRGBA(bytesOf(hash))\n const channel = (value: number) => Math.round(value * 255)\n return `rgb(${channel(r)} ${channel(g)} ${channel(b)} / ${Math.round(a * 100) / 100})`\n}\n\n/**\n * How much of a ThumbHash a placeholder paints: its blurred picture\n * (`detail`), or its average color (`average`).\n */\nexport type Level = 'detail' | 'average'\n\n/**\n * The CSS `background` an image's placeholder paints, whatever the image: a\n * color, a ThumbHash at `level`, or the provider's smallest width of the\n * image. None when the image has no placeholder, or the provider has no URL\n * for the smallest width.\n */\nexport const background = <Asset extends ImageAsset>(\n asset: Asset,\n provider: Provider<Asset>,\n level: Level,\n): Option.Option<string> =>\n Option.flatMap(asset.placeholder, placeholder =>\n Placeholder.match(placeholder, {\n Color: ({ value }) => Option.some(value),\n ThumbHash: ({ hash }) =>\n Option.some(level === 'detail' ? cssUrl(decode(hash)) : average(hash)),\n LowRes: () =>\n Option.map(\n provider.url(asset, { width: provider.widths.values[0]!, encoding: provider.fallback }),\n cssUrl,\n ),\n }),\n )\n","import { Option } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport { mimeType, type Encoding } from './format.js'\nimport * as Layout from './layout.js'\nimport { background, type Level } from './placeholder.js'\nimport type { Provider } from './provider.js'\nimport * as Widths from './widths.js'\n\n/** A `source` element's attributes: one format's candidates. */\nexport interface Source {\n readonly type: string\n readonly srcset: string\n}\n\n/** The `img` element's attributes. */\nexport interface Img {\n readonly src: string\n readonly srcset: string\n readonly sizes: string\n readonly width: number\n readonly height: number\n readonly loading: 'lazy' | 'eager'\n readonly decoding: Option.Option<'async'>\n readonly fetchPriority: Option.Option<'high'>\n}\n\n/**\n * Everything an image's markup says, derived from its facts, its provider and\n * its layout. A view writes these; it decides nothing.\n */\nexport interface Picture {\n /** One per format the provider offers before the `img`'s own; none, a bare `img`. */\n readonly sources: ReadonlyArray<Source>\n readonly img: Img\n /** The original's aspect ratio, as CSS writes one. */\n readonly ratio: string\n /** Where a crop keeps the subject, as `object-position` writes it. */\n readonly focus: Option.Option<string>\n /**\n * The CSS `background` to paint behind the image until it loads. None for\n * an image with transparent pixels, which would show it through them.\n */\n readonly placeholder: Option.Option<string>\n}\n\n/** An image's facts, and a provider that takes them: a hashed one for `Provider.hosted`. */\nexport interface Input<Asset extends ImageAsset = ImageAsset> {\n readonly asset: Asset\n readonly provider: Provider<NoInfer<Asset>>\n readonly layout: Layout.Layout\n /** The page's largest image: fetched first, not lazily. */\n readonly priority?: boolean\n /** In place of the layout's `sizes`, when the page knows the drawn width better. */\n readonly sizes?: string\n /**\n * How much of a ThumbHash to paint. By default its picture for a `priority`\n * image, the one a reader waits on, and its average color for the rest, so\n * a grid of thumbnails adds colors to the HTML, not pictures.\n */\n readonly placeholder?: Level\n}\n\n/**\n * The attributes of one image, or none when the provider has no URL for any\n * of its candidates in the `img`'s own encoding (a build table that never made\n * this image). Candidates the provider lacks are left out, never written as a\n * broken URL.\n */\nexport const derive = <Asset extends ImageAsset>(input: Input<Asset>): Option.Option<Picture> => {\n const { asset, provider, layout, priority = false } = input\n const candidates = Layout.candidates(layout, provider.widths, asset.width)\n\n const entries = (encoding: Encoding) =>\n candidates.flatMap(candidate =>\n Option.match(provider.url(asset, { width: candidate.request, encoding }), {\n onNone: () => [],\n onSome: url => [{ url, described: candidate.described }],\n }),\n )\n const srcsetOf = (list: ReadonlyArray<{ readonly url: string; readonly described: number }>) =>\n list.map(({ url, described }) => `${url} ${described}w`).join(', ')\n\n const own = entries(provider.fallback)\n if (own.length === 0) return Option.none()\n\n // A browser that ignores `srcset` fetches `src`: the first width at least\n // as wide as the image is drawn, or the largest there is.\n const drawn = Layout.Schema.match(layout, {\n Fixed: ({ width }) => width,\n Constrained: ({ width }) => width,\n FullWidth: () => Number.POSITIVE_INFINITY,\n })\n const src = (own.find(entry => entry.described >= drawn) ?? own[own.length - 1]!).url\n\n const sources = provider.sources.flatMap(format => {\n const list = entries(format)\n return list.length === 0 ? [] : [{ type: mimeType(format), srcset: srcsetOf(list) }]\n })\n\n const sizes = input.sizes ?? Layout.sizes(layout)\n const box = Layout.box(layout, asset)\n return Option.some({\n sources,\n img: {\n src,\n srcset: srcsetOf(own),\n // A lazy image may let the browser use its laid-out width instead.\n sizes: priority || sizes.startsWith('auto') ? sizes : `auto, ${sizes}`,\n width: box.width,\n height: box.height,\n loading: priority ? 'eager' : 'lazy',\n decoding: priority ? Option.none() : Option.some('async'),\n fetchPriority: priority ? Option.some('high') : Option.none(),\n },\n ratio: Layout.ratio(asset),\n focus: Option.map(asset.focus, ({ x, y }) => `${x * 100}% ${y * 100}%`),\n placeholder: asset.alpha\n ? Option.none()\n : background(asset, provider, input.placeholder ?? (priority ? 'detail' : 'average')),\n })\n}\n\nconst escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>')\n\n/** What a preload names: the candidates the browser will choose from, at the `img`'s sizes. */\nexport interface Preloaded {\n /** A `source`'s media type, so a browser that cannot show it skips the preload. */\n readonly type: Option.Option<string>\n readonly srcset: string\n readonly sizes: string\n}\n\n/** The `<link rel=\"preload\">` naming `preloaded`, its values escaped for the attribute. */\nexport const preloadLink = ({ type, srcset, sizes }: Preloaded): string => {\n const attributes: ReadonlyArray<readonly [string, string]> = [\n ['rel', 'preload'],\n ['as', 'image'],\n ...Option.match(type, { onNone: () => [], onSome: value => [['type', value] as const] }),\n ['imagesrcset', srcset],\n ['imagesizes', sizes],\n ['fetchpriority', 'high'],\n ]\n return `<link ${attributes.map(([name, value]) => `${name}=\"${escapeAttribute(value)}\"`).join(' ')}>`\n}\n\n/**\n * A `<link rel=\"preload\">` for a page's `head`, so the browser fetches its\n * largest image before it reaches the `img`. It names the candidates the\n * browser will choose from: the first `source`'s, with its `type`, so a\n * browser that cannot show that format skips the preload rather than fetching\n * a file it will not use; the `img`'s when there is no `source`. Only for the\n * image drawn with `priority`.\n */\nexport const preload = ({ sources, img }: Picture): string => {\n const [first] = sources\n return preloadLink({\n type: Option.map(Option.fromNullishOr(first), source => source.type),\n srcset: first === undefined ? img.srcset : first.srcset,\n sizes: img.sizes,\n })\n}\n\n// Link-preview fetchers read JPEG; many read WebP and PNG; not all read AVIF.\nconst OPEN_GRAPH_ENCODINGS = ['jpeg', 'webp', 'png'] as const\n\n/**\n * An image for a page's Open Graph `og:image`: at the first ladder width of\n * at least 1200, as JPEG when the provider makes it, else WebP or PNG, never\n * AVIF, as an absolute URL against `origin`. None when the provider has no\n * such variant.\n */\nexport const ogImage = <Asset extends ImageAsset>(\n asset: Asset,\n provider: Provider<NoInfer<Asset>>,\n origin: string,\n): Option.Option<string> => {\n const width = Widths.atLeast(provider.widths, 1200)\n // A provider that picks the format reads the fetcher's `Accept`; the rest are asked in turn.\n const encodings: ReadonlyArray<Encoding> =\n provider.fallback === 'auto' ? ['auto'] : OPEN_GRAPH_ENCODINGS\n return Option.map(\n Option.firstSomeOf(encodings.map(encoding => provider.url(asset, { width, encoding }))),\n url => new URL(url, origin).href,\n )\n}\n","import { Option, Schema } from 'effect'\nimport type { HashedAsset, ImageAsset } from './asset.js'\nimport type { Encoding, Format } from './format.js'\nimport * as Variant from './variant.js'\nimport * as Widths from './widths.js'\n\n/** One variant asked of a provider: a ladder width, in an encoding. */\nexport interface Request {\n readonly width: number\n readonly encoding: Encoding\n}\n\n/**\n * Writes the URL of a variant. A provider performs no I/O: it knows a host's\n * URL scheme, the widths it makes, and the encodings worth offering. `Asset`\n * is the facts it needs: `HashedAsset` for one that names originals by hash.\n */\nexport interface Provider<in Asset extends ImageAsset = ImageAsset> {\n readonly widths: Widths.Widths\n /** Formats offered as `source`s before the `img`, most preferred first. */\n readonly sources: ReadonlyArray<Format>\n /** What the `img` itself asks for; `auto` lets the host choose. */\n readonly fallback: Encoding\n /** The variant's URL, or none when this provider has no such variant. */\n readonly url: (asset: Asset, request: Request) => Option.Option<string>\n}\n\n/** A file a build emitted: one width of one original, in one format. */\nexport interface File {\n readonly width: number\n readonly format: Format\n readonly url: string\n}\n\n/**\n * The provider of one image whose variants a build already wrote: a table of\n * files, no URL scheme. Its ladder is the widths it has, and it answers none\n * for a variant it lacks. Refuses no files, and two files for one variant.\n */\nexport const fromFiles = (\n files: ReadonlyArray<File>,\n formats: { readonly sources: ReadonlyArray<Format>; readonly fallback: Format },\n): Provider => {\n if (files.length === 0) throw new Error('Provider.fromFiles: no files')\n const byVariant = new Map<string, string>()\n for (const file of files) {\n const variant = `${file.width}:${file.format}`\n if (byVariant.has(variant)) {\n throw new Error(`Provider.fromFiles: two files for ${file.width}px ${file.format}`)\n }\n byVariant.set(variant, file.url)\n }\n return {\n widths: Widths.make([...new Set(files.map(file => file.width))]),\n sources: formats.sources,\n fallback: formats.fallback,\n url: (_asset, { width, encoding }) =>\n Option.fromNullishOr(byVariant.get(`${width}:${encoding}`)),\n }\n}\n\nconst HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/i\n\n/**\n * Cloudflare's own resizing, as URLs under `/cdn-cgi/image/` on a zone that\n * has it on. No Worker of ours runs: the zone fetches the original by its\n * `key` (a path on the zone, or an absolute URL it may fetch), scales it down\n * without enlarging, and picks the format from `Accept`.\n */\nexport const cdnCgi = (\n options: {\n /** The zone's host; omitted, URLs are relative to the page's. */\n readonly zone?: string\n readonly widths?: Widths.Widths\n /** 1 to 100. Cloudflare's default when omitted. */\n readonly quality?: number\n } = {},\n): Provider => {\n const { zone, widths = Widths.standard, quality } = options\n if (zone !== undefined && !HOSTNAME.test(zone)) {\n throw new Error(`Provider.cdnCgi: \"${zone}\" is not a host name`)\n }\n if (quality !== undefined && !Schema.is(Variant.Quality)(quality)) {\n throw new Error(`Provider.cdnCgi: quality ${quality} is not an integer from 1 to 100`)\n }\n const base = zone === undefined ? '' : `https://${zone}`\n const qualityOption = quality === undefined ? '' : `,quality=${quality}`\n return {\n widths,\n sources: [],\n fallback: 'auto',\n url: (asset, { width, encoding }) => {\n const operations = `width=${width},format=${encoding},fit=scale-down${qualityOption}`\n return Option.some(`${base}/cdn-cgi/image/${operations}/${cdnCgiSource(asset.key)}`)\n },\n }\n}\n\nconst cdnCgiSource = (key: string): string => {\n if (!/^https?:\\/\\//.test(key)) return key.replace(/^\\/+/, '')\n // A query in an absolute source would be read as the image URL's own.\n return key.includes('?') ? encodeURIComponent(key) : key\n}\n\n/** `Provider.hosted`'s provider, carrying its space, so its server reads the same one. */\nexport interface Hosted extends Provider<HashedAsset> {\n readonly space: Variant.Space\n}\n\n/**\n * Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under\n * `baseUrl`. An original is named by its content hash, so it takes a\n * `HashedAsset`, and has no URL for `auto`: this server names the format in\n * the URL, never reads `Accept`, so every cache can key on the URL alone.\n * Its formats and quality must be in `space`, or it is refused here rather\n * than answered with a 400 on every image. Give the same value to the server\n * (`serveFetch`'s `images.provider`), which reads its space from it.\n */\nexport const hosted = (\n options: {\n /** The server's origin, such as `https://img.example.com`; omitted, the page's. */\n readonly baseUrl?: string\n /** The server's space; the same value its handler decodes with. */\n readonly space?: Variant.Space\n /** Formats offered as `source`s; by default every one of the space's but the last. */\n readonly sources?: ReadonlyArray<Format>\n /** The `img`'s own format; by default the space's last. */\n readonly fallback?: Format\n readonly quality?: number\n } = {},\n): Hosted => {\n const { baseUrl: askedBaseUrl = '', space = Variant.standard } = options\n const fallback = options.fallback ?? space.formats[space.formats.length - 1]!\n const sources = options.sources ?? space.formats.slice(0, -1)\n const parsed = Option.liftThrowable((value: string) => new URL(value))(askedBaseUrl)\n const origin = Option.filter(\n parsed,\n url => (url.protocol === 'http:' || url.protocol === 'https:') && askedBaseUrl === url.origin,\n )\n if (askedBaseUrl !== '' && Option.isNone(origin)) {\n throw new Error(`Provider.hosted: \"${askedBaseUrl}\" is not an origin`)\n }\n const baseUrl = Option.match(origin, { onNone: () => '', onSome: url => url.origin })\n for (const format of [...sources, fallback]) {\n if (!space.formats.includes(format)) {\n throw new Error(`Provider.hosted: the server's space does not make ${format}`)\n }\n }\n const quality = Option.fromNullishOr(options.quality)\n if (Option.isSome(quality) && !space.qualities.includes(quality.value)) {\n throw new Error(`Provider.hosted: the server's space does not make quality ${quality.value}`)\n }\n const encodeVariant = Schema.encodeOption(space.schema)\n return {\n space,\n widths: space.widths,\n sources,\n fallback,\n url: (asset, { width, encoding }) => {\n if (encoding === 'auto') return Option.none()\n return Option.map(\n encodeVariant({ width, format: encoding, quality }),\n variant =>\n baseUrl + Variant.PATH.replace(':hash', asset.hash.value).replace(':variant', variant),\n )\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,cAAc,CAAC,CAAC;;AAG7D,MAAM,eAAe,OAAO,YAAY;;CAEtC,OAAO,EAAE,OAAO,UAAU;;CAE1B,aAAa,EAAE,OAAO,UAAU;;CAEhC,WAAW,CAAC;AACd,CAAC;AAID,MAAa,QAAQ,aAAa,MAAM,MAAM;AAC9C,MAAa,cAAc,aAAa,MAAM,YAAY;AAC1D,MAAa,kBAA0B,aAAa,MAAM,UAAU,KAAK,CAAC,CAAC;;;;;;;AAkB3E,MAAa,cACX,QACA,QACA,cAC6B;CAC7B,MAAM,SAAS,aAAa,MAAM,QAAQ;EACxC,QAAQ,EAAE,YAAY,CA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ACA,QAAQ,MAAM;EACd;EACA;EACA,MAAM,OAAO,EAAE,OAAO,eAAe;GACnC,IAAI,aAAa,QAAQ,OAAO,OAAO,KAAK;GAC5C,OAAO,OAAO,IACZ,cAAc;IAAE;IAAO,QAAQ;IAAU;GAAQ,CAAC,IAClD,YACE,UAAA,KAAuB,QAAQ,SAAS,MAAM,KAAK,KAAK,CAAC,CAAC,QAAQ,YAAY,OAAO,CACzF;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["candidates","Layout.candidates","sizes","Layout.sizes","box","Layout.box","Layout.ratio","Widths.atLeast","Widths.make","Widths.standard","Variant.Quality","Variant.standard"],"sources":["../src/layout.ts","../src/placeholder.ts","../src/picture.ts","../src/provider.ts"],"sourcesContent":["import { Schema } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport { atLeast, type Widths } from './widths.js'\n\nconst CssPixels = Schema.Finite.check(Schema.isGreaterThan(0))\n\n/** How wide an image is drawn, from which its candidates and `sizes` follow. */\nconst LayoutSchema = Schema.TaggedUnion({\n /** Always this many CSS pixels wide. */\n Fixed: { width: CssPixels },\n /** At most this wide, and the viewport's width when that is narrower. */\n Constrained: { width: CssPixels },\n /** The viewport's width. */\n FullWidth: {},\n})\nexport { LayoutSchema as Schema }\nexport type Layout = typeof LayoutSchema.Type\n\nexport const Fixed = LayoutSchema.cases.Fixed.make\nexport const Constrained = LayoutSchema.cases.Constrained.make\nexport const FullWidth = (): Layout => LayoutSchema.cases.FullWidth.make({})\n\n/**\n * One `srcset` entry: the ladder width asked of the provider, and the width\n * the answer has. They differ only above the original's own width, where a\n * provider that does not enlarge answers with the original's.\n */\nexport interface Candidate {\n readonly request: number\n readonly described: number\n}\n\n/**\n * The widths worth offering for `layout`: for a fixed image its 1x and 2x,\n * for a constrained one every width up to its 2x, for a full-width one the\n * whole ladder. Widths above the original fetch the original's pixels, so\n * only the first of them is kept.\n */\nexport const candidates = (\n layout: Layout,\n widths: Widths,\n intrinsic: number,\n): ReadonlyArray<Candidate> => {\n const wanted = LayoutSchema.match(layout, {\n Fixed: ({ width }) => [atLeast(widths, width), atLeast(widths, 2 * width)],\n Constrained: ({ width }) => {\n const top = atLeast(widths, 2 * width)\n return widths.values.filter(value => value <= top)\n },\n FullWidth: () => widths.values,\n })\n const result: Array<Candidate> = []\n for (const request of wanted) {\n const described = Math.min(request, intrinsic)\n if (result.at(-1)?.described !== described) result.push({ request, described })\n }\n return result\n}\n\n/** The `sizes` a layout implies: how wide the image is drawn at each viewport. */\nexport const sizes = (layout: Layout): string =>\n LayoutSchema.match(layout, {\n Fixed: ({ width }) => `${width}px`,\n Constrained: ({ width }) => `(min-width: ${width}px) ${width}px, 100vw`,\n FullWidth: () => '100vw',\n })\n\n/** The original's aspect ratio, as CSS writes one. */\nexport const ratio = (asset: Pick<ImageAsset, 'width' | 'height'>): string =>\n `${asset.width} / ${asset.height}`\n\n/**\n * The `width` and `height` attributes: the drawn size where the layout fixes\n * one, the original's where it does not. Either way their ratio is the\n * original's, which is what reserves the box before a byte arrives.\n */\nexport const box = (\n layout: Layout,\n asset: Pick<ImageAsset, 'width' | 'height'>,\n): { readonly width: number; readonly height: number } => {\n const pixel = (value: number) => Math.max(1, Math.round(value))\n const scaled = (width: number) => ({\n width: pixel(width),\n height: pixel((width * asset.height) / asset.width),\n })\n return LayoutSchema.match(layout, {\n Fixed: ({ width }) => scaled(width),\n Constrained: ({ width }) => scaled(width),\n FullWidth: () => ({ width: asset.width, height: asset.height }),\n })\n}\n","import { Option } from 'effect'\nimport { thumbHashToAverageRGBA, thumbHashToDataURL } from 'thumbhash'\nimport { Placeholder, type ImageAsset } from './asset.js'\nimport type { Provider } from './provider.js'\n\n// A list redraws the same images, and decoding draws a PNG each time; a few\n// hundred recent ones cover a page without growing for the life of the app.\nconst DECODED_LIMIT = 256\nconst decoded = new Map<string, string>()\n\nconst bytesOf = (hash: string) => Uint8Array.from(atob(hash), char => char.charCodeAt(0))\n\nconst decode = (hash: string): string => {\n const cached = decoded.get(hash)\n if (cached !== undefined) return cached\n const url = thumbHashToDataURL(bytesOf(hash))\n if (decoded.size >= DECODED_LIMIT) decoded.delete(decoded.keys().next().value!)\n decoded.set(hash, url)\n return url\n}\n\n// Percent-encode what would end or escape a quoted CSS `url()`.\nconst cssUrl = (url: string): string =>\n `url(\"${url.replace(/[\"\\\\\\n\\r]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`)}\")`\n\n// A ThumbHash's average color, which costs a few bytes of HTML where its picture costs kilobytes.\nconst average = (hash: string): string => {\n const { r, g, b, a } = thumbHashToAverageRGBA(bytesOf(hash))\n const channel = (value: number) => Math.round(value * 255)\n return `rgb(${channel(r)} ${channel(g)} ${channel(b)} / ${Math.round(a * 100) / 100})`\n}\n\n/**\n * How much of a ThumbHash a placeholder paints: its blurred picture\n * (`detail`), or its average color (`average`).\n */\nexport type Level = 'detail' | 'average'\n\n/**\n * The CSS `background` an image's placeholder paints, whatever the image: a\n * color, a ThumbHash at `level`, or the provider's smallest width of the\n * image. None when the image has no placeholder, or the provider has no URL\n * for the smallest width.\n */\nexport const background = <Asset extends ImageAsset>(\n asset: Asset,\n provider: Provider<Asset>,\n level: Level,\n): Option.Option<string> =>\n Option.flatMap(asset.placeholder, placeholder =>\n Placeholder.match(placeholder, {\n Color: ({ value }) => Option.some(value),\n ThumbHash: ({ hash }) =>\n Option.some(level === 'detail' ? cssUrl(decode(hash)) : average(hash)),\n LowRes: () =>\n Option.map(\n provider.url(asset, { width: provider.widths.values[0]!, encoding: provider.fallback }),\n cssUrl,\n ),\n }),\n )\n","import { Option } from 'effect'\nimport type { ImageAsset } from './asset.js'\nimport { mimeType, type Encoding } from './format.js'\nimport * as Layout from './layout.js'\nimport { background, type Level } from './placeholder.js'\nimport type { Provider } from './provider.js'\nimport * as Widths from './widths.js'\n\n/** A `source` element's attributes: one format's candidates. */\nexport interface Source {\n readonly type: string\n readonly srcset: string\n}\n\n/** The `img` element's attributes. */\nexport interface Img {\n readonly src: string\n readonly srcset: string\n readonly sizes: string\n readonly width: number\n readonly height: number\n readonly loading: 'lazy' | 'eager'\n readonly decoding: Option.Option<'async'>\n readonly fetchPriority: Option.Option<'high'>\n}\n\n/**\n * Everything an image's markup says, derived from its facts, its provider and\n * its layout. A view writes these; it decides nothing.\n */\nexport interface Picture {\n /** One per format the provider offers before the `img`'s own; none, a bare `img`. */\n readonly sources: ReadonlyArray<Source>\n readonly img: Img\n /** The original's aspect ratio, as CSS writes one. */\n readonly ratio: string\n /** Where a crop keeps the subject, as `object-position` writes it. */\n readonly focus: Option.Option<string>\n /**\n * The CSS `background` to paint behind the image until it loads. None for\n * an image with transparent pixels, which would show it through them.\n */\n readonly placeholder: Option.Option<string>\n}\n\n/** An image's facts, and a provider that takes them: a hashed one for `Provider.hosted`. */\nexport interface Input<Asset extends ImageAsset = ImageAsset> {\n readonly asset: Asset\n readonly provider: Provider<NoInfer<Asset>>\n readonly layout: Layout.Layout\n /** The page's largest image: fetched first, not lazily. */\n readonly priority?: boolean\n /** In place of the layout's `sizes`, when the page knows the drawn width better. */\n readonly sizes?: string\n /**\n * How much of a ThumbHash to paint. By default its picture for a `priority`\n * image, the one a reader waits on, and its average color for the rest, so\n * a grid of thumbnails adds colors to the HTML, not pictures.\n */\n readonly placeholder?: Level\n}\n\n/**\n * The attributes of one image, or none when the provider has no URL for any\n * of its candidates in the `img`'s own encoding (a build table that never made\n * this image). Candidates the provider lacks are left out, never written as a\n * broken URL.\n */\nexport const derive = <Asset extends ImageAsset>(input: Input<Asset>): Option.Option<Picture> => {\n const { asset, provider, layout, priority = false } = input\n const candidates = Layout.candidates(layout, provider.widths, asset.width)\n\n const entries = (encoding: Encoding) =>\n candidates.flatMap(candidate =>\n Option.match(provider.url(asset, { width: candidate.request, encoding }), {\n onNone: () => [],\n onSome: url => [{ url, described: candidate.described }],\n }),\n )\n const srcsetOf = (list: ReadonlyArray<{ readonly url: string; readonly described: number }>) =>\n list.map(({ url, described }) => `${url} ${described}w`).join(', ')\n\n const own = entries(provider.fallback)\n if (own.length === 0) return Option.none()\n\n // A browser that ignores `srcset` fetches `src`: the first width at least\n // as wide as the image is drawn, or the largest there is.\n const drawn = Layout.Schema.match(layout, {\n Fixed: ({ width }) => width,\n Constrained: ({ width }) => width,\n FullWidth: () => Number.POSITIVE_INFINITY,\n })\n const src = (own.find(entry => entry.described >= drawn) ?? own[own.length - 1]!).url\n\n const sources = provider.sources.flatMap(format => {\n const list = entries(format)\n return list.length === 0 ? [] : [{ type: mimeType(format), srcset: srcsetOf(list) }]\n })\n\n const sizes = input.sizes ?? Layout.sizes(layout)\n const box = Layout.box(layout, asset)\n return Option.some({\n sources,\n img: {\n src,\n srcset: srcsetOf(own),\n // A lazy image may let the browser use its laid-out width instead.\n sizes: priority || sizes.startsWith('auto') ? sizes : `auto, ${sizes}`,\n width: box.width,\n height: box.height,\n loading: priority ? 'eager' : 'lazy',\n decoding: priority ? Option.none() : Option.some('async'),\n fetchPriority: priority ? Option.some('high') : Option.none(),\n },\n ratio: Layout.ratio(asset),\n focus: Option.map(asset.focus, ({ x, y }) => `${x * 100}% ${y * 100}%`),\n placeholder: asset.alpha\n ? Option.none()\n : background(asset, provider, input.placeholder ?? (priority ? 'detail' : 'average')),\n })\n}\n\nconst escapeAttribute = (value: string): string =>\n value.replace(/&/g, '&').replace(/\"/g, '"').replace(/</g, '<').replace(/>/g, '>')\n\n/** What a preload names: the candidates the browser will choose from, at the `img`'s sizes. */\nexport interface Preloaded {\n /** A `source`'s media type, so a browser that cannot show it skips the preload. */\n readonly type: Option.Option<string>\n readonly srcset: string\n readonly sizes: string\n}\n\n/** The `<link rel=\"preload\">` naming `preloaded`, its values escaped for the attribute. */\nexport const preloadLink = ({ type, srcset, sizes }: Preloaded): string => {\n const attributes: ReadonlyArray<readonly [string, string]> = [\n ['rel', 'preload'],\n ['as', 'image'],\n ...Option.match(type, { onNone: () => [], onSome: value => [['type', value] as const] }),\n ['imagesrcset', srcset],\n ['imagesizes', sizes],\n ['fetchpriority', 'high'],\n ]\n return `<link ${attributes.map(([name, value]) => `${name}=\"${escapeAttribute(value)}\"`).join(' ')}>`\n}\n\n/**\n * A `<link rel=\"preload\">` for a page's `head`, so the browser fetches its\n * largest image before it reaches the `img`. It names the candidates the\n * browser will choose from: the first `source`'s, with its `type`, so a\n * browser that cannot show that format skips the preload rather than fetching\n * a file it will not use; the `img`'s when there is no `source`. Only for the\n * image drawn with `priority`.\n */\nexport const preload = ({ sources, img }: Picture): string => {\n const [first] = sources\n return preloadLink({\n type: Option.map(Option.fromNullishOr(first), source => source.type),\n srcset: first === undefined ? img.srcset : first.srcset,\n sizes: img.sizes,\n })\n}\n\n// Link-preview fetchers read JPEG; many read WebP and PNG; not all read AVIF.\nconst OPEN_GRAPH_ENCODINGS = ['jpeg', 'webp', 'png'] as const\n\n/**\n * An image for a page's Open Graph `og:image`: at the first ladder width of\n * at least 1200, as JPEG when the provider makes it, else WebP or PNG, never\n * AVIF, as an absolute URL against `origin`. None when the provider has no\n * such variant.\n */\nexport const ogImage = <Asset extends ImageAsset>(\n asset: Asset,\n provider: Provider<NoInfer<Asset>>,\n origin: string,\n): Option.Option<string> => {\n const width = Widths.atLeast(provider.widths, 1200)\n // A provider that picks the format reads the fetcher's `Accept`; the rest are asked in turn.\n const encodings: ReadonlyArray<Encoding> =\n provider.fallback === 'auto' ? ['auto'] : OPEN_GRAPH_ENCODINGS\n return Option.map(\n Option.firstSomeOf(encodings.map(encoding => provider.url(asset, { width, encoding }))),\n url => new URL(url, origin).href,\n )\n}\n","import { Option, Schema } from 'effect'\nimport type { HashedAsset, ImageAsset } from './asset.js'\nimport type { Encoding, Format } from './format.js'\nimport * as Variant from './variant.js'\nimport * as Widths from './widths.js'\n\n/** One variant asked of a provider: a ladder width, in an encoding. */\nexport interface Request {\n readonly width: number\n readonly encoding: Encoding\n}\n\n/**\n * Writes the URL of a variant. A provider performs no I/O: it knows a host's\n * URL scheme, the widths it makes, and the encodings worth offering. `Asset`\n * is the facts it needs: `HashedAsset` for one that names originals by hash.\n */\nexport interface Provider<in Asset extends ImageAsset = ImageAsset> {\n readonly widths: Widths.Widths\n /** Formats offered as `source`s before the `img`, most preferred first. */\n readonly sources: ReadonlyArray<Format>\n /** What the `img` itself asks for; `auto` lets the host choose. */\n readonly fallback: Encoding\n /** The variant's URL, or none when this provider has no such variant. */\n readonly url: (asset: Asset, request: Request) => Option.Option<string>\n}\n\n/** A file a build emitted: one width of one original, in one format. */\nexport interface File {\n readonly width: number\n readonly format: Format\n readonly url: string\n}\n\n/**\n * The provider of one image whose variants a build already wrote: a table of\n * files, no URL scheme. Its ladder is the widths it has, and it answers none\n * for a variant it lacks. Refuses no files, and two files for one variant.\n */\nexport const fromFiles = (\n files: ReadonlyArray<File>,\n formats: { readonly sources: ReadonlyArray<Format>; readonly fallback: Format },\n): Provider => {\n if (files.length === 0) throw new Error('Provider.fromFiles: no files')\n const byVariant = new Map<string, string>()\n for (const file of files) {\n const variant = `${file.width}:${file.format}`\n if (byVariant.has(variant)) {\n throw new Error(`Provider.fromFiles: two files for ${file.width}px ${file.format}`)\n }\n byVariant.set(variant, file.url)\n }\n return {\n widths: Widths.make([...new Set(files.map(file => file.width))]),\n sources: formats.sources,\n fallback: formats.fallback,\n url: (_asset, { width, encoding }) =>\n Option.fromNullishOr(byVariant.get(`${width}:${encoding}`)),\n }\n}\n\nconst HOSTNAME = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z]{2,63}$/i\n\n/**\n * Cloudflare's own resizing, as URLs under `/cdn-cgi/image/` on a zone that\n * has it on. No Worker of ours runs: the zone fetches the original by its\n * `key` (a path on the zone, or an absolute URL it may fetch), scales it down\n * without enlarging, and picks the format from `Accept`.\n */\nexport const cdnCgi = (\n options: {\n /** The zone's host; omitted, URLs are relative to the page's. */\n readonly zone?: string\n readonly widths?: Widths.Widths\n /** 1 to 100. Cloudflare's default when omitted. */\n readonly quality?: number\n } = {},\n): Provider => {\n const { zone, widths = Widths.standard, quality } = options\n if (zone !== undefined && !HOSTNAME.test(zone)) {\n throw new Error(`Provider.cdnCgi: \"${zone}\" is not a host name`)\n }\n if (quality !== undefined && !Schema.is(Variant.Quality)(quality)) {\n throw new Error(`Provider.cdnCgi: quality ${quality} is not an integer from 1 to 100`)\n }\n const base = zone === undefined ? '' : `https://${zone}`\n const qualityOption = quality === undefined ? '' : `,quality=${quality}`\n return {\n widths,\n sources: [],\n fallback: 'auto',\n url: (asset, { width, encoding }) => {\n const operations = `width=${width},format=${encoding},fit=scale-down${qualityOption}`\n return Option.some(`${base}/cdn-cgi/image/${operations}/${cdnCgiSource(asset.key)}`)\n },\n }\n}\n\nconst cdnCgiSource = (key: string): string => {\n if (!/^https?:\\/\\//.test(key)) return key.replace(/^\\/+/, '')\n // A query in an absolute source would be read as the image URL's own.\n return key.includes('?') ? encodeURIComponent(key) : key\n}\n\n/** `Provider.hosted`'s provider, carrying its space, so its server reads the same one. */\nexport interface Hosted extends Provider<HashedAsset> {\n readonly space: Variant.Space\n}\n\n/**\n * Our own server's variants (`foldkit-media/server`), at `Variant.PATH` under\n * `baseUrl`. An original is named by its content hash, so it takes a\n * `HashedAsset`, and has no URL for `auto`: this server names the format in\n * the URL, never reads `Accept`, so every cache can key on the URL alone.\n * Its formats and quality must be in `space`, or it is refused here rather\n * than answered with a 400 on every image. Give the same value to the server\n * (`serveFetch`'s `images.provider`), which reads its space from it.\n */\nexport const hosted = (\n options: {\n /** The server's origin, such as `https://img.example.com`; omitted, the page's. */\n readonly baseUrl?: string\n /** The server's space; the same value its handler decodes with. */\n readonly space?: Variant.Space\n /** Formats offered as `source`s; by default every one of the space's but the last. */\n readonly sources?: ReadonlyArray<Format>\n /** The `img`'s own format; by default the space's last. */\n readonly fallback?: Format\n readonly quality?: number\n } = {},\n): Hosted => {\n const { baseUrl: askedBaseUrl = '', space = Variant.standard } = options\n const fallback = options.fallback ?? space.formats[space.formats.length - 1]!\n const sources = options.sources ?? space.formats.slice(0, -1)\n const parsed = Option.liftThrowable((value: string) => new URL(value))(askedBaseUrl)\n const origin = Option.filter(\n parsed,\n url => (url.protocol === 'http:' || url.protocol === 'https:') && askedBaseUrl === url.origin,\n )\n if (askedBaseUrl !== '' && Option.isNone(origin)) {\n throw new Error(`Provider.hosted: \"${askedBaseUrl}\" is not an origin`)\n }\n const baseUrl = Option.match(origin, { onNone: () => '', onSome: url => url.origin })\n for (const format of [...sources, fallback]) {\n if (!space.formats.includes(format)) {\n throw new Error(`Provider.hosted: the server's space does not make ${format}`)\n }\n }\n const quality = Option.fromNullishOr(options.quality)\n if (Option.isSome(quality) && !space.qualities.includes(quality.value)) {\n throw new Error(`Provider.hosted: the server's space does not make quality ${quality.value}`)\n }\n const encodeVariant = Schema.encodeOption(space.schema)\n return {\n space,\n widths: space.widths,\n sources,\n fallback,\n url: (asset, { width, encoding }) => {\n if (encoding === 'auto') return Option.none()\n return Option.map(\n encodeVariant({ width, format: encoding, quality }),\n variant =>\n baseUrl + Variant.PATH.replace(':hash', asset.hash.value).replace(':variant', variant),\n )\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAIA,MAAM,YAAY,OAAO,OAAO,MAAM,OAAO,cAAc,CAAC,CAAC;;AAG7D,MAAM,eAAe,OAAO,YAAY;;CAEtC,OAAO,EAAE,OAAO,UAAU;;CAE1B,aAAa,EAAE,OAAO,UAAU;;CAEhC,WAAW,CAAC;AACd,CAAC;AAID,MAAa,QAAQ,aAAa,MAAM,MAAM;AAC9C,MAAa,cAAc,aAAa,MAAM,YAAY;AAC1D,MAAa,kBAA0B,aAAa,MAAM,UAAU,KAAK,CAAC,CAAC;;;;;;;AAkB3E,MAAa,cACX,QACA,QACA,cAC6B;CAC7B,MAAM,SAAS,aAAa,MAAM,QAAQ;EACxC,QAAQ,EAAE,YAAY,CAAC,QAAQ,QAAQ,KAAK,GAAG,QAAQ,QAAQ,IAAI,KAAK,CAAC;EACzE,cAAc,EAAE,YAAY;GAC1B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O,KAAK;GAC5C,OAAO,OAAO,IACZ,cAAc;IAAE;IAAO,QAAQ;IAAU;GAAQ,CAAC,IAClD,YACE,UAAA,KAAuB,QAAQ,SAAS,MAAM,KAAK,KAAK,CAAC,CAAC,QAAQ,YAAY,OAAO,CACzF;EACF;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/limits.ts
|
|
2
2
|
const nonNegativeInteger = (name, value) => {
|
|
3
3
|
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`foldkit-media: ${name} must be a non-negative integer`);
|
|
4
4
|
return value;
|
|
@@ -7,7 +7,6 @@ const positiveInteger = (name, value) => {
|
|
|
7
7
|
if (!Number.isSafeInteger(value) || value < 1) throw new Error(`${name} must be a positive integer`);
|
|
8
8
|
return value;
|
|
9
9
|
};
|
|
10
|
-
//#endregion
|
|
11
10
|
export { positiveInteger as n, nonNegativeInteger as t };
|
|
12
11
|
|
|
13
|
-
//# sourceMappingURL=limits-
|
|
12
|
+
//# sourceMappingURL=limits-B4hHpyfE.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"limits-
|
|
1
|
+
{"version":3,"file":"limits-B4hHpyfE.mjs","names":[],"sources":["../src/limits.ts"],"sourcesContent":["export const nonNegativeInteger = (name: string, value: number): number => {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new Error(`foldkit-media: ${name} must be a non-negative integer`)\n }\n return value\n}\n\nexport const positiveInteger = (name: string, value: number): number => {\n if (!Number.isSafeInteger(value) || value < 1) {\n throw new Error(`${name} must be a positive integer`)\n }\n return value\n}\n"],"mappings":";AAAA,MAAa,sBAAsB,MAAc,UAA0B;CACzE,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,MAAM,IAAI,MAAM,kBAAkB,KAAK,gCAAgC;CAEzE,OAAO;AACT;AAEA,MAAa,mBAAmB,MAAc,UAA0B;CACtE,IAAI,CAAC,OAAO,cAAc,KAAK,KAAK,QAAQ,GAC1C,MAAM,IAAI,MAAM,GAAG,KAAK,4BAA4B;CAEtD,OAAO;AACT"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { n as HashedAsset, r as ImageAsset } from "./asset-
|
|
2
|
-
import { i as Format, r as Encoding, t as Widths } from "./widths-
|
|
3
|
-
import { t as Space } from "./variant-
|
|
1
|
+
import { n as HashedAsset, r as ImageAsset } from "./asset-BLo8VWmd.mjs";
|
|
2
|
+
import { i as Format, r as Encoding, t as Widths } from "./widths-upkgLdek.mjs";
|
|
3
|
+
import { t as Space } from "./variant-B-vyMmFB.mjs";
|
|
4
4
|
import { Option } from "effect";
|
|
5
5
|
declare namespace provider_d_exports {
|
|
6
6
|
export { File, Hosted, Provider, Request, cdnCgi, fromFiles, hosted };
|
|
@@ -76,6 +76,5 @@ declare const hosted: (options?: {
|
|
|
76
76
|
readonly fallback?: Format;
|
|
77
77
|
readonly quality?: number;
|
|
78
78
|
}) => Hosted;
|
|
79
|
-
//#endregion
|
|
80
79
|
export { Provider as n, provider_d_exports as r, Hosted as t };
|
|
81
|
-
//# sourceMappingURL=provider-
|
|
80
|
+
//# sourceMappingURL=provider-CB0nqu0m.d.mts.map
|