@pttn.dev/helpers 0.0.0-stage → 0.0.43398875466

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pattern
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @pttn.dev/helpers
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Helpers for themes built on [Pattern](https://pttn.dev), a hosted CMS. A theme
4
+ imports this package as `@pattern/helpers`. It holds pure URL builders
5
+ (`imageUrl`, `srcset` and `linkUrl`) that work on server-rendered pages and in
6
+ island bundles alike.
7
+
8
+ This package lets a theme exported from Pattern keep compiling outside Pattern.
9
+ On Pattern itself, the platform supplies it and you do not install it.
10
+
11
+ ## Install
12
+
13
+ Themes import `@pattern/helpers`, and the package is published as
14
+ `@pttn.dev/helpers`. Install it under its import name with an npm alias:
15
+
16
+ ```sh
17
+ npm install @pattern/helpers@npm:@pttn.dev/helpers@<version>
18
+ ```
19
+
20
+ That records the alias in your theme's `package.json`:
21
+
22
+ ```json
23
+ {
24
+ "dependencies": {
25
+ "@pattern/helpers": "npm:@pttn.dev/helpers@<version>"
26
+ }
27
+ }
28
+ ```
29
+
30
+ Use the version that matches the platform release your theme was exported
31
+ from. Each Pattern platform release publishes one version, in lockstep with
32
+ `@pttn.dev/components` and the platform's Svelte version. There is no separate
33
+ version line to choose from.
34
+
35
+ ## Licence
36
+
37
+ MIT. See [`LICENSE`](./LICENSE).
38
+
39
+ ## Contributions
40
+
41
+ This package is published one-way from Pattern's platform releases. Pull
42
+ requests and issues are not accepted. For questions or problems, email
43
+ [hello@pttn.dev](mailto:hello@pttn.dev). To report a vulnerability, see
44
+ [`SECURITY.md`](./SECURITY.md).
package/SECURITY.md ADDED
@@ -0,0 +1,14 @@
1
+ # Security policy
2
+
3
+ ## Reporting a vulnerability
4
+
5
+ Email [hello@pttn.dev](mailto:hello@pttn.dev) to report a vulnerability in
6
+ `@pttn.dev/helpers`. Please do not disclose it publicly until it is fixed.
7
+
8
+ Include the package version, what the vulnerability lets someone do, and the
9
+ steps or code that reproduce it.
10
+
11
+ ## Supported versions
12
+
13
+ Fixes ship in a new Pattern platform release, which publishes a new version of
14
+ this package. Earlier versions are not patched.
package/index.js ADDED
@@ -0,0 +1,201 @@
1
+ // The `@pattern/helpers` allowlisted import: the URL builders that replace the
2
+ // Liquid `image_url` / `link_url` filters (ADR-013's contract, new syntax).
3
+ // Pure functions over already-resolved data — no I/O, no capabilities.
4
+ //
5
+ // `imageUrl` and `srcset` emit the canonical UNSIGNED transform form
6
+ // `<url-origin>/img/<options>/<path>` (docs/spec/image-transforms.md; ADR-041 §3
7
+ // as amended by ADR-070). The sandbox holds no signing key and the guest has no
8
+ // host imports, so the host signs these URLs in a narrow post-render pass — with
9
+ // the same option bounds applied again there, because guest output is untrusted.
10
+ // The option set,
11
+ // clamping, defaults and canonical ordering below mirror the retired Liquid
12
+ // `image_url` filter exactly (docs/spec/image-transforms.md; ADR-069 §3–§4).
13
+
14
+ /// Upper bound on `width`/`height`, in pixels — mirrors `transform::MAX_DIMENSION`.
15
+ const MAX_DIMENSION = 5000;
16
+
17
+ const TRANSFORM_PREFIX = '/img/';
18
+ /// Legacy Cloudflare URL interface — never emitted; WAF-blocked (ADR-070).
19
+ const LEGACY_PREFIX = '/cdn-cgi/image/';
20
+
21
+ /// Closed `fit` enum, both spellings the Liquid filter accepted (ADR-041 §3).
22
+ const FITS = new Map([
23
+ ['scale-down', 'scale-down'], ['scale_down', 'scale-down'],
24
+ ['contain', 'contain'],
25
+ ['cover', 'cover'],
26
+ ['crop', 'crop'],
27
+ ['aspect-crop', 'aspect-crop'], ['aspect_crop', 'aspect-crop'],
28
+ ['pad', 'pad'],
29
+ ]);
30
+ /// Closed `format` enum; `jpg` normalizes to Cloudflare's `jpeg` spelling.
31
+ const FORMATS = new Map([
32
+ ['auto', 'auto'],
33
+ ['webp', 'webp'],
34
+ ['avif', 'avif'],
35
+ ['jpeg', 'jpeg'], ['jpg', 'jpeg'],
36
+ ['png', 'png'],
37
+ ]);
38
+ /// The fits that crop, and therefore honor `gravity` (ADR-069 §4).
39
+ const CROPPING_FITS = new Set(['cover', 'crop', 'aspect-crop']);
40
+
41
+ function keyword(value) {
42
+ return String(value).trim().toLowerCase();
43
+ }
44
+
45
+ /// A positive integer in canonical decimal spelling; `0`, fractional, negative,
46
+ /// non-numeric or empty values drop to `null`, never raise (CON-006).
47
+ function positiveInt(value) {
48
+ const n =
49
+ typeof value === 'number'
50
+ ? value
51
+ : typeof value === 'string' && /^\d+$/.test(value.trim())
52
+ ? Number(value)
53
+ : NaN;
54
+ if (!Number.isInteger(n) || n <= 0) return null;
55
+ return n;
56
+ }
57
+
58
+ function clampedDimension(value) {
59
+ const n = positiveInt(value);
60
+ return n === null ? null : Math.min(n, MAX_DIMENSION);
61
+ }
62
+
63
+ function parseFit(value) {
64
+ return FITS.get(keyword(value)) ?? null;
65
+ }
66
+
67
+ function parseFormat(value) {
68
+ return FORMATS.get(keyword(value)) ?? null;
69
+ }
70
+
71
+ /// Normalized `XxY` focal point, both in `[0, 1]`, top-left origin (ADR-069 §1).
72
+ /// `auto`/`face` and out-of-range values drop to `null`, never raise (§3).
73
+ function parseGravity(value) {
74
+ if (typeof value !== 'string') return null;
75
+ const trimmed = value.trim();
76
+ const split = trimmed.indexOf('x');
77
+ if (split < 0) return null;
78
+ const xs = trimmed.slice(0, split).trim();
79
+ const ys = trimmed.slice(split + 1).trim();
80
+ if (xs === '' || ys === '') return null;
81
+ const x = Number(xs);
82
+ const y = Number(ys);
83
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
84
+ if (x < 0 || x > 1 || y < 0 || y > 1) return null;
85
+ return { x, y };
86
+ }
87
+
88
+ /// Whether the asset's MIME has a transform path at all (ADR-041 §3). Video, PDF,
89
+ /// documents and SVG are delivered as-is. An absent `mime` is treated as an image —
90
+ /// the helper's name is the caller's assertion, like the filter before it.
91
+ function isTransformableMime(asset) {
92
+ if (asset.mime === undefined) return true;
93
+ const mime = String(asset.mime ?? '').trim().toLowerCase();
94
+ return mime.startsWith('image/') && mime !== 'image/svg+xml';
95
+ }
96
+
97
+ /// The canonical comma-separated options list, or `null` when nothing survives —
98
+ /// the plain-delivery-URL case. Canonical order: fit, width, height, gravity,
99
+ /// quality, format (one edge-cache key per transform).
100
+ function buildOptions(opts) {
101
+ const width = clampedDimension(opts?.width);
102
+ const height = clampedDimension(opts?.height);
103
+ const q = positiveInt(opts?.quality);
104
+ const quality = q === null ? null : Math.min(q, 100);
105
+ const format = parseFormat(opts?.format);
106
+ const fit = parseFit(opts?.fit);
107
+ const gravity = parseGravity(opts?.gravity);
108
+
109
+ // A fit with no dimension has no box to resize toward — dropped, so a
110
+ // pass-through never bills a transform. Both dimensions without an explicit
111
+ // fit mean "fill this box" → cover; a single dimension keeps Cloudflare's
112
+ // aspect-preserving default.
113
+ let effectiveFit = null;
114
+ if (width !== null || height !== null) {
115
+ effectiveFit = fit ?? (width !== null && height !== null ? 'cover' : null);
116
+ }
117
+
118
+ const parts = [];
119
+ if (effectiveFit !== null) parts.push(`fit=${effectiveFit}`);
120
+ if (width !== null) parts.push(`width=${width}`);
121
+ if (height !== null) parts.push(`height=${height}`);
122
+ // Gravity rides a cropping fit only; rounded to two decimals so a jittering
123
+ // low-order bit cannot fragment the edge cache (ADR-069 §4).
124
+ if (gravity !== null && effectiveFit !== null && CROPPING_FITS.has(effectiveFit)) {
125
+ parts.push(`gravity=${gravity.x.toFixed(2)}x${gravity.y.toFixed(2)}`);
126
+ }
127
+ if (quality !== null) parts.push(`quality=${quality}`);
128
+ if (format !== null) parts.push(`format=${format}`);
129
+ return parts.length === 0 ? null : parts.join(',');
130
+ }
131
+
132
+ /// Split a delivery URL into `origin` and leading-`/` path the way the host's
133
+ /// `ImageTransform::apply` does, so options land at the zone root. `null` for an
134
+ /// origin-only URL (nothing to transform).
135
+ function splitDeliveryUrl(url) {
136
+ const scheme = url.indexOf('://');
137
+ if (scheme < 0) return { origin: '', path: url };
138
+ const pathStart = url.indexOf('/', scheme + 3);
139
+ if (pathStart < 0) return null;
140
+ return { origin: url.slice(0, pathStart), path: url.slice(pathStart) };
141
+ }
142
+
143
+ /// Rewrite a delivery URL into its unsigned transform form. No surviving options
144
+ /// → the plain delivery URL; an already-transformed path is never double-wrapped.
145
+ function unsignedTransformUrl(url, opts) {
146
+ const options = buildOptions(opts);
147
+ if (options === null) return url;
148
+ const parts = splitDeliveryUrl(url);
149
+ if (parts === null) return url;
150
+ if (parts.path.startsWith(TRANSFORM_PREFIX) || parts.path.startsWith(LEGACY_PREFIX)) {
151
+ return url;
152
+ }
153
+ return parts.origin + TRANSFORM_PREFIX + options + parts.path;
154
+ }
155
+
156
+ /// A usable resolved asset: an object carrying a non-empty `url` string. Anything else —
157
+ /// absent, unresolved (a bare id string), or emptied — yields no URL at all (CON-006:
158
+ /// never a render error).
159
+ function isUsableAsset(asset) {
160
+ return (
161
+ !!asset &&
162
+ typeof asset === 'object' &&
163
+ typeof asset.url === 'string' &&
164
+ asset.url !== ''
165
+ );
166
+ }
167
+
168
+ /// `imageUrl(asset, { width, height, fit, gravity, quality, format })` — the
169
+ /// unsigned transform URL for a resolved asset, or the plain delivery URL when
170
+ /// there is nothing to transform. An absent/unresolved asset yields `''`
171
+ /// (CON-006: never a render error).
172
+ export function imageUrl(asset, opts = {}) {
173
+ if (!isUsableAsset(asset)) return '';
174
+ if (!isTransformableMime(asset)) return asset.url;
175
+ return unsignedTransformUrl(asset.url, opts);
176
+ }
177
+
178
+ /// `srcset(asset, widths, opts)` — one unsigned transform URL per width, in the
179
+ /// `srcset` attribute grammar: `"<url> <w>w, …"`. Invalid widths drop; widths
180
+ /// that clamp to the same value dedupe on the clamped width, so the descriptor
181
+ /// stays honest about the URL it names. `''` when nothing usable remains.
182
+ export function srcset(asset, widths, opts = {}) {
183
+ if (!isUsableAsset(asset)) return '';
184
+ if (!isTransformableMime(asset)) return '';
185
+ if (!Array.isArray(widths)) return '';
186
+ const seen = new Set();
187
+ const entries = [];
188
+ for (const requested of widths) {
189
+ const width = clampedDimension(requested);
190
+ if (width === null || seen.has(width)) continue;
191
+ seen.add(width);
192
+ const url = imageUrl(asset, { ...opts, width });
193
+ if (url === '') continue;
194
+ entries.push(`${url} ${width}w`);
195
+ }
196
+ return entries.join(', ');
197
+ }
198
+
199
+ export function linkUrl(ref) {
200
+ return ref?.url ?? '';
201
+ }
package/package.json CHANGED
@@ -1,6 +1,17 @@
1
1
  {
2
2
  "name": "@pttn.dev/helpers",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.43398875466",
4
+ "description": "Pattern platform helpers. Themes import it as @pattern/helpers through an npm alias. The version is stamped from the platform release tag at publish.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "exports": {
9
+ ".": "./index.js"
10
+ },
11
+ "files": [
12
+ "index.js",
13
+ "LICENSE",
14
+ "README.md",
15
+ "SECURITY.md"
16
+ ]
17
+ }