foldkit-media 0.3.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +65 -4
- package/dist/{asset-BLo8VWmd.d.mts → asset.d.ts} +10 -11
- package/dist/asset.d.ts.map +1 -0
- package/dist/asset.js +66 -0
- package/dist/asset.js.map +1 -0
- package/dist/browser/index.d.ts +15 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +69 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/browser/{index.d.mts → upload.d.ts} +5 -16
- package/dist/browser/upload.d.ts.map +1 -0
- package/dist/browser/upload.js +87 -0
- package/dist/browser/upload.js.map +1 -0
- package/dist/cloudflare/{index.d.mts → index.d.ts} +8 -6
- package/dist/cloudflare/index.d.ts.map +1 -0
- package/dist/cloudflare/{index.mjs → index.js} +35 -15
- package/dist/cloudflare/index.js.map +1 -0
- package/dist/describe.d.ts +32 -0
- package/dist/describe.d.ts.map +1 -0
- package/dist/describe.js +30 -0
- package/dist/describe.js.map +1 -0
- package/dist/format.d.ts +12 -0
- package/dist/format.d.ts.map +1 -0
- package/dist/{format-BCRTFU9j.mjs → format.js} +2 -2
- package/dist/format.js.map +1 -0
- package/dist/{icon-BGtxExTN.d.mts → icon.d.ts} +14 -17
- package/dist/icon.d.ts.map +1 -0
- package/dist/{icon-0A2dBtqj.mjs → icon.js} +2 -12
- package/dist/icon.js.map +1 -0
- package/dist/icons/{index.d.mts → index.d.ts} +2 -2
- package/dist/icons/index.d.ts.map +1 -0
- package/dist/icons/{index.mjs → index.js} +2 -2
- package/dist/icons/index.js.map +1 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/layout.d.ts +60 -0
- package/dist/layout.d.ts.map +1 -0
- package/dist/layout.js +72 -0
- package/dist/layout.js.map +1 -0
- package/dist/limits.d.ts +3 -0
- package/dist/limits.d.ts.map +1 -0
- package/dist/{limits-B4hHpyfE.mjs → limits.js} +2 -2
- package/dist/limits.js.map +1 -0
- package/dist/picture.d.ts +88 -0
- package/dist/picture.d.ts.map +1 -0
- package/dist/picture.js +113 -0
- package/dist/picture.js.map +1 -0
- package/dist/placeholder.d.ts +16 -0
- package/dist/placeholder.d.ts.map +1 -0
- package/dist/placeholder.js +38 -0
- package/dist/placeholder.js.map +1 -0
- package/dist/{provider-CB0nqu0m.d.mts → provider.d.ts} +16 -19
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +93 -0
- package/dist/provider.js.map +1 -0
- package/dist/server/admission.d.ts +31 -0
- package/dist/server/admission.d.ts.map +1 -0
- package/dist/server/admission.js +41 -0
- package/dist/server/admission.js.map +1 -0
- package/dist/server/api.d.ts +14 -0
- package/dist/server/api.d.ts.map +1 -0
- package/dist/server/api.js +21 -0
- package/dist/server/api.js.map +1 -0
- package/dist/server/diagnostics.d.ts +53 -0
- package/dist/server/diagnostics.d.ts.map +1 -0
- package/dist/server/diagnostics.js +50 -0
- package/dist/server/diagnostics.js.map +1 -0
- package/dist/server/errors.d.ts +24 -0
- package/dist/server/errors.d.ts.map +1 -0
- package/dist/{errors-BhEgXJ4m.mjs → server/errors.js} +2 -2
- package/dist/server/errors.js.map +1 -0
- package/dist/server/facts.d.ts +36 -0
- package/dist/server/facts.d.ts.map +1 -0
- package/dist/server/facts.js +126 -0
- package/dist/server/facts.js.map +1 -0
- package/dist/server/fetch.d.ts +29 -0
- package/dist/server/fetch.d.ts.map +1 -0
- package/dist/server/fetch.js +32 -0
- package/dist/server/fetch.js.map +1 -0
- package/dist/server/handlers.d.ts +48 -0
- package/dist/server/handlers.d.ts.map +1 -0
- package/dist/server/handlers.js +151 -0
- package/dist/server/handlers.js.map +1 -0
- package/dist/server/headers.d.ts +47 -0
- package/dist/server/headers.d.ts.map +1 -0
- package/dist/server/headers.js +134 -0
- package/dist/server/headers.js.map +1 -0
- package/dist/server/index.d.ts +13 -0
- package/dist/server/index.js +12 -0
- package/dist/server/materialize.d.ts +36 -0
- package/dist/server/materialize.d.ts.map +1 -0
- package/dist/server/materialize.js +62 -0
- package/dist/server/materialize.js.map +1 -0
- package/dist/{services-BZoK2VOY.d.mts → server/services.d.ts} +12 -12
- package/dist/server/services.d.ts.map +1 -0
- package/dist/{services-7B4hsQM7.mjs → server/services.js} +3 -3
- package/dist/server/services.js.map +1 -0
- package/dist/server/stores.d.ts +27 -0
- package/dist/server/stores.d.ts.map +1 -0
- package/dist/server/stores.js +62 -0
- package/dist/server/stores.js.map +1 -0
- package/dist/server/upload.d.ts +113 -0
- package/dist/server/upload.d.ts.map +1 -0
- package/dist/server/upload.js +185 -0
- package/dist/server/upload.js.map +1 -0
- package/dist/sharp/{index.d.mts → index.d.ts} +3 -3
- package/dist/sharp/index.d.ts.map +1 -0
- package/dist/sharp/{index.mjs → index.js} +11 -9
- package/dist/sharp/index.js.map +1 -0
- package/dist/unpic/{index.d.mts → index.d.ts} +5 -4
- package/dist/unpic/index.d.ts.map +1 -0
- package/dist/unpic/{index.mjs → index.js} +3 -3
- package/dist/unpic/index.js.map +1 -0
- package/dist/{variant-B-vyMmFB.d.mts → variant.d.ts} +15 -18
- package/dist/variant.d.ts.map +1 -0
- package/dist/variant.js +75 -0
- package/dist/variant.js.map +1 -0
- package/dist/vite/{index.d.mts → icons.d.ts} +1 -19
- package/dist/vite/icons.d.ts.map +1 -0
- package/dist/vite/icons.js +178 -0
- package/dist/vite/icons.js.map +1 -0
- package/dist/vite/images.d.ts +20 -0
- package/dist/vite/images.d.ts.map +1 -0
- package/dist/vite/images.js +167 -0
- package/dist/vite/images.js.map +1 -0
- package/dist/vite/index.d.ts +3 -0
- package/dist/vite/index.js +3 -0
- package/dist/widths.d.ts +22 -0
- package/dist/widths.d.ts.map +1 -0
- package/dist/{widths-qp3jshiF.mjs → widths.js} +2 -8
- package/dist/widths.js.map +1 -0
- package/package.json +22 -21
- package/dist/asset-BLo8VWmd.d.mts.map +0 -1
- package/dist/browser/index.d.mts.map +0 -1
- package/dist/browser/index.mjs +0 -150
- package/dist/browser/index.mjs.map +0 -1
- package/dist/cloudflare/index.d.mts.map +0 -1
- package/dist/cloudflare/index.mjs.map +0 -1
- package/dist/describe-BOgc0xbR.d.mts +0 -52
- package/dist/describe-BOgc0xbR.d.mts.map +0 -1
- package/dist/describe-C6sWA_8p.mjs +0 -171
- package/dist/describe-C6sWA_8p.mjs.map +0 -1
- package/dist/errors-BhEgXJ4m.mjs.map +0 -1
- package/dist/format-BCRTFU9j.mjs.map +0 -1
- package/dist/icon-0A2dBtqj.mjs.map +0 -1
- package/dist/icon-BGtxExTN.d.mts.map +0 -1
- package/dist/icons/index.d.mts.map +0 -1
- package/dist/icons/index.mjs.map +0 -1
- package/dist/index.d.mts +0 -157
- package/dist/index.d.mts.map +0 -1
- package/dist/index.mjs +0 -322
- package/dist/index.mjs.map +0 -1
- package/dist/limits-B4hHpyfE.mjs.map +0 -1
- package/dist/provider-CB0nqu0m.d.mts.map +0 -1
- package/dist/rolldown-runtime-BJohB4LM.mjs +0 -13
- package/dist/server/index.d.mts +0 -170
- package/dist/server/index.d.mts.map +0 -1
- package/dist/server/index.mjs +0 -231
- package/dist/server/index.mjs.map +0 -1
- package/dist/services-7B4hsQM7.mjs.map +0 -1
- package/dist/services-BZoK2VOY.d.mts.map +0 -1
- package/dist/sharp/index.d.mts.map +0 -1
- package/dist/sharp/index.mjs.map +0 -1
- package/dist/stores-CxraN3kt.mjs +0 -490
- package/dist/stores-CxraN3kt.mjs.map +0 -1
- package/dist/unpic/index.d.mts.map +0 -1
- package/dist/unpic/index.mjs.map +0 -1
- package/dist/upload-lVLMRJoC.d.mts +0 -160
- package/dist/upload-lVLMRJoC.d.mts.map +0 -1
- package/dist/variant-B-vyMmFB.d.mts.map +0 -1
- package/dist/vite/index.d.mts.map +0 -1
- package/dist/vite/index.mjs +0 -328
- package/dist/vite/index.mjs.map +0 -1
- package/dist/widths-qp3jshiF.mjs.map +0 -1
- package/dist/widths-upkgLdek.d.mts +0 -36
- package/dist/widths-upkgLdek.d.mts.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/cloudflare/index.ts"],"sourcesContent":["/**\n * The media server's services on Cloudflare: originals in R2, the Images\n * binding as the transformer, and variants kept in R2 behind the Cache API.\n * Each takes the binding it needs, so build them in `serveFetch`'s `layer`\n * from the request's environment.\n */\nimport type {\n Cache,\n CacheStorage,\n ImagesBinding,\n R2Bucket,\n RateLimit,\n} from '@cloudflare/workers-types'\nimport { Effect, Layer, Option } from 'effect'\nimport { KeyValueStore } from 'effect/persistence'\nimport { Diagnostics } from 'foldkit-surface'\nimport { Admission, RateLimited } from '../server/admission.js'\nimport { admissionFailed, imageFailed, storeFailed } from '../server/diagnostics.js'\nimport { Inspector } from '../describe.js'\nimport { OriginalNotFound, QuotaExhausted, TransformFailed } from '../server/errors.js'\nimport { Originals, Transformer, Variants, type Encoded, type Kept } from '../server/services.js'\nimport { StoredFacts, Uploads, decodeFacts, encodeFacts, factsKey } from '../server/upload.js'\nimport { makeVariants } from '../server/stores.js'\n\n/** Originals in an R2 bucket, each under its content hash. */\nexport const originalsR2 = (bucket: R2Bucket): Layer.Layer<Originals> =>\n Layer.succeed(Originals, {\n get: hash =>\n Effect.promise(() => bucket.get(hash)).pipe(\n Effect.flatMap(object =>\n object === null\n ? Effect.fail(new OriginalNotFound({ hash }))\n : Effect.succeed({\n // The two runtimes' stream types differ only in their declarations.\n body: object.body as unknown as ReadableStream<Uint8Array>,\n size: object.size,\n }),\n ),\n ),\n })\n\n/**\n * Uploads into an R2 bucket, each under its content hash, what `originalsR2`\n * reads, and its facts under `facts/<hash>`, what `storedFactsR2` reads.\n */\nexport const uploadsR2 = (bucket: R2Bucket): Layer.Layer<Uploads> =>\n Layer.succeed(Uploads, {\n put: (hash, bytes, facts) =>\n Effect.promise(async () => {\n await bucket.put(hash, bytes)\n await bucket.put(factsKey(hash), encodeFacts(facts))\n }),\n })\n\n/** An upload's facts, read back from the bucket `uploadsR2` keeps them in. */\nexport const storedFactsR2 = (bucket: R2Bucket): Layer.Layer<StoredFacts> =>\n Layer.succeed(StoredFacts, {\n get: hash =>\n Effect.promise(async () => {\n const object = await bucket.get(factsKey(hash))\n return object === null ? Option.none() : Option.some(decodeFacts(await object.text()))\n }),\n })\n\n// Cloudflare's code for a spent transformation allowance.\nconst QUOTA_EXHAUSTED = 9422\n\nconst isImagesError = (cause: unknown): cause is { readonly code: number } =>\n typeof cause === 'object' && cause !== null && typeof Reflect.get(cause, 'code') === 'number'\n\n/**\n * The Images binding as the transformer. It scales down, never up, and names\n * the format, so the variant is what its URL says. A spent allowance is\n * `QuotaExhausted`; any other refusal is `TransformFailed`, its reason logged.\n */\nexport const transformerImages = (images: ImagesBinding): Layer.Layer<Transformer> =>\n Layer.succeed(Transformer, {\n transform: (original, variant) =>\n Effect.tryPromise({\n try: async () => {\n const result = await images\n .input(original.body as unknown as Parameters<ImagesBinding['input']>[0])\n .transform({ width: variant.width, fit: 'scale-down' })\n .output({\n format: `image/${variant.format}`,\n ...Option.match(variant.quality, {\n onNone: () => ({}),\n onSome: quality => ({ quality }),\n }),\n })\n const response = result.response()\n return {\n bytes: new Uint8Array(await response.arrayBuffer()),\n contentType: result.contentType(),\n }\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch((cause): Effect.Effect<never, QuotaExhausted | TransformFailed> =>\n isImagesError(cause) && cause.code === QUOTA_EXHAUSTED\n ? Effect.fail(new QuotaExhausted({}))\n : Diagnostics.report(imageFailed('transform', cause)).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n ),\n ),\n ),\n })\n\n/**\n * An R2 bucket as an Effect `KeyValueStore`, for anything that keeps bytes by\n * key: `variantsKeyValueStore`, `originalsKeyValueStore`, or the\n * application's own. `keys`, `clear` and `size` list the whole bucket.\n */\nexport const keyValueStoreR2 = (bucket: R2Bucket): Layer.Layer<KeyValueStore.KeyValueStore> =>\n Layer.succeed(KeyValueStore.KeyValueStore, r2Store(bucket))\n\nconst r2Store = (bucket: R2Bucket): KeyValueStore.KeyValueStore => {\n const attempt = <A>(method: string, key: string | undefined, run: () => Promise<A>) =>\n Effect.tryPromise({\n try: run,\n catch: cause =>\n new KeyValueStore.KeyValueStoreError({\n message: `R2 ${method} failed`,\n method,\n ...(key === undefined ? {} : { key }),\n cause,\n }),\n })\n // Every key in the bucket, a page of listing at a time.\n const allKeys = async () => {\n const found: Array<string> = []\n let cursor: string | undefined\n do {\n const page = await bucket.list(cursor === undefined ? {} : { cursor })\n found.push(...page.objects.map(object => object.key))\n cursor = page.truncated ? page.cursor : undefined\n } while (cursor !== undefined)\n return found\n }\n return KeyValueStore.make({\n get: key => attempt('get', key, async () => (await bucket.get(key))?.text()),\n getUint8Array: key =>\n attempt('getUint8Array', key, async () => {\n const object = await bucket.get(key)\n return object === null ? undefined : new Uint8Array(await object.arrayBuffer())\n }),\n set: (key, value) => attempt('set', key, async () => void (await bucket.put(key, value))),\n remove: key => attempt('remove', key, () => bucket.delete(key)),\n clear: attempt('clear', undefined, async () => {\n const all = await allKeys()\n // R2 deletes at most 1,000 keys a call.\n for (let at = 0; at < all.length; at += 1000) await bucket.delete(all.slice(at, at + 1000))\n }),\n size: attempt('size', undefined, async () => (await allKeys()).length),\n keys: attempt('keys', undefined, allKeys),\n })\n}\n\n// The Cache API keys by request; this origin is never fetched.\nconst edgeKey = (key: string) => `https://foldkit-media.invalid/${key}`\n\n/**\n * Variants with the edge's Cache API in front: read there first, and filled\n * from what is kept behind it, so a popular variant is served from the edge.\n */\nconst withEdge = (behind: Variants['Service'], edge: Cache): Variants['Service'] => {\n const fill = (key: string, encoded: Encoded) =>\n Effect.tryPromise({\n try: () =>\n edge.put(\n edgeKey(key),\n // The page's Response and workers-types' differ only in their declarations.\n new Response(encoded.bytes, {\n headers: {\n 'content-type': encoded.contentType,\n 'cache-control': 'public, max-age=31536000, immutable',\n },\n }) as never,\n ),\n catch: cause => cause,\n }).pipe(\n Effect.catch(cause =>\n Diagnostics.report(storeFailed({ store: 'edge', operation: 'write', key, cause })),\n ),\n )\n const behindEdge = (key: string) =>\n behind.get(key).pipe(\n Effect.tap(found =>\n Option.match(found, {\n onNone: () => Effect.void,\n onSome: kept => fill(key, kept.encoded),\n }),\n ),\n )\n return {\n get: key =>\n Effect.tryPromise({\n try: async () => {\n const hit = await edge.match(edgeKey(key))\n return hit === undefined\n ? Option.none<Kept>()\n : Option.some({\n encoded: {\n bytes: new Uint8Array(await hit.arrayBuffer()),\n contentType: hit.headers.get('content-type') ?? 'application/octet-stream',\n },\n from: 'edge' as const,\n })\n },\n catch: cause => cause,\n }).pipe(\n Effect.catch(cause =>\n Diagnostics.report(storeFailed({ store: 'edge', operation: 'read', key, cause })).pipe(\n Effect.as(Option.none<Kept>()),\n ),\n ),\n Effect.flatMap(found => (Option.isSome(found) ? Effect.succeed(found) : behindEdge(key))),\n ),\n put: (key, encoded) => behind.put(key, encoded).pipe(Effect.andThen(fill(key, encoded))),\n }\n}\n\n// A Worker's global, which the DOM's `CacheStorage` declares without `default`.\ndeclare const caches: CacheStorage | undefined\n\nconst cacheOf = (cache: Cache | true): Cache => {\n if (cache !== true) return cache\n if (typeof caches === 'undefined') {\n throw new Error(\n 'variantsR2: `cache: true` reads the Worker global `caches.default`, which this runtime lacks',\n )\n }\n return caches.default\n}\n\n/**\n * Variants kept in R2 under `prefix`, so one made last month is not made, and\n * billed, again: `variantsKeyValueStore` over `keyValueStoreR2`. With `cache`,\n * the Cache API stands in front of it: `true` for the Worker's\n * `caches.default`, or a cache of your own (`await caches.open(…)`).\n */\nexport const variantsR2 = (\n bucket: R2Bucket,\n options: { readonly prefix?: string; readonly cache?: Cache | true } = {},\n): Layer.Layer<Variants> => {\n const kept = makeVariants(KeyValueStore.prefix(r2Store(bucket), options.prefix ?? 'variants/'))\n return Layer.succeed(\n Variants,\n Option.match(Option.fromNullishOr(options.cache), {\n onNone: () => kept,\n onSome: cache => withEdge(kept, cacheOf(cache)),\n }),\n )\n}\n\n/**\n * Admission through a Workers rate-limit binding (`[[ratelimits]]`), whose\n * limit and period are its configuration. It answers yes or no, not when, so\n * a refusal says to retry after `retryAfterSeconds` (the binding's period, 60\n * by default). A binding that fails admits the request, reported as\n * `AdmissionFailed`.\n */\nexport const admissionRateLimit = (\n binding: RateLimit,\n options: { readonly retryAfterSeconds?: number } = {},\n): Layer.Layer<Admission> =>\n Layer.succeed(Admission, {\n admit: client =>\n Effect.tryPromise(() => binding.limit({ key: `foldkit-media:${client}` })).pipe(\n Effect.catch(cause =>\n Diagnostics.report(admissionFailed({ limiter: 'binding', client, cause })).pipe(\n Effect.as({ success: true }),\n ),\n ),\n Effect.flatMap(({ success }) =>\n success\n ? Effect.void\n : Effect.fail(new RateLimited({ retryAfterSeconds: options.retryAfterSeconds ?? 60 })),\n ),\n ),\n })\n\n/**\n * The `Inspector` through the Images binding: an original's size from `info`,\n * which costs no transformation. It makes no thumbnail, since raw pixels are\n * not offered offline and could not be tested, so an original described here\n * has no ThumbHash; and as `info` does not say whether pixels are\n * transparent, every format but JPEG is taken to be, which costs a\n * placeholder, never shows a wrong one. An SVG, which has no size in pixels,\n * is refused.\n */\nexport const inspectorImages = (images: ImagesBinding): Layer.Layer<Inspector> =>\n Layer.succeed(Inspector, {\n inspect: bytes =>\n Effect.tryPromise({\n try: () =>\n images.info(\n new Blob([bytes]).stream() as unknown as Parameters<ImagesBinding['info']>[0],\n ),\n catch: cause => cause,\n }).pipe(\n Effect.flatMap(info =>\n // An SVG's answer has no width: it has no size in pixels.\n 'width' in info\n ? Effect.succeed({\n width: info.width,\n height: info.height,\n alpha: info.format !== 'image/jpeg',\n thumbnail: Option.none(),\n })\n : Effect.fail(info),\n ),\n Effect.catch(cause =>\n Diagnostics.report(imageFailed('inspect', cause)).pipe(\n Effect.andThen(Effect.fail(new TransformFailed({}))),\n ),\n ),\n ),\n })\n"],"mappings":";;;;;;;;;;;;AAyBA,MAAa,eAAe,WAC1B,MAAM,QAAQ,WAAW,EACvB,MAAK,SAC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BAAgB;CAAE,SAAS;CAAW;CAAQ;AAAM,CAAC,CAAC,CAAC,CAAC,KACzE,OAAO,GAAG,EAAE,SAAS,KAAK,CAAC,CAC7B,CACF,GACA,OAAO,SAAS,EAAE,cAChB,UACI,OAAO,OACP,OAAO,KAAK,IAAI,YAAY,EAAE,mBAAmB,QAAQ,qBAAqB,GAAG,CAAC,CAAC,CACzF,CACF,EACJ,CAAC;;;;;;;;;;AAWH,MAAa,mBAAmB,WAC9B,MAAM,QAAQ,WAAW,EACvB,UAAS,UACP,OAAO,WAAW;CAChB,WACE,OAAO,KACL,IAAI,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,OAAO,CAC3B;CACF,QAAO,UAAS;AAClB,CAAC,CAAC,CAAC,KACD,OAAO,SAAQ,SAEb,WAAW,OACP,OAAO,QAAQ;CACb,OAAO,KAAK;CACZ,QAAQ,KAAK;CACb,OAAO,KAAK,WAAW;CACvB,WAAW,OAAO,KAAK;AACzB,CAAC,IACD,OAAO,KAAK,IAAI,CACtB,GACA,OAAO,OAAM,UACX,YAAY,OAAO,YAAY,WAAW,KAAK,CAAC,CAAC,CAAC,KAChD,OAAO,QAAQ,OAAO,KAAK,IAAI,gBAAgB,CAAC,CAAC,CAAC,CAAC,CACrD,CACF,CACF,EACJ,CAAC"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { Context, Effect, Option } from "effect";
|
|
2
|
+
import { ImageAsset } from "./asset.js";
|
|
3
|
+
import { OriginalTooLarge, TransformFailed } from "./server/errors.js";
|
|
4
|
+
/** A picture at most 100 pixels a side, as raw RGBA: what a ThumbHash is made from. */
|
|
5
|
+
export interface Thumbnail {
|
|
6
|
+
readonly width: number;
|
|
7
|
+
readonly height: number;
|
|
8
|
+
readonly rgba: Uint8Array;
|
|
9
|
+
}
|
|
10
|
+
/** What an inspector reads of an original. */
|
|
11
|
+
export interface Inspected {
|
|
12
|
+
readonly width: number;
|
|
13
|
+
readonly height: number;
|
|
14
|
+
/** Whether it may have transparent pixels; an inspector that cannot tell says yes. */
|
|
15
|
+
readonly alpha: boolean;
|
|
16
|
+
/** None where the inspector cannot make one (the Images binding offline makes no raw pixels). */
|
|
17
|
+
readonly thumbnail: Option.Option<Thumbnail>;
|
|
18
|
+
}
|
|
19
|
+
declare const Inspector_base: Context.ServiceClass<Inspector, "foldkit-media/Inspector", {
|
|
20
|
+
readonly inspect: (bytes: Uint8Array<ArrayBuffer>) => Effect.Effect<Inspected, TransformFailed | OriginalTooLarge>;
|
|
21
|
+
}>;
|
|
22
|
+
/** Reads an original's facts: its size, its alpha, and a thumbnail. */
|
|
23
|
+
export declare class Inspector extends Inspector_base {}
|
|
24
|
+
/**
|
|
25
|
+
* An original's facts, as an `ImageAsset` under `key`: its size and alpha
|
|
26
|
+
* from the `Inspector`, its SHA-256, and a ThumbHash placeholder where the
|
|
27
|
+
* inspector made a thumbnail. Where an original enters (an upload, a build, a
|
|
28
|
+
* page's content naming a URL), so its facts are derived once and stored.
|
|
29
|
+
*/
|
|
30
|
+
export declare const describe: (key: string, bytes: Uint8Array<ArrayBuffer>) => Effect.Effect<ImageAsset, TransformFailed | OriginalTooLarge, Inspector>;
|
|
31
|
+
export {};
|
|
32
|
+
//# sourceMappingURL=describe.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"describe.d.ts","names":[],"sources":["../src/describe.ts"],"mappings":";;;;iBAMiB;WACN;WACA;WACA,MAAM;;;iBAIA;WACN;WACA;;WAEA;;WAEA,WAAW,OAAO,OAAO;;;WAOd,UAChB,OAAO,WAAW,iBACf,OAAO,OAAO,WAAW,kBAAkB;;;qBALvC,kBAAkB;;;;;;;qBAoBlB,WAAQ,aACR,OACJ,WAAW,iBACjB,OAAO,OAAO,YAAY,kBAAkB,kBAAkB"}
|
package/dist/describe.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { Context, Effect, Option } from "effect";
|
|
2
|
+
import { rgbaToThumbHash } from "thumbhash";
|
|
3
|
+
import { Placeholder } from "./asset.js";
|
|
4
|
+
// src/describe.ts
|
|
5
|
+
/** Reads an original's facts: its size, its alpha, and a thumbnail. */
|
|
6
|
+
var Inspector = class extends Context.Service()("foldkit-media/Inspector") {};
|
|
7
|
+
const hex = (buffer) => Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
8
|
+
const base64 = (bytes) => btoa(String.fromCharCode(...bytes));
|
|
9
|
+
/**
|
|
10
|
+
* An original's facts, as an `ImageAsset` under `key`: its size and alpha
|
|
11
|
+
* from the `Inspector`, its SHA-256, and a ThumbHash placeholder where the
|
|
12
|
+
* inspector made a thumbnail. Where an original enters (an upload, a build, a
|
|
13
|
+
* page's content naming a URL), so its facts are derived once and stored.
|
|
14
|
+
*/
|
|
15
|
+
const describe = (key, bytes) => Effect.gen(function* () {
|
|
16
|
+
const inspected = yield* Inspector.use((inspector) => inspector.inspect(bytes));
|
|
17
|
+
const digest = yield* Effect.promise(() => crypto.subtle.digest("SHA-256", bytes));
|
|
18
|
+
return {
|
|
19
|
+
key,
|
|
20
|
+
width: inspected.width,
|
|
21
|
+
height: inspected.height,
|
|
22
|
+
alpha: inspected.alpha,
|
|
23
|
+
hash: Option.some(hex(digest)),
|
|
24
|
+
placeholder: Option.map(inspected.thumbnail, ({ width, height, rgba }) => Placeholder.cases.ThumbHash.make({ hash: base64(rgbaToThumbHash(width, height, rgba)) })),
|
|
25
|
+
focus: Option.none()
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
export { Inspector, describe };
|
|
29
|
+
|
|
30
|
+
//# sourceMappingURL=describe.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"describe.js","names":[],"sources":["../src/describe.ts"],"sourcesContent":["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":";;;;;AAuBA,IAAa,YAAb,cAA+B,QAAQ,QAOrC,CAAC,CAAC,yBAAyB,CAAC,CAAC,CAAC;AAEhC,MAAM,OAAO,WACX,MAAM,KAAK,IAAI,WAAW,MAAM,IAAG,SAAQ,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,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"}
|
package/dist/format.d.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
/** An encoding a variant can be written in. */
|
|
3
|
+
export declare const Format: Schema.Literals<readonly ["avif", "webp", "jpeg", "png"]>;
|
|
4
|
+
export type Format = typeof Format.Type;
|
|
5
|
+
/**
|
|
6
|
+
* What a provider is asked for: a format, or `auto` for a provider that picks
|
|
7
|
+
* the format itself from the request's `Accept`.
|
|
8
|
+
*/
|
|
9
|
+
export type Encoding = Format | 'auto';
|
|
10
|
+
/** The media type a `source` element names. */
|
|
11
|
+
export declare const mimeType: (format: Format) => string;
|
|
12
|
+
//# sourceMappingURL=format.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format.d.ts","names":[],"sources":["../src/format.ts"],"mappings":";;qBAGa,QAAM,OAAA;YACP,gBAAgB,OAAO;;;;;YAMvB,WAAW;;qBAUV,WAAQ,QAAY"}
|
|
@@ -15,6 +15,6 @@ const mimeTypes = {
|
|
|
15
15
|
};
|
|
16
16
|
/** The media type a `source` element names. */
|
|
17
17
|
const mimeType = (format) => mimeTypes[format];
|
|
18
|
-
export {
|
|
18
|
+
export { Format, mimeType };
|
|
19
19
|
|
|
20
|
-
//# sourceMappingURL=format
|
|
20
|
+
//# sourceMappingURL=format.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"format.js","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,6 +1,3 @@
|
|
|
1
|
-
declare namespace icon_d_exports {
|
|
2
|
-
export { IconData, Stroke, SvgBuilder, SvgNode, SvgTag, TAGS, draw, key, maskUrl, prefixIds, serialize, withStroke };
|
|
3
|
-
}
|
|
4
1
|
/**
|
|
5
2
|
* An icon as data: what a build reads from an icon set or an SVG file, parsed
|
|
6
3
|
* (`foldkit-media/icons`), not markup to set as HTML. A view draws it
|
|
@@ -8,34 +5,34 @@ declare namespace icon_d_exports {
|
|
|
8
5
|
* from the one value.
|
|
9
6
|
*/
|
|
10
7
|
/** The elements an icon may hold: presentational SVG, nothing that runs, loads or holds text. */
|
|
11
|
-
declare const TAGS: readonly ['g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline', 'polygon', 'defs', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'use'];
|
|
12
|
-
type SvgTag = (typeof TAGS)[number];
|
|
8
|
+
export declare const TAGS: readonly ['g', 'path', 'circle', 'ellipse', 'rect', 'line', 'polyline', 'polygon', 'defs', 'linearGradient', 'radialGradient', 'stop', 'clipPath', 'mask', 'use'];
|
|
9
|
+
export type SvgTag = (typeof TAGS)[number];
|
|
13
10
|
/** One element of an icon's drawing, and its children. */
|
|
14
|
-
interface SvgNode {
|
|
11
|
+
export interface SvgNode {
|
|
15
12
|
readonly tag: SvgTag;
|
|
16
13
|
readonly attributes: Readonly<Record<string, string>>;
|
|
17
14
|
readonly children: ReadonlyArray<SvgNode>;
|
|
18
15
|
}
|
|
19
16
|
/** An icon: its `viewBox`, the attributes its root `svg` carries (its fill and stroke), and its drawing. */
|
|
20
|
-
interface IconData {
|
|
17
|
+
export interface IconData {
|
|
21
18
|
readonly viewBox: string;
|
|
22
19
|
readonly attributes: Readonly<Record<string, string>>;
|
|
23
20
|
readonly nodes: ReadonlyArray<SvgNode>;
|
|
24
21
|
}
|
|
25
22
|
/** The icon as one standalone `svg` document. */
|
|
26
|
-
declare const serialize: (icon: IconData) => string;
|
|
23
|
+
export declare const serialize: (icon: IconData) => string;
|
|
27
24
|
/**
|
|
28
25
|
* The icon as a CSS `url()`, for a mask (`Icons.byAttribute`, `Icons.glyph`):
|
|
29
26
|
* a mask reads only the drawing's shape, so its colours do not matter, and
|
|
30
27
|
* the element it masks paints in `currentColor`.
|
|
31
28
|
*/
|
|
32
|
-
declare const maskUrl: (icon: IconData) => string;
|
|
29
|
+
export declare const maskUrl: (icon: IconData) => string;
|
|
33
30
|
/**
|
|
34
31
|
* A short name for the icon, from its content: the same drawing has the same
|
|
35
32
|
* key on a server and in the browser, and two drawings almost never share
|
|
36
33
|
* one. A drawing's ids are prefixed with it, and a sprite names its symbol by it.
|
|
37
34
|
*/
|
|
38
|
-
declare const key: (icon: IconData) => string;
|
|
35
|
+
export declare const key: (icon: IconData) => string;
|
|
39
36
|
/**
|
|
40
37
|
* The icon with each id it defines, and each `href` and `url()` naming one,
|
|
41
38
|
* prefixed: two icons drawn inline on one page share the document's ids, and
|
|
@@ -44,9 +41,9 @@ declare const key: (icon: IconData) => string;
|
|
|
44
41
|
* reaches a CSS `url()`. An icon with no ids is returned as it was given.
|
|
45
42
|
* Kept per icon and prefix, since a view asks again on every render.
|
|
46
43
|
*/
|
|
47
|
-
declare const prefixIds: (icon: IconData, prefix: string) => IconData;
|
|
44
|
+
export declare const prefixIds: (icon: IconData, prefix: string) => IconData;
|
|
48
45
|
/** How a drawing's strokes are drawn: their width, and whether their ends and joins are round. */
|
|
49
|
-
interface Stroke {
|
|
46
|
+
export interface Stroke {
|
|
50
47
|
readonly width?: number | undefined;
|
|
51
48
|
readonly corners?: 'round' | 'square' | undefined;
|
|
52
49
|
}
|
|
@@ -56,14 +53,14 @@ interface Stroke {
|
|
|
56
53
|
* none. A filled icon draws no stroke, so it is unchanged in what shows. For
|
|
57
54
|
* a mask, whose drawing CSS cannot reach once it is a `url()`.
|
|
58
55
|
*/
|
|
59
|
-
declare const withStroke: (icon: IconData, stroke: Stroke) => IconData;
|
|
56
|
+
export declare const withStroke: (icon: IconData, stroke: Stroke) => IconData;
|
|
60
57
|
type Element<Node, Attribute> = (attributes: ReadonlyArray<Attribute>, children: ReadonlyArray<Node>) => Node;
|
|
61
58
|
/**
|
|
62
59
|
* What `draw` needs of a view's builder: an element per tag an icon may hold,
|
|
63
60
|
* and raw attributes. Foldkit's `HtmlBuilder` is one, so this package needs
|
|
64
61
|
* no view library of its own.
|
|
65
62
|
*/
|
|
66
|
-
type SvgBuilder<Node, Attribute> = {
|
|
63
|
+
export type SvgBuilder<Node, Attribute> = {
|
|
67
64
|
readonly svg: Element<Node, Attribute>;
|
|
68
65
|
readonly Attribute: (name: string, value: string) => Attribute;
|
|
69
66
|
readonly AriaHidden: (value: boolean) => Attribute;
|
|
@@ -80,9 +77,9 @@ type SvgBuilder<Node, Attribute> = {
|
|
|
80
77
|
* for the copy that shows. Each key's drawing is kept for the icon's life, so
|
|
81
78
|
* take keys from a small fixed set (a place on the page), not one per row.
|
|
82
79
|
*/
|
|
83
|
-
declare const draw: <Node, Attribute>(icon: IconData, h: SvgBuilder<Node, Attribute>, options?: {
|
|
80
|
+
export declare const draw: <Node, Attribute>(icon: IconData, h: SvgBuilder<Node, Attribute>, options?: {
|
|
84
81
|
readonly key?: string;
|
|
85
82
|
readonly size?: string;
|
|
86
83
|
}) => Node;
|
|
87
|
-
export {
|
|
88
|
-
//# sourceMappingURL=icon
|
|
84
|
+
export {};
|
|
85
|
+
//# sourceMappingURL=icon.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"icon.d.ts","names":[],"sources":["../src/icon.ts"],"mappings":";;;;;;;qBAQa;YAiBD,iBAAiB;;iBAGZ;WACN,KAAK;WACL,YAAY,SAAS;WACrB,UAAU,cAAc;;;iBAIlB;WACN;WACA,YAAY,SAAS;WACrB,OAAO,cAAc;;;qBAiBnB,YAAS,MAAU;;;;;;qBAQnB,UAAO,MAAU;;;;;;qBAajB,MAAG,MAAU;;;;;;;;;qBA8Cb,YAAS,MAAU,UAAQ,mBAAmB;;iBAqC1C;WACN;WACA;;;;;;;;qBASE,aAAU,MAAU,UAAQ,QAAU,WAAS;KA+BvD,QAAQ,MAAM,cACjB,YAAY,cAAc,YAC1B,UAAU,cAAc,UACrB;;;;;;YAOO,WAAW,MAAM;WAClB,KAAK,QAAQ,MAAM;WACnB,YAAY,cAAc,kBAAkB;WAC5C,aAAa,mBAAmB;gBAC3B,OAAO,SAAS,QAAQ,MAAM;;;;;;;;;;;;;qBAcjC,OAAQ,MAAM,WAAS,MAC5B,UAAQ,GACX,WAAW,MAAM,YAAU;WACV;WAAuB;MAC1C"}
|
|
@@ -1,14 +1,4 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-BJohB4LM.mjs";
|
|
2
1
|
// src/icon.ts
|
|
3
|
-
var icon_exports = /* @__PURE__ */ __exportAll({
|
|
4
|
-
TAGS: () => TAGS,
|
|
5
|
-
draw: () => draw,
|
|
6
|
-
key: () => key,
|
|
7
|
-
maskUrl: () => maskUrl,
|
|
8
|
-
prefixIds: () => prefixIds,
|
|
9
|
-
serialize: () => serialize,
|
|
10
|
-
withStroke: () => withStroke
|
|
11
|
-
});
|
|
12
2
|
/**
|
|
13
3
|
* An icon as data: what a build reads from an icon set or an SVG file, parsed
|
|
14
4
|
* (`foldkit-media/icons`), not markup to set as HTML. A view draws it
|
|
@@ -179,6 +169,6 @@ const draw = (icon, h, options = {}) => {
|
|
|
179
169
|
...written(attributes)
|
|
180
170
|
], nodes.map(drawn));
|
|
181
171
|
};
|
|
182
|
-
export {
|
|
172
|
+
export { TAGS, draw, key, maskUrl, prefixIds, serialize, withStroke };
|
|
183
173
|
|
|
184
|
-
//# sourceMappingURL=icon
|
|
174
|
+
//# sourceMappingURL=icon.js.map
|
package/dist/icon.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"icon.js","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;CAC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AACpD;;;;;;;;;;;;;AA8BA,MAAa,QACX,MACA,GACA,UAA6D,CAAC,MACrD;CACT,MAAM,SAAS,IAAI,IAAI,KAAK,QAAQ,QAAQ,KAAA,IAAY,KAAK,IAAI,QAAQ;CACzE,MAAM,EAAE,SAAS,YAAY,UAAU,UAAU,MAAM,MAAM;CAC7D,MAAM,OAAO,QAAQ,QAAQ;CAC7B,MAAM,WAAW,SACf,OAAO,QAAQ,IAAI,CAAC,CAAC,KAAK,CAAC,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,5 +1,5 @@
|
|
|
1
|
-
import { t as IconData } from "../icon-BGtxExTN.mjs";
|
|
2
1
|
import { Schema } from "effect";
|
|
2
|
+
import { IconData } from "../icon.js";
|
|
3
3
|
/**
|
|
4
4
|
* The icon in `svg`, one whole SVG document, as `IconData`; `name` says which
|
|
5
5
|
* icon a refusal is about. Throws on anything outside the allowlist.
|
|
@@ -46,4 +46,4 @@ export declare const namesOf: (set: IconifySet) => ReadonlyArray<string>;
|
|
|
46
46
|
* rather than drawn as a second, transformed drawing.
|
|
47
47
|
*/
|
|
48
48
|
export declare const fromIconify: (set: IconifySet, name: string) => IconData;
|
|
49
|
-
//# sourceMappingURL=index.d.
|
|
49
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","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"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as TAGS } from "../icon-0A2dBtqj.mjs";
|
|
2
1
|
import { Schema } from "effect";
|
|
2
|
+
import { TAGS } from "../icon.js";
|
|
3
3
|
// src/icons/index.ts
|
|
4
4
|
/**
|
|
5
5
|
* SVG to `IconData`, for builds and generator scripts: a Vite plugin reading
|
|
@@ -316,4 +316,4 @@ const fromIconify = (set, name) => {
|
|
|
316
316
|
};
|
|
317
317
|
export { IconifySet, fromIconify, namesOf, parse };
|
|
318
318
|
|
|
319
|
-
//# sourceMappingURL=index.
|
|
319
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/icons/index.ts"],"sourcesContent":["/**\n * SVG to `IconData`, for builds and generator scripts: a Vite plugin reading\n * an icon set, a script writing a package's icon constants. The parse is where\n * an icon is checked, because it is drawn inline: an element or attribute\n * outside the presentational allowlist, a `style`, an event attribute, or a\n * reference outside the icon fails here, naming the icon, rather than being\n * dropped.\n */\nimport { Schema } from 'effect'\nimport { TAGS, type IconData, type SvgNode, type SvgTag } from '../icon.js'\n\nconst ELEMENTS: ReadonlySet<string> = new Set(TAGS)\nconst isTag = (tag: string): tag is SvgTag => ELEMENTS.has(tag)\n\n/** Words for a reader, which an icon's label replaces; skipped with what they hold. */\nconst DROPPED_ELEMENTS = new Set(['title', 'desc', 'metadata'])\n\nconst PRESENTATION = [\n 'clip-path',\n 'clip-rule',\n 'color',\n 'display',\n 'fill',\n 'fill-opacity',\n 'fill-rule',\n 'mask',\n 'opacity',\n 'paint-order',\n 'shape-rendering',\n 'stroke',\n 'stroke-dasharray',\n 'stroke-dashoffset',\n 'stroke-linecap',\n 'stroke-linejoin',\n 'stroke-miterlimit',\n 'stroke-opacity',\n 'stroke-width',\n 'transform',\n 'vector-effect',\n 'visibility',\n]\n\nconst ATTRIBUTES = new Set([\n ...PRESENTATION,\n 'id',\n 'd',\n 'pathLength',\n 'cx',\n 'cy',\n 'r',\n 'rx',\n 'ry',\n 'x',\n 'y',\n 'x1',\n 'y1',\n 'x2',\n 'y2',\n 'width',\n 'height',\n 'points',\n 'href',\n 'offset',\n 'stop-color',\n 'stop-opacity',\n 'fx',\n 'fy',\n 'fr',\n 'gradientUnits',\n 'gradientTransform',\n 'spreadMethod',\n 'clipPathUnits',\n 'maskUnits',\n 'maskContentUnits',\n])\n\n/** The root keeps what it paints; its size is its container's, so it gives that up. */\nconst ROOT_ATTRIBUTES = new Set(PRESENTATION)\nconst DROPPED_ROOT = new Set(['xmlns', 'xmlns:xlink', 'version', 'width', 'height', 'viewBox'])\nconst ROOT_ALLOWED = new Set([...ROOT_ATTRIBUTES, ...DROPPED_ROOT])\n\nconst ENTITIES: ReadonlyMap<string, string> = new Map([\n ['amp', '&'],\n ['lt', '<'],\n ['gt', '>'],\n ['quot', '\"'],\n ['apos', \"'\"],\n])\n\nconst USER_UNITS = /^\\d+(\\.\\d+)?$/\n\n/**\n * The CSS and SVG functions an attribute may call: colours, transforms, and\n * `url()`, whose target is checked apart. Any other is refused, since a\n * presentation attribute is read as CSS, where `image-set()` or `cross-fade()`\n * fetches a bare URL.\n */\nconst FUNCTIONS: ReadonlySet<string> = new Set([\n 'url',\n 'rgb',\n 'rgba',\n 'hsl',\n 'hsla',\n 'hwb',\n 'lab',\n 'lch',\n 'oklab',\n 'oklch',\n 'color',\n 'color-mix',\n 'matrix',\n 'translate',\n 'scale',\n 'rotate',\n 'skewx',\n 'skewy',\n])\n\n/**\n * The icon in `svg`, one whole SVG document, as `IconData`; `name` says which\n * icon a refusal is about. Throws on anything outside the allowlist.\n */\nexport const parse = (svg: string, name: string): IconData => {\n const refuse = (reason: string): never => {\n throw new Error(`The icon \"${name}\" cannot be drawn inline: ${reason}.`)\n }\n\n const decode = (value: string): string =>\n value.replace(/&([^;\\s]*);/g, (whole, entity: string) => {\n if (!entity.startsWith('#')) {\n return ENTITIES.get(entity) ?? refuse(`it holds the unknown entity ${whole}`)\n }\n const [, hex, decimal] = /^#(?:x([0-9a-fA-F]+)|([0-9]+))$/.exec(entity) ?? []\n const point =\n hex !== undefined ? Number.parseInt(hex, 16) : Number.parseInt(decimal ?? '0', 10)\n return point > 0 && point <= 0x10ffff\n ? String.fromCodePoint(point)\n : refuse(`it holds ${whole}, which is no character`)\n })\n\n const ATTRIBUTE = /\\s+([^\\s=/>]+)\\s*=\\s*(?:\"([^\"]*)\"|'([^']*)')/y\n\n // Every id the icon defines, and every fragment it names: one naming no id of its own\n // would reach the page's, so the two are compared once the whole icon is read.\n const ids = new Set<string>()\n const references: Array<{\n readonly tag: string\n readonly attribute: string\n readonly id: string\n }> = []\n\n const attributesOf = (tag: string, source: string, allowed: ReadonlySet<string>) => {\n const attributes: Record<string, string> = Object.create(null)\n ATTRIBUTE.lastIndex = 0\n while (ATTRIBUTE.lastIndex < source.trimEnd().length) {\n const from = ATTRIBUTE.lastIndex\n const match = ATTRIBUTE.exec(source)\n if (match === null)\n return refuse(`its <${tag}> is malformed at \"${source.slice(from).trim()}\"`)\n const written = match[1]!\n const value = decode(match[2] ?? match[3]!)\n const attribute = written === 'xlink:href' ? 'href' : written\n if (Object.hasOwn(attributes, attribute)) refuse(`its <${tag}> sets ${attribute} twice`)\n if (!allowed.has(attribute))\n refuse(`its <${tag}> has the attribute ${attribute}, which is not drawn inline`)\n if (attribute === 'href') {\n if (!value.startsWith('#')) refuse(`its <${tag}> links outside the icon (${value})`)\n references.push({ tag, attribute, id: value.slice(1) })\n }\n // A presentation attribute is read as CSS, where `URL(` is `url(` and an escape can spell either.\n if (value.includes('\\\\')) refuse(`its <${tag}>'s ${attribute} holds a CSS escape`)\n for (const [, called] of value.matchAll(/([a-z][a-z0-9-]*)\\s*\\(/gi)) {\n if (!FUNCTIONS.has(called!.toLowerCase()))\n refuse(`its <${tag}>'s ${attribute} calls ${called}(), which is not drawn inline`)\n }\n for (const [, target] of value.matchAll(/url\\(\\s*['\"]?([^)'\"]*)/gi)) {\n if (!target!.trim().startsWith('#'))\n refuse(`its <${tag}>'s ${attribute} refers outside the icon (${value})`)\n references.push({ tag, attribute, id: target!.trim().slice(1) })\n }\n if (attribute === 'id') ids.add(value)\n attributes[attribute] = value\n }\n return attributes\n }\n\n interface Open {\n readonly tag: SvgTag\n readonly attributes: Readonly<Record<string, string>>\n readonly children: Array<SvgNode>\n }\n let root:\n | { readonly attributes: Readonly<Record<string, string>>; readonly children: Array<SvgNode> }\n | undefined\n /** The elements open inside the root now, innermost last. */\n const open: Array<Open> = []\n let closed = false\n /** How deep inside a dropped element the parse is; its content is skipped whole. */\n let dropping = 0\n let at = 0\n\n while (at < svg.length) {\n const start = svg.indexOf('<', at)\n const text = svg.slice(at, start === -1 ? svg.length : start).trim()\n if (text !== '' && dropping === 0) refuse(`it holds the text \"${text}\"`)\n if (start === -1) break\n\n const [opener, closer] = svg.startsWith('<!--', start) ? ['<!--', '-->'] : ['<', '>']\n const end = svg.indexOf(closer, start + opener.length)\n if (end === -1) refuse(`a ${opener === '<' ? 'tag' : 'comment'} never closes`)\n at = end + closer.length\n if (opener === '<!--') continue\n const inside = svg.slice(start + 1, end)\n\n if (inside.startsWith('?') || inside.startsWith('!DOCTYPE')) {\n if (root !== undefined) refuse('it holds a declaration inside its drawing')\n continue\n }\n if (inside.startsWith('!')) refuse('it holds CDATA or a declaration')\n\n if (inside.startsWith('/')) {\n const tag = inside.slice(1).trim()\n if (dropping > 0) {\n if (DROPPED_ELEMENTS.has(tag)) dropping -= 1\n continue\n }\n if (open.length === 0 && tag === 'svg' && root !== undefined && !closed) {\n closed = true\n continue\n }\n const element = open.pop()\n if (element?.tag !== tag) {\n refuse(`</${tag}> closes ${element === undefined ? 'nothing' : `<${element.tag}>`}`)\n }\n ;(open.at(-1) ?? root!).children.push(element!)\n continue\n }\n\n const selfClosing = inside.endsWith('/')\n const body = selfClosing ? inside.slice(0, -1) : inside\n const tag = /^[^\\s/>]*/.exec(body)![0]\n if (dropping > 0) {\n if (DROPPED_ELEMENTS.has(tag) && !selfClosing) dropping += 1\n continue\n }\n if (closed) refuse('it holds markup after its svg')\n if (root === undefined) {\n if (tag !== 'svg') refuse(`its root is <${tag}>, not <svg>`)\n root = { attributes: attributesOf(tag, body.slice(tag.length), ROOT_ALLOWED), children: [] }\n if (selfClosing) closed = true\n continue\n }\n if (DROPPED_ELEMENTS.has(tag)) {\n if (!selfClosing) dropping += 1\n continue\n }\n if (!isTag(tag)) return refuse(`it holds <${tag}>, which is not drawn inline`)\n const element: Open = {\n tag,\n attributes: attributesOf(tag, body.slice(tag.length), ATTRIBUTES),\n children: [],\n }\n if (selfClosing) (open.at(-1) ?? root).children.push(element)\n else open.push(element)\n }\n\n if (root === undefined) return refuse('it holds no svg')\n if (!closed) refuse(`<${open.at(-1)?.tag ?? 'svg'}> never closes`)\n for (const { tag, attribute, id } of references) {\n if (!ids.has(id))\n refuse(`its <${tag}>'s ${attribute} names #${id}, which the icon does not define`)\n }\n\n const { viewBox, width, height } = root.attributes\n const presentation: Record<string, string> = {}\n for (const [attribute, value] of Object.entries(root.attributes)) {\n if (!DROPPED_ROOT.has(attribute)) presentation[attribute] = value\n }\n return {\n viewBox:\n viewBox ??\n (width !== undefined &&\n height !== undefined &&\n USER_UNITS.test(width) &&\n USER_UNITS.test(height)\n ? `0 0 ${width} ${height}`\n : refuse('it has no viewBox, and no width and height in user units to make one')),\n attributes: presentation,\n nodes: root.children,\n }\n}\n\nconst Box = {\n width: Schema.optional(Schema.Number),\n height: Schema.optional(Schema.Number),\n left: Schema.optional(Schema.Number),\n top: Schema.optional(Schema.Number),\n}\ntype IconifyBox = Schema.Struct.Type<typeof Box>\n\n// An icon or an alias may turn its drawing; read so that it is refused, not drawn unturned.\nconst Turn = {\n rotate: Schema.optional(Schema.Number),\n hFlip: Schema.optional(Schema.Boolean),\n vFlip: Schema.optional(Schema.Boolean),\n}\nconst turns = (entry: Schema.Struct.Type<typeof Turn>): boolean =>\n (entry.rotate !== undefined && entry.rotate !== 0) || entry.hFlip === true || entry.vFlip === true\n\n/**\n * An Iconify set, as its JSON file holds it (`@iconify-json/<prefix>/icons.json`).\n * What the drawing does not need (`info`, `categories`, an icon's `hidden`) is\n * read past.\n */\nexport const IconifySet = Schema.Struct({\n prefix: Schema.String,\n icons: Schema.Record(Schema.String, Schema.Struct({ body: Schema.String, ...Turn, ...Box })),\n aliases: Schema.optional(\n Schema.Record(Schema.String, Schema.Struct({ parent: Schema.String, ...Turn, ...Box })),\n ),\n ...Box,\n})\nexport type IconifySet = typeof IconifySet.Type\n\n/** Every name the set draws: its icons, then its aliases. */\nexport const namesOf = (set: IconifySet): ReadonlyArray<string> => [\n ...Object.keys(set.icons),\n ...Object.keys(set.aliases ?? {}),\n]\n\n/**\n * The icon `name` of an Iconify set, through its aliases, each of which may\n * give its own box. An alias that rotates or flips its parent is refused\n * rather than drawn as a second, transformed drawing.\n */\nexport const fromIconify = (set: IconifySet, name: string): IconData => {\n const label = `${set.prefix}:${name}`\n const refuse = (reason: string): never => {\n throw new Error(`The icon \"${label}\" cannot be drawn inline: ${reason}.`)\n }\n const boxes: Array<IconifyBox> = []\n let current = name\n while (!Object.hasOwn(set.icons, current)) {\n const alias =\n set.aliases !== undefined && Object.hasOwn(set.aliases, current)\n ? set.aliases[current]!\n : undefined\n if (alias === undefined) return refuse(`the set has no icon ${current}`)\n if (turns(alias)) refuse('it is an alias that rotates or flips its parent')\n if (boxes.length > 16) refuse('its aliases go round in a circle')\n boxes.push(alias)\n current = alias.parent\n }\n const icon = set.icons[current]!\n if (turns(icon)) refuse(`its drawing ${current} rotates or flips itself`)\n const nearest = [...boxes, icon, set]\n const read = (key: keyof IconifyBox, otherwise: number) =>\n nearest.find(box => box[key] !== undefined)?.[key] ?? otherwise\n return parse(\n `<svg viewBox=\"${read('left', 0)} ${read('top', 0)} ${read('width', 16)} ${read('height', 16)}\">${icon.body}</svg>`,\n label,\n )\n}\n"],"mappings":";;;;;;;;;;;AAWA,MAAM,WAAgC,IAAI,IAAI,IAAI;AAClD,MAAM,SAAS,QAA+B,SAAS,IAAI,GAAG;;AAG9D,MAAM,mCAAmB,IAAI,IAAI;CAAC;CAAS;CAAQ;AAAU,CAAC;AAE9D,MAAM,eAAe;CACnB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,6BAAa,IAAI,IAAI;CACzB,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,MAAM,kBAAkB,IAAI,IAAI,YAAY;AAC5C,MAAM,+BAAe,IAAI,IAAI;CAAC;CAAS;CAAe;CAAW;CAAS;CAAU;AAAS,CAAC;AAC9F,MAAM,+BAAe,IAAI,IAAI,CAAC,GAAG,iBAAiB,GAAG,YAAY,CAAC;AAElE,MAAM,2BAAwC,IAAI,IAAI;CACpD,CAAC,OAAO,GAAG;CACX,CAAC,MAAM,GAAG;CACV,CAAC,MAAM,GAAG;CACV,CAAC,QAAQ,IAAG;CACZ,CAAC,QAAQ,GAAG;AACd,CAAC;AAED,MAAM,aAAa;;;;;;;AAQnB,MAAM,4BAAiC,IAAI,IAAI;CAC7C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,MAAa,SAAS,KAAa,SAA2B;CAC5D,MAAM,UAAU,WAA0B;EACxC,MAAM,IAAI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,GAAG,OAAO,eAAe,QAAQ,yBAAyB;CACxE,MAAM,UAAU;EAAC,GAAG;EAAO;EAAM;CAAG;CACpC,MAAM,QAAQ,KAAuB,cACnC,QAAQ,MAAK,QAAO,IAAI,SAAS,KAAA,CAAS,CAAC,GAAG,QAAQ;CACxD,OAAO,MACL,iBAAiB,KAAK,QAAQ,CAAC,EAAE,GAAG,KAAK,OAAO,CAAC,EAAE,GAAG,KAAK,SAAS,EAAE,EAAE,GAAG,KAAK,UAAU,EAAE,EAAE,IAAI,KAAK,KAAK,SAC5G,KACF;AACF"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import * as Variant from "./variant.js";
|
|
2
|
+
import { Focus, HashedAsset, ImageAsset, Placeholder, isHashed } from "./asset.js";
|
|
3
|
+
import { Inspected, Inspector, Thumbnail, describe } from "./describe.js";
|
|
4
|
+
import { Encoding, Format, mimeType } from "./format.js";
|
|
5
|
+
import * as Icon from "./icon.js";
|
|
6
|
+
import { IconData, Stroke, SvgBuilder, SvgNode, SvgTag } from "./icon.js";
|
|
7
|
+
import * as Layout from "./layout.js";
|
|
8
|
+
import * as Picture from "./picture.js";
|
|
9
|
+
import * as Provider from "./provider.js";
|
|
10
|
+
import * as Widths from "./widths.js";
|
|
11
|
+
export { type Encoding, Focus, Format, HashedAsset, Icon, type IconData, ImageAsset, type Inspected, Inspector, Layout, Picture, Placeholder, Provider, type Stroke, type SvgBuilder, type SvgNode, type SvgTag, type Thumbnail, Variant, Widths, describe, isHashed, mimeType };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import * as Variant from "./variant.js";
|
|
2
|
+
import { Focus, HashedAsset, ImageAsset, Placeholder, isHashed } from "./asset.js";
|
|
3
|
+
import { Inspector, describe } from "./describe.js";
|
|
4
|
+
import { Format, mimeType } from "./format.js";
|
|
5
|
+
import * as Icon from "./icon.js";
|
|
6
|
+
import * as Layout from "./layout.js";
|
|
7
|
+
import * as Picture from "./picture.js";
|
|
8
|
+
import * as Provider from "./provider.js";
|
|
9
|
+
import * as Widths from "./widths.js";
|
|
10
|
+
export { Focus, Format, HashedAsset, Icon, ImageAsset, Inspector, Layout, Picture, Placeholder, Provider, Variant, Widths, describe, isHashed, mimeType };
|
package/dist/layout.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
import { ImageAsset } from "./asset.js";
|
|
3
|
+
import { Widths } from "./widths.js";
|
|
4
|
+
/** How wide an image is drawn, from which its candidates and `sizes` follow. */
|
|
5
|
+
declare const LayoutSchema: Schema.TaggedUnion<{
|
|
6
|
+
readonly Constrained: Schema.TaggedStruct<"Constrained", {
|
|
7
|
+
readonly width: Schema.Finite;
|
|
8
|
+
}>;
|
|
9
|
+
readonly Fixed: Schema.TaggedStruct<"Fixed", {
|
|
10
|
+
readonly width: Schema.Finite;
|
|
11
|
+
}>;
|
|
12
|
+
readonly FullWidth: Schema.TaggedStruct<"FullWidth", {}>;
|
|
13
|
+
}>;
|
|
14
|
+
export type Layout = typeof LayoutSchema.Type;
|
|
15
|
+
export declare const Fixed: (input: {
|
|
16
|
+
readonly _tag?: "Fixed";
|
|
17
|
+
readonly width: number;
|
|
18
|
+
}, options?: Schema.MakeOptions) => {
|
|
19
|
+
readonly _tag: "Fixed";
|
|
20
|
+
readonly width: number;
|
|
21
|
+
};
|
|
22
|
+
export declare const Constrained: (input: {
|
|
23
|
+
readonly _tag?: "Constrained";
|
|
24
|
+
readonly width: number;
|
|
25
|
+
}, options?: Schema.MakeOptions) => {
|
|
26
|
+
readonly _tag: "Constrained";
|
|
27
|
+
readonly width: number;
|
|
28
|
+
};
|
|
29
|
+
export declare const FullWidth: () => Layout;
|
|
30
|
+
/**
|
|
31
|
+
* One `srcset` entry: the ladder width asked of the provider, and the width
|
|
32
|
+
* the answer has. They differ only above the original's own width, where a
|
|
33
|
+
* provider that does not enlarge answers with the original's.
|
|
34
|
+
*/
|
|
35
|
+
export interface Candidate {
|
|
36
|
+
readonly request: number;
|
|
37
|
+
readonly described: number;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The widths worth offering for `layout`: for a fixed image its 1x and 2x,
|
|
41
|
+
* for a constrained one every width up to its 2x, for a full-width one the
|
|
42
|
+
* whole ladder. Widths above the original fetch the original's pixels, so
|
|
43
|
+
* only the first of them is kept.
|
|
44
|
+
*/
|
|
45
|
+
export declare const candidates: (layout: Layout, widths: Widths, intrinsic: number) => ReadonlyArray<Candidate>;
|
|
46
|
+
/** The `sizes` a layout implies: how wide the image is drawn at each viewport. */
|
|
47
|
+
export declare const sizes: (layout: Layout) => string;
|
|
48
|
+
/** The original's aspect ratio, as CSS writes one. */
|
|
49
|
+
export declare const ratio: (asset: Pick<ImageAsset, 'width' | 'height'>) => string;
|
|
50
|
+
/**
|
|
51
|
+
* The `width` and `height` attributes: the drawn size where the layout fixes
|
|
52
|
+
* one, the original's where it does not. Either way their ratio is the
|
|
53
|
+
* original's, which is what reserves the box before a byte arrives.
|
|
54
|
+
*/
|
|
55
|
+
export declare const box: (layout: Layout, asset: Pick<ImageAsset, 'width' | 'height'>) => {
|
|
56
|
+
readonly width: number;
|
|
57
|
+
readonly height: number;
|
|
58
|
+
};
|
|
59
|
+
export { LayoutSchema as Schema };
|
|
60
|
+
//# sourceMappingURL=layout.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"layout.d.ts","names":[],"sources":["../src/layout.ts"],"mappings":";;;;cAOM,cAAY,OAAA;;;;;;;;;YASN,gBAAgB,aAAa;qBAE5B,QAAK;;;;;;;qBACL,cAAW;;;;;;;qBACX,iBAAgB;;;;;;iBAOZ;WACN;WACA;;;;;;;;qBASE,aAAU,QACb,QAAM,QACN,QAAM,sBAEb,cAAc;;qBAkBJ,QAAK,QAAY;;qBAQjB,QAAK,OAAW,KAAK;;;;;;qBAQrB,MAAG,QACN,QAAM,OACP,KAAK;WACA;WAAwB"}
|
package/dist/layout.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Schema } from "effect";
|
|
2
|
+
import { atLeast } from "./widths.js";
|
|
3
|
+
// src/layout.ts
|
|
4
|
+
const CssPixels = Schema.Finite.check(Schema.isGreaterThan(0));
|
|
5
|
+
/** How wide an image is drawn, from which its candidates and `sizes` follow. */
|
|
6
|
+
const LayoutSchema = Schema.TaggedUnion({
|
|
7
|
+
/** Always this many CSS pixels wide. */
|
|
8
|
+
Fixed: { width: CssPixels },
|
|
9
|
+
/** At most this wide, and the viewport's width when that is narrower. */
|
|
10
|
+
Constrained: { width: CssPixels },
|
|
11
|
+
/** The viewport's width. */
|
|
12
|
+
FullWidth: {}
|
|
13
|
+
});
|
|
14
|
+
const Fixed = LayoutSchema.cases.Fixed.make;
|
|
15
|
+
const Constrained = LayoutSchema.cases.Constrained.make;
|
|
16
|
+
const FullWidth = () => LayoutSchema.cases.FullWidth.make({});
|
|
17
|
+
/**
|
|
18
|
+
* The widths worth offering for `layout`: for a fixed image its 1x and 2x,
|
|
19
|
+
* for a constrained one every width up to its 2x, for a full-width one the
|
|
20
|
+
* whole ladder. Widths above the original fetch the original's pixels, so
|
|
21
|
+
* only the first of them is kept.
|
|
22
|
+
*/
|
|
23
|
+
const candidates = (layout, widths, intrinsic) => {
|
|
24
|
+
const wanted = LayoutSchema.match(layout, {
|
|
25
|
+
Fixed: ({ width }) => [atLeast(widths, width), atLeast(widths, 2 * width)],
|
|
26
|
+
Constrained: ({ width }) => {
|
|
27
|
+
const top = atLeast(widths, 2 * width);
|
|
28
|
+
return widths.values.filter((value) => value <= top);
|
|
29
|
+
},
|
|
30
|
+
FullWidth: () => widths.values
|
|
31
|
+
});
|
|
32
|
+
const result = [];
|
|
33
|
+
for (const request of wanted) {
|
|
34
|
+
const described = Math.min(request, intrinsic);
|
|
35
|
+
if (result.at(-1)?.described !== described) result.push({
|
|
36
|
+
request,
|
|
37
|
+
described
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return result;
|
|
41
|
+
};
|
|
42
|
+
/** The `sizes` a layout implies: how wide the image is drawn at each viewport. */
|
|
43
|
+
const sizes = (layout) => LayoutSchema.match(layout, {
|
|
44
|
+
Fixed: ({ width }) => `${width}px`,
|
|
45
|
+
Constrained: ({ width }) => `(min-width: ${width}px) ${width}px, 100vw`,
|
|
46
|
+
FullWidth: () => "100vw"
|
|
47
|
+
});
|
|
48
|
+
/** The original's aspect ratio, as CSS writes one. */
|
|
49
|
+
const ratio = (asset) => `${asset.width} / ${asset.height}`;
|
|
50
|
+
/**
|
|
51
|
+
* The `width` and `height` attributes: the drawn size where the layout fixes
|
|
52
|
+
* one, the original's where it does not. Either way their ratio is the
|
|
53
|
+
* original's, which is what reserves the box before a byte arrives.
|
|
54
|
+
*/
|
|
55
|
+
const box = (layout, asset) => {
|
|
56
|
+
const pixel = (value) => Math.max(1, Math.round(value));
|
|
57
|
+
const scaled = (width) => ({
|
|
58
|
+
width: pixel(width),
|
|
59
|
+
height: pixel(width * asset.height / asset.width)
|
|
60
|
+
});
|
|
61
|
+
return LayoutSchema.match(layout, {
|
|
62
|
+
Fixed: ({ width }) => scaled(width),
|
|
63
|
+
Constrained: ({ width }) => scaled(width),
|
|
64
|
+
FullWidth: () => ({
|
|
65
|
+
width: asset.width,
|
|
66
|
+
height: asset.height
|
|
67
|
+
})
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
export { Constrained, Fixed, FullWidth, LayoutSchema as Schema, box, candidates, ratio, sizes };
|
|
71
|
+
|
|
72
|
+
//# sourceMappingURL=layout.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"layout.js","names":[],"sources":["../src/layout.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"],"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,MAAM,MAAM,QAAQ,QAAQ,IAAI,KAAK;GACrC,OAAO,OAAO,OAAO,QAAO,UAAS,SAAS,GAAG;EACnD;EACA,iBAAiB,OAAO;CAC1B,CAAC;CACD,MAAM,SAA2B,CAAC;CAClC,KAAK,MAAM,WAAW,QAAQ;EAC5B,MAAM,YAAY,KAAK,IAAI,SAAS,SAAS;EAC7C,IAAI,OAAO,GAAG,EAAE,CAAC,EAAE,cAAc,WAAW,OAAO,KAAK;GAAE;GAAS;EAAU,CAAC;CAChF;CACA,OAAO;AACT;;AAGA,MAAa,SAAS,WACpB,aAAa,MAAM,QAAQ;CACzB,QAAQ,EAAE,YAAY,GAAG,MAAM;CAC/B,cAAc,EAAE,YAAY,eAAe,MAAM,MAAM,MAAM;CAC7D,iBAAiB;AACnB,CAAC;;AAGH,MAAa,SAAS,UACpB,GAAG,MAAM,MAAM,KAAK,MAAM;;;;;;AAO5B,MAAa,OACX,QACA,UACwD;CACxD,MAAM,SAAS,UAAkB,KAAK,IAAI,GAAG,KAAK,MAAM,KAAK,CAAC;CAC9D,MAAM,UAAU,WAAmB;EACjC,OAAO,MAAM,KAAK;EAClB,QAAQ,MAAO,QAAQ,MAAM,SAAU,MAAM,KAAK;CACpD;CACA,OAAO,aAAa,MAAM,QAAQ;EAChC,QAAQ,EAAE,YAAY,OAAO,KAAK;EAClC,cAAc,EAAE,YAAY,OAAO,KAAK;EACxC,kBAAkB;GAAE,OAAO,MAAM;GAAO,QAAQ,MAAM;EAAO;CAC/D,CAAC;AACH"}
|
package/dist/limits.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"limits.d.ts","names":[],"sources":["../src/limits.ts"],"mappings":"A,qBAAa,qBAAkB,cAAgB;qBAOlC,kBAAe,cAAgB"}
|
|
@@ -7,6 +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
|
-
export {
|
|
10
|
+
export { nonNegativeInteger, positiveInteger };
|
|
11
11
|
|
|
12
|
-
//# sourceMappingURL=limits
|
|
12
|
+
//# sourceMappingURL=limits.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"limits.js","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"}
|