@stagepass/cli 2.2.1 → 2.2.6

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stagepass/cli",
3
- "version": "2.2.1",
3
+ "version": "2.2.6",
4
4
  "description": "Local Development Orchestrator for Webflow",
5
5
  "type": "module",
6
6
  "main": "bin/index.js",
@@ -25,6 +25,7 @@ import {
25
25
  fetchPublished,
26
26
  installedHasPerModuleTypes,
27
27
  rangeHasPerModuleTypes,
28
+ resolveSnippetLoaderVersion,
28
29
  } from '../lib/registry.js';
29
30
  import { updateConfigTypes } from '../lib/project-sync.js';
30
31
 
@@ -33,14 +34,10 @@ const PER_MODULE_TYPES_HINT =
33
34
  'types use "@stagepass/modules" for now. Run `stagepass upgrade` once it is published to narrow them.';
34
35
 
35
36
  /**
36
- * Resolve a boolean flag that may appear as --foo / --no-foo.
37
- * Only argv is trusted: Commander defaults negated pairs to true, which would
38
- * break defaults like --install (off unless passed).
39
- *
40
37
  * @param {object} _options
41
38
  * @param {string} key
42
39
  * @param {string[]} argv
43
- * @param {boolean|undefined} defaultValue undefined = still unset
40
+ * @param {boolean|undefined} defaultValue
44
41
  */
45
42
  export function resolveBoolFlag(_options, key, argv, defaultValue) {
46
43
  const pos = `--${key}`;
@@ -51,7 +48,7 @@ export function resolveBoolFlag(_options, key, argv, defaultValue) {
51
48
  }
52
49
 
53
50
  /**
54
- * @param {object} options Commander options
51
+ * @param {object} options
55
52
  * @param {object} [deps]
56
53
  */
57
54
  async function resolveAuthor(options, deps) {
@@ -95,7 +92,6 @@ async function askYesNo(rl, question, defaultYes) {
95
92
  }
96
93
 
97
94
  /**
98
- * Merge flags + optional interactive prompts into a resolved config.
99
95
  * @param {string|undefined} nameArg
100
96
  * @param {object} options
101
97
  * @param {object} deps
@@ -115,7 +111,7 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
115
111
  let styles =
116
112
  options.styles === 'css' || options.styles === 'scss' ? options.styles : '';
117
113
 
118
- // Prefer argv for --foo / --no-foo so Commander default quirks do not flip defaults.
114
+ // Prefer argv for --foo / --no-foo so Commander defaults do not flip.
119
115
  let modules = resolveBoolFlag(options, 'modules', argv, undefined);
120
116
  let git = resolveBoolFlag(options, 'git', argv, undefined);
121
117
  let install = resolveBoolFlag(options, 'install', argv, undefined);
@@ -139,9 +135,9 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
139
135
  }
140
136
 
141
137
  /**
142
- * Detect modules on the live site (public GET, never executed).
143
- * @returns {Promise<string[] | null>} detected list, or null when unknown
144
- */
138
+ * Detect modules on the live site (public GET, never executed).
139
+ * @returns {Promise<string[] | null>} detected list, or null when unknown
140
+ */
145
141
  const detectFromSite = async () => {
146
142
  if (!origin) return null;
147
143
  log(`Checking live site https://${origin}/ for Stagepass script tags...`);
@@ -231,7 +227,7 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
231
227
  error: '--no-modules conflicts with declared site modules. Drop --no-modules or pass --site-modules none.',
232
228
  };
233
229
  }
234
- // The npm package (types) follows the declared list; keep the legacy default (included).
230
+ // npm package (types) follows the declared list; legacy default is included.
235
231
  if (siteModules.length > 0) modules = true;
236
232
 
237
233
  // Non-interactive / --yes defaults
@@ -289,16 +285,13 @@ export async function resolveNewOptions(nameArg, options = {}, deps = {}) {
289
285
  remote: remoteCheck.remote,
290
286
  install,
291
287
  dryRun: options.dryRun === true,
292
- loaderVersion:
293
- deps.packagesVersion || deps.cliVersion || STAGEPASS_PACKAGES_VERSION,
288
+ // Bundled loader until createNew resolves the published one (AC-14).
289
+ loaderVersion: deps.packagesVersion || STAGEPASS_PACKAGES_VERSION,
294
290
  },
295
291
  };
296
292
  }
297
293
 
298
294
  /**
299
- * After `npm install`, align tsconfig/jsconfig types with the installed
300
- * @stagepass/modules (per-module entries only when it ships them).
301
- *
302
295
  * @param {string} targetDir
303
296
  * @param {{ siteModules: string[], perModuleTypes?: boolean }} config
304
297
  * @param {typeof fs} fse
@@ -324,8 +317,6 @@ async function reconcileInstalledTypes(targetDir, config, fse, log) {
324
317
  }
325
318
 
326
319
  /**
327
- * Scaffold a new Stagepass project.
328
- *
329
320
  * @param {string|undefined} nameArg
330
321
  * @param {object} [options]
331
322
  * @param {object} [deps]
@@ -375,9 +366,7 @@ export async function createNew(nameArg, options = {}, deps = {}) {
375
366
  }
376
367
  };
377
368
 
378
- // Single-module types (`@stagepass/modules/cookies`) exist since modules
379
- // 2.2.0. Only use them when a published release in range ships them;
380
- // otherwise (or offline) fall back to the umbrella types so tsc passes.
369
+ // Per-module types since modules 2.2.0; else umbrella types so tsc passes.
381
370
  const singleModuleTypes =
382
371
  config.modules === true &&
383
372
  config.siteModules.length > 0 &&
@@ -389,6 +378,17 @@ export async function createNew(nameArg, options = {}, deps = {}) {
389
378
  if (!config.perModuleTypes) log(chalk.yellow(PER_MODULE_TYPES_HINT));
390
379
  }
391
380
 
381
+ // Snippets pin the resolved loader, never the CLI version (AC-14).
382
+ if (!config.dryRun) {
383
+ const loader = await (deps.fetchPublished || fetchPublished)('@stagepass/loader', { exec });
384
+ config.loaderVersion = await resolveSnippetLoaderVersion({
385
+ published: loader,
386
+ cwd: targetDir,
387
+ bundled: config.loaderVersion,
388
+ fse,
389
+ });
390
+ }
391
+
392
392
  let files;
393
393
  try {
394
394
  files = await planScaffoldFiles(config, { readTemplate });
@@ -507,5 +507,5 @@ export async function createNew(nameArg, options = {}, deps = {}) {
507
507
  return 0;
508
508
  }
509
509
 
510
- /** Commander-facing alias */
510
+ /** Commander-facing alias */
511
511
  export const newProject = createNew;
@@ -13,12 +13,13 @@ import { STAGEPASS_PACKAGES_VERSION } from '../lib/versions.js';
13
13
  import {
14
14
  PACKAGES_MAJOR_RANGE,
15
15
  fetchPublished,
16
+ resolveSnippetLoaderVersion,
16
17
  installedHasPerModuleTypes,
17
18
  maxSatisfying,
18
19
  rangeHasPerModuleTypes,
19
20
  satisfiesSimple,
20
21
  } from '../lib/registry.js';
21
- import { detectSite } from '../lib/site-detect.js';
22
+ import { detectSite, normalizeSiteUrl } from '../lib/site-detect.js';
22
23
  import {
23
24
  applyProjectSync,
24
25
  planProjectSync,
@@ -31,7 +32,6 @@ const STAGEPASS_SCOPE = '@stagepass/';
31
32
  const SAFE_SPEC_RE = /^[~^]?[0-9A-Za-z][0-9A-Za-z._+-]*$/;
32
33
 
33
34
  /**
34
- * True when the version looks like an npm dist-tag (bare word, e.g. latest).
35
35
  * @param {string} version
36
36
  */
37
37
  function isDistTag(version) {
@@ -43,15 +43,7 @@ function isDistTag(version) {
43
43
  }
44
44
 
45
45
  /**
46
- * Resolve the range to write for one @stagepass/* package.
47
- *
48
- * Never writes a version or range that no published release satisfies
49
- * (releases can be staged but not yet approved, which gives ETARGET):
50
- * - default: `^<latest>` when latest is in the current major, else
51
- * `^<highest published 2.x>`; `^2` when npm is unreachable
52
- * - `--version <semver|range>`: must match a published version
53
- * - `--version <dist-tag>`: the published version behind that tag
54
- *
46
+ * Never writes a version/range no published release satisfies (avoids ETARGET on staged releases).
55
47
  * @param {string} name
56
48
  * @param {string|undefined} requested
57
49
  * @param {{ distTags: Record<string, string>, versions: string[] } | null} published
@@ -96,8 +88,6 @@ export function resolvePackageTarget(name, requested, published) {
96
88
  }
97
89
 
98
90
  /**
99
- * Resolve target ranges for every @stagepass/* dependency in package.json.
100
- *
101
91
  * @param {string|undefined} requested `--version`
102
92
  * @param {string[]} names package names
103
93
  * @param {object} [deps]
@@ -120,7 +110,6 @@ export async function resolveUpgradeTargets(requested, names, deps = {}) {
120
110
  }
121
111
 
122
112
  /**
123
- * Collect @stagepass/* entries from dependencies and devDependencies.
124
113
  * @param {object} pkg
125
114
  * @returns {{ section: 'dependencies'|'devDependencies', name: string, from: string }[]}
126
115
  */
@@ -140,7 +129,6 @@ export function findStagepassDeps(pkg) {
140
129
  }
141
130
 
142
131
  /**
143
- * Rewrite @stagepass/* versions in a package.json object (mutates a copy).
144
132
  * @param {object} pkg
145
133
  * @param {string | Record<string, string>} target one spec for all, or per package name
146
134
  * @returns {{ next: object, changes: { name: string, from: string, to: string, section: string }[] }}
@@ -163,10 +151,6 @@ export function applyStagepassVersions(pkg, target) {
163
151
  }
164
152
 
165
153
  /**
166
- * Upgrade @stagepass/* deps in the current project's package.json and sync
167
- * the declared modules into stagepass.json, AGENTS.md, the Cursor rule and
168
- * tsconfig/jsconfig types.
169
- *
170
154
  * @param {object} [options]
171
155
  * @param {boolean} [options.dryRun]
172
156
  * @param {string} [options.version]
@@ -202,6 +186,14 @@ export async function upgrade(options = {}, deps = {}) {
202
186
  return 1;
203
187
  }
204
188
 
189
+ if (options.site) {
190
+ const c = normalizeSiteUrl(options.site);
191
+ if (!c.ok) {
192
+ log(chalk.red(c.error));
193
+ return 1;
194
+ }
195
+ }
196
+
205
197
  const names = findStagepassDeps(pkg).map((d) => d.name);
206
198
  let resolvedTargets;
207
199
  try {
@@ -319,6 +311,27 @@ export async function upgrade(options = {}, deps = {}) {
319
311
  );
320
312
  }
321
313
 
314
+ // Snippet: --version pin of loader on 2.x wins; resolve before writing so a failure changes nothing.
315
+ let loaderPub = '@stagepass/loader' in published ? published['@stagepass/loader'] : undefined;
316
+ const getLoaderPub = async () => {
317
+ if (loaderPub !== undefined) return loaderPub;
318
+ const lookup = deps.fetchPublished || ((name) => fetchPublished(name, { exec: deps.exec || defaultExec }));
319
+ loaderPub = await lookup('@stagepass/loader');
320
+ return loaderPub;
321
+ };
322
+ let snippetVersion = null;
323
+ if (options.version != null) {
324
+ let t = targets['@stagepass/loader'];
325
+ if (!t) {
326
+ try {
327
+ t = resolvePackageTarget('@stagepass/loader', options.version, await getLoaderPub());
328
+ } catch (e) {
329
+ log(chalk.red(e instanceof Error ? e.message : String(e)));
330
+ return 1;
331
+ }
332
+ }
333
+ if (t.resolved && satisfiesSimple(t.resolved, PACKAGES_MAJOR_RANGE)) snippetVersion = t.resolved;
334
+ }
322
335
  if (options.dryRun) {
323
336
  log(chalk.dim('\nDry run: no files were modified.'));
324
337
  } else {
@@ -332,8 +345,16 @@ export async function upgrade(options = {}, deps = {}) {
332
345
  if (plan.writes.length > 0) log(chalk.green(`Updated ${plan.writes.length} project file(s).`));
333
346
  }
334
347
 
348
+ if (!snippetVersion) {
349
+ snippetVersion = await resolveSnippetLoaderVersion({
350
+ published: await getLoaderPub(),
351
+ cwd,
352
+ bundled: STAGEPASS_PACKAGES_VERSION,
353
+ fse,
354
+ });
355
+ }
335
356
  const snippets = buildWebflowSnippets({
336
- version: targets['@stagepass/loader']?.resolved || STAGEPASS_PACKAGES_VERSION,
357
+ version: snippetVersion,
337
358
  moduleList: resolved.modules,
338
359
  });
339
360
  printWebflowSnippets(snippets, log);
@@ -1,7 +1,6 @@
1
1
  /**
2
- * Doctor checks for the current project folder: declared modules in
3
- * stagepass.json vs. the Stagepass scripts the live Webflow site loads.
4
- * Read-only: one public GET of the live page, parsed and never executed.
2
+ * Doctor checks: declared modules vs Stagepass scripts on the live site.
3
+ * Read-only public GET; HTML parsed, never executed.
5
4
  */
6
5
 
7
6
  import path from 'node:path';
@@ -41,7 +40,7 @@ export async function runProjectSiteChecks(opts = {}) {
41
40
  }
42
41
 
43
42
  if (opts.skipSite) return checks;
44
- const found = await resolveProjectOrigin(cwd, sp.data, { loadProjects: opts.loadProjects });
43
+ const found = await resolveProjectOrigin(cwd, sp.data, { loadProjects: opts.loadProjects, log: opts.log });
45
44
  if (!found) {
46
45
  checks.push({
47
46
  id: 'project.site',
@@ -1,12 +1,5 @@
1
1
  /**
2
- * Sync generated project files with the declared Stagepass modules
3
- * (used by `stagepass upgrade` and `stagepass doctor`).
4
- *
5
- * Writes only:
6
- * - stagepass.json `modules` (and `origin` when passed via --site)
7
- * - AGENTS.md managed block (created when missing)
8
- * - .cursor/rules/stagepass.mdc (created when missing, managed block refreshed)
9
- * - tsconfig.json / jsconfig.json `compilerOptions.types` (plain JSON only)
2
+ * Sync generated project files with declared Stagepass modules
10
3
  */
11
4
 
12
5
  import path from 'node:path';
@@ -25,10 +18,9 @@ import {
25
18
  typesForModules,
26
19
  } from './project-modules.js';
27
20
  import { loadProjects } from './projects.js';
28
- import { describeDetection, normalizeSiteUrl } from './site-detect.js';
21
+ import { describeDetection, normalizeSiteUrl, SITE_PORT_ERROR } from './site-detect.js';
29
22
 
30
23
  /**
31
- * Read and parse stagepass.json (null when missing or invalid).
32
24
  * @param {string} cwd
33
25
  * @param {typeof fs} [fse]
34
26
  * @returns {Promise<{ exists: boolean, data: Record<string, unknown> | null, raw: string, error?: string }>}
@@ -49,7 +41,6 @@ export async function readStagepassJson(cwd, fse = fs) {
49
41
  }
50
42
 
51
43
  /**
52
- * Declared modules from stagepass.json (`null` when missing or legacy boolean).
53
44
  * @param {Record<string, unknown> | null} data
54
45
  * @returns {string[] | null}
55
46
  */
@@ -59,10 +50,11 @@ export function declaredModules(data) {
59
50
  return result.ok ? result.modules : null;
60
51
  }
61
52
 
53
+ function warnPortSkip(log, source) {
54
+ if (log) log(`Skipped ${source}: it contains a port. Use the host only, e.g. my-site.webflow.io.`);
55
+ }
56
+
62
57
  /**
63
- * Live origin for a project: stagepass.json `origin`, else the first concrete
64
- * (non-wildcard) origin stored by `stagepass link` for this project folder.
65
- *
66
58
  * @param {string} cwd
67
59
  * @param {Record<string, unknown> | null} data
68
60
  * @param {{ loadProjects?: typeof loadProjects, realpath?: (p: string) => Promise<string> }} [deps]
@@ -72,6 +64,7 @@ export async function resolveProjectOrigin(cwd, data, deps = {}) {
72
64
  if (data && typeof data.origin === 'string' && data.origin.trim() !== '') {
73
65
  const check = normalizeSiteUrl(data.origin);
74
66
  if (check.ok) return { origin: check.host, source: 'stagepass.json' };
67
+ if (check.error === SITE_PORT_ERROR) warnPortSkip(deps.log, 'stagepass.json origin');
75
68
  }
76
69
  const load = deps.loadProjects || loadProjects;
77
70
  const realpath = deps.realpath || ((p) => fs.realpath(p));
@@ -99,21 +92,18 @@ export async function resolveProjectOrigin(cwd, data, deps = {}) {
99
92
  for (const origin of Array.isArray(entry.origins) ? entry.origins : []) {
100
93
  const check = normalizeSiteUrl(String(origin));
101
94
  if (check.ok) return { origin: check.host, source: 'stagepass link' };
95
+ if (check.error === SITE_PORT_ERROR) warnPortSkip(deps.log, 'linked origin from stagepass link');
102
96
  }
103
97
  }
104
98
  return null;
105
99
  }
106
100
 
107
101
  /**
108
- * Decide the declared modules list for `upgrade`.
109
- * Order: --site-modules flag, live site detection, existing stagepass.json,
110
- * interactive prompt. The npm dependency is only mentioned as a hint.
111
- *
112
102
  * @param {object} input
113
103
  * @param {string} input.cwd
114
- * @param {Record<string, unknown> | null} input.data stagepass.json
115
- * @param {object} input.pkg package.json
116
- * @param {object} input.options { siteModules?, site?, skipSite?, yes? }
104
+ * @param {Record<string, unknown> | null} input.data
105
+ * @param {object} input.pkg
106
+ * @param {object} input.options
117
107
  * @param {object} deps
118
108
  * @param {(site: string) => Promise<any>} deps.detectSite
119
109
  * @param {(question: string, def: string) => Promise<string>} [deps.ask]
@@ -147,7 +137,7 @@ export async function resolveUpgradeModules(input, deps) {
147
137
  if (!check.ok) return { ok: false, error: check.error };
148
138
  origin = check.host;
149
139
  } else {
150
- const found = await resolveProjectOrigin(cwd, data, { loadProjects: deps.loadProjects });
140
+ const found = await resolveProjectOrigin(cwd, data, { loadProjects: deps.loadProjects, log });
151
141
  origin = found ? found.origin : null;
152
142
  }
153
143
 
@@ -179,9 +169,7 @@ export async function resolveUpgradeModules(input, deps) {
179
169
  source = 'stagepass.json';
180
170
  }
181
171
 
182
- // Legacy `"modules": true` (CLI 2.0/2.1) meant "modules included", typed via
183
- // `@stagepass/modules` (all modules). Keep that as `["all"]` so an upgrade
184
- // without a live site result never removes types the project relied on.
172
+ // Legacy `"modules": true` meant all modules typed; keep as `["all"]` without a live site.
185
173
  if (!candidate && data?.modules === true) {
186
174
  candidate = ['all'];
187
175
  source = 'legacy "modules": true in stagepass.json';
@@ -228,9 +216,7 @@ export async function resolveUpgradeModules(input, deps) {
228
216
  }
229
217
 
230
218
  /**
231
- * Update `compilerOptions.types` in a tsconfig/jsconfig source.
232
- *
233
- * @param {string} raw file contents
219
+ * @param {string} raw
234
220
  * @param {string[]} modules
235
221
  * @param {{ modulesDependency: boolean, perModuleTypes?: boolean }} opts
236
222
  * @returns {{ status: 'updated' | 'unchanged' | 'skipped', content?: string, reason?: string, types?: string[] }}
@@ -273,14 +259,12 @@ export function updateConfigTypes(raw, modules, opts) {
273
259
  }
274
260
 
275
261
  /**
276
- * Plan file changes for the declared modules (pure, no writes).
277
- *
278
262
  * @param {object} input
279
263
  * @param {string} input.cwd
280
264
  * @param {string[]} input.modules
281
- * @param {string | null} [input.origin] stored in stagepass.json when set
282
- * @param {object} input.pkg package.json
283
- * @param {boolean} [input.perModuleTypes] false when @stagepass/modules has no per-module types (umbrella entry)
265
+ * @param {string | null} [input.origin]
266
+ * @param {object} input.pkg
267
+ * @param {boolean} [input.perModuleTypes]
284
268
  * @param {typeof fs} [fse]
285
269
  * @returns {Promise<{ writes: { file: string, content: string, action: string }[], notes: string[] }>}
286
270
  */
@@ -388,7 +372,6 @@ export async function planProjectSync(input, fse = fs) {
388
372
  }
389
373
 
390
374
  /**
391
- * Write planned changes (skips when dryRun).
392
375
  * @param {string} cwd
393
376
  * @param {{ file: string, content: string }[]} writes
394
377
  * @param {typeof fs} [fse]
@@ -1,39 +1,31 @@
1
- /**
2
- * Read-only npm registry lookups for @stagepass/* packages.
3
- *
4
- * Versions of @stagepass/cli, loader and modules are decoupled, and a release
5
- * can be staged on npm long before it is published. Generated projects and
6
- * `stagepass upgrade` therefore never derive a dependency range from the CLI's
7
- * own version: they only write ranges that a published version satisfies.
8
- */
1
+ /** Read-only npm registry lookups for @stagepass/* packages. */
9
2
 
10
3
  import fs from 'fs-extra';
11
4
  import path from 'node:path';
12
5
  import { defaultExec } from './exec.js';
13
6
  import { MODULE_IDS } from './project-modules.js';
7
+ import { STAGEPASS_PACKAGES_VERSION } from './versions.js';
14
8
 
15
- /** Major range used for new projects (matches the `@2` CDN embed policy). */
9
+ /** Major range for new projects (matches `@2` CDN embed policy). */
16
10
  export const PACKAGES_MAJOR_RANGE = '^2';
17
11
 
18
- /** First @stagepass/modules release with per-module type entry points. */
12
+ /** First @stagepass/modules release with per-module type entry points. */
19
13
  export const PER_MODULE_TYPES_SINCE = '2.2.0';
20
14
 
21
- const SEMVER_RE = /^(\d+)\.(\d+)\.(\d+)(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/;
15
+ const SEMVER_RE = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?$/;
22
16
  const PKG_NAME_RE = /^@stagepass\/[a-z0-9][a-z0-9._-]*$/;
23
17
 
24
18
  /**
25
- * Parse a semver string (prerelease kept as a flag).
26
19
  * @param {string} version
27
20
  * @returns {{ major: number, minor: number, patch: number, pre: boolean } | null}
28
21
  */
29
22
  export function parseSemver(version) {
30
- const m = SEMVER_RE.exec(String(version).trim());
23
+ const m = SEMVER_RE.exec(String(version));
31
24
  if (!m) return null;
32
- return { major: +m[1], minor: +m[2], patch: +m[3], pre: String(version).includes('-') };
25
+ return { major: +m[1], minor: +m[2], patch: +m[3], pre: Boolean(m[4]) };
33
26
  }
34
27
 
35
28
  /**
36
- * Compare two semver strings (prerelease suffix ignored for ordering).
37
29
  * @param {string} a
38
30
  * @param {string} b
39
31
  * @returns {number}
@@ -46,8 +38,6 @@ export function compareSemver(a, b) {
46
38
  }
47
39
 
48
40
  /**
49
- * Whether a stable version satisfies a simple range: exact `1.2.3`,
50
- * caret `^2`, `^2.2`, `^2.2.0`, or tilde `~2.2.0`. Prereleases never match.
51
41
  * @param {string} version
52
42
  * @param {string} range
53
43
  * @returns {boolean}
@@ -80,7 +70,6 @@ export function satisfiesSimple(version, range) {
80
70
  }
81
71
 
82
72
  /**
83
- * Highest published stable version satisfying a range.
84
73
  * @param {string[]} versions
85
74
  * @param {string} range
86
75
  * @returns {string | null}
@@ -94,9 +83,6 @@ export function maxSatisfying(versions, range) {
94
83
  }
95
84
 
96
85
  /**
97
- * Published dist-tags and versions of a package, or null when npm or the
98
- * network is unavailable (callers fall back to the major range).
99
- *
100
86
  * @param {string} name
101
87
  * @param {{ exec?: import('./exec.js').ExecFn, timeoutMs?: number }} [deps]
102
88
  * @returns {Promise<{ distTags: Record<string, string>, versions: string[] } | null>}
@@ -140,9 +126,7 @@ export async function fetchPublished(name, deps = {}) {
140
126
  }
141
127
 
142
128
  /**
143
- * Whether the @stagepass/modules version a range resolves to ships
144
- * per-module types (`@stagepass/modules/<id>`).
145
- * @param {string[] | null | undefined} versions published versions
129
+ * @param {string[] | null | undefined} versions
146
130
  * @param {string} range
147
131
  * @returns {boolean | null} null when unknown (no registry data)
148
132
  */
@@ -154,8 +138,7 @@ export function rangeHasPerModuleTypes(versions, range) {
154
138
  }
155
139
 
156
140
  /**
157
- * Whether the installed @stagepass/modules ships per-module types.
158
- * @param {string} cwd project directory
141
+ * @param {string} cwd
159
142
  * @param {typeof fs} [fse]
160
143
  * @returns {Promise<boolean | null>} null when not installed
161
144
  */
@@ -167,3 +150,35 @@ export async function installedHasPerModuleTypes(cwd, fse = fs) {
167
150
  }
168
151
  return true;
169
152
  }
153
+
154
+ /**
155
+ * @param {string} cwd
156
+ * @param {typeof fs} [fse]
157
+ * @returns {Promise<string | null>}
158
+ */
159
+ export async function installedLoaderVersion(cwd, fse = fs) {
160
+ const file = path.join(cwd, 'node_modules', '@stagepass', 'loader', 'package.json');
161
+ try {
162
+ if (!(await fse.pathExists(file))) return null;
163
+ const pkg = await fse.readJson(file);
164
+ const version = typeof pkg?.version === 'string' ? pkg.version : '';
165
+ return satisfiesSimple(version, PACKAGES_MAJOR_RANGE) ? version : null;
166
+ } catch {
167
+ return null;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Loader version for Webflow snippets (AC-14); never the CLI version.
173
+ * @param {object} options
174
+ * @param {{ distTags: Record<string, string>, versions: string[] } | null} options.published
175
+ * @param {string} options.cwd
176
+ * @param {string} [options.bundled]
177
+ * @param {typeof fs} [options.fse]
178
+ * @returns {Promise<string>}
179
+ */
180
+ export async function resolveSnippetLoaderVersion({ published, cwd, bundled, fse = fs }) {
181
+ const best = published ? maxSatisfying(published.versions, PACKAGES_MAJOR_RANGE) : null;
182
+ if (best) return best;
183
+ return (await installedLoaderVersion(cwd, fse)) || bundled || STAGEPASS_PACKAGES_VERSION;
184
+ }
@@ -1,9 +1,6 @@
1
1
  /**
2
- * Detect which Stagepass scripts a live Webflow site loads.
3
- *
4
- * Public GET only: https, no cookies or auth headers, max 3 redirects,
5
- * ~5 s timeout, size cap. The fetched HTML is parsed with regexes for
6
- * <script src> values and is never executed.
2
+ * Detect Stagepass scripts on a live Webflow site.
3
+ * Public GET only: https, no cookies/credentials; HTML scanned, never executed.
7
4
  */
8
5
 
9
6
  import { validateOriginEntry } from './origins.js';
@@ -12,26 +9,55 @@ import { MODULE_CHOICES, normalizeModulesList } from './project-modules.js';
12
9
  export const DETECT_TIMEOUT_MS = 5000;
13
10
  export const DETECT_MAX_BYTES = 2 * 1024 * 1024;
14
11
  export const DETECT_MAX_REDIRECTS = 3;
12
+ export const SITE_PORT_ERROR =
13
+ 'Site URL must not contain a port, also not :443. Use the host only, e.g. my-site.webflow.io.';
15
14
 
16
- // Bounded attribute run keeps the scan linear on hostile input.
15
+ // Bound attribute length so the scan stays linear on hostile input.
17
16
  const SCRIPT_TAG_RE = /<script\b[^<>]{0,4096}>/gi;
18
17
  const SRC_ATTR_RE = /\ssrc\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+))/i;
19
18
  const STAGEPASS_SRC_RE =
20
19
  /^(?:https?:)?\/\/(cdn\.jsdelivr\.net\/npm|unpkg\.com)\/@stagepass\/(loader|modules)(?:@([0-9A-Za-z.^~_-]+))?\/dist\/([a-z]+)(?:\.min)?\.js(?:[?#].*)?$/i;
21
20
 
22
21
  /**
23
- * Normalize a live site input (host or https URL) to an https URL.
24
- * Rejects http, wildcards, credentials, and invalid hosts.
25
- *
22
+ * True when the raw URL names a port (`:443`/`:0443` included).
23
+ * new URL drops default ports; read authority from the raw string before new URL.
24
+ * @param {string} input
25
+ * @returns {boolean}
26
+ */
27
+ function hasExplicitPort(input) {
28
+ const s = String(input == null ? '' : input)
29
+ .replace(/^[\u0000-\u0020]+|[\u0000-\u0020]+$/g, '')
30
+ .replace(/[\t\n\r]/g, '')
31
+ .replace(/\\/g, '/');
32
+ const scheme = /^[a-z][a-z0-9+.-]*:/i.exec(s);
33
+ const rest = scheme ? s.slice(scheme[0].length) : s;
34
+ // No authority without `//`.
35
+ if (!rest.startsWith('//')) return false;
36
+ const authority = rest.replace(/^\/+/, '').split(/[/?#]/, 1)[0];
37
+ const hostPort = authority.slice(authority.lastIndexOf('@') + 1);
38
+ if (hostPort.startsWith('[')) {
39
+ const end = hostPort.indexOf(']');
40
+ return end === -1 || hostPort.slice(end + 1).includes(':');
41
+ }
42
+ return hostPort.includes(':');
43
+ }
44
+
45
+ /**
46
+ * Normalize host/https URL; rejects http, wildcards, credentials, invalid hosts.
26
47
  * @param {string} input
27
48
  * @returns {{ ok: true, url: string, host: string } | { ok: false, error: string }}
28
49
  */
29
50
  export function normalizeSiteUrl(input) {
30
51
  const raw = String(input == null ? '' : input).trim();
31
52
  if (!raw) return { ok: false, error: 'No live site given.' };
53
+ const candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`;
54
+ // Port check on raw string before new URL (default ports would be dropped).
55
+ if (hasExplicitPort(candidate)) {
56
+ return { ok: false, error: SITE_PORT_ERROR };
57
+ }
32
58
  let url;
33
59
  try {
34
- url = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`);
60
+ url = new URL(candidate);
35
61
  } catch {
36
62
  return { ok: false, error: `Invalid site URL: ${raw}` };
37
63
  }
@@ -42,7 +68,7 @@ export function normalizeSiteUrl(input) {
42
68
  return { ok: false, error: 'Site URL must not contain credentials.' };
43
69
  }
44
70
  if (url.port) {
45
- return { ok: false, error: 'Site URL must not contain a port.' };
71
+ return { ok: false, error: SITE_PORT_ERROR };
46
72
  }
47
73
  const host = url.hostname.toLowerCase();
48
74
  const check = validateOriginEntry(host);
@@ -54,9 +80,7 @@ export function normalizeSiteUrl(input) {
54
80
  }
55
81
 
56
82
  /**
57
- * Remove `<!-- … -->` comments in linear time (a lazy regex is quadratic on
58
- * many unterminated `<!--`). An unterminated comment drops the rest.
59
- *
83
+ * Strip HTML comments in linear time (lazy regex is quadratic on unterminated `<!--`).
60
84
  * @param {string} html
61
85
  * @returns {string}
62
86
  */
@@ -78,8 +102,6 @@ function stripHtmlComments(html) {
78
102
  }
79
103
 
80
104
  /**
81
- * Parse Stagepass loader / module script tags from HTML (no execution).
82
- *
83
105
  * @param {string} html
84
106
  * @returns {{ loader: { version: string, cdn: string } | null, modules: { id: string, version: string, cdn: string }[] }}
85
107
  */
@@ -88,7 +110,6 @@ export function parseStagepassScripts(html) {
88
110
  let loader = null;
89
111
  /** @type {Map<string, { id: string, version: string, cdn: string }>} */
90
112
  const modules = new Map();
91
- // Ignore commented-out tags; the HTML is only scanned, never executed.
92
113
  const source = stripHtmlComments(String(html || ''));
93
114
 
94
115
  for (const match of source.matchAll(SCRIPT_TAG_RE)) {
@@ -115,7 +136,6 @@ export function parseStagepassScripts(html) {
115
136
  }
116
137
 
117
138
  /**
118
- * Declared-list form of detected modules (`all` wins).
119
139
  * @param {{ modules: { id: string }[] }} detection
120
140
  * @returns {string[]}
121
141
  */
@@ -125,7 +145,6 @@ export function detectedModulesList(detection) {
125
145
  }
126
146
 
127
147
  /**
128
- * Read a response body up to `maxBytes` (truncates; never throws on size).
129
148
  * @param {Response} res
130
149
  * @param {number} maxBytes
131
150
  */
@@ -153,9 +172,7 @@ async function readCapped(res, maxBytes) {
153
172
  }
154
173
 
155
174
  /**
156
- * Fetch a live page and detect Stagepass scripts.
157
- *
158
- * @param {string} siteInput host or https URL
175
+ * @param {string} siteInput
159
176
  * @param {object} [deps]
160
177
  * @param {typeof fetch} [deps.fetch]
161
178
  * @param {number} [deps.timeoutMs]
@@ -200,6 +217,10 @@ export async function detectSite(siteInput, deps = {}) {
200
217
  if (next.username || next.password) {
201
218
  return { ok: false, url: current, error: 'Redirect URL contains credentials.' };
202
219
  }
220
+ // Port check on raw Location before following (URL drops default ports).
221
+ if (next.port || hasExplicitPort(location)) {
222
+ return { ok: false, url: current, error: 'Redirect URL contains a port and was not followed.' };
223
+ }
203
224
  current = next.toString();
204
225
  continue;
205
226
  }
@@ -226,7 +247,6 @@ export async function detectSite(siteInput, deps = {}) {
226
247
  }
227
248
 
228
249
  /**
229
- * One-line summary of a detection result.
230
250
  * @param {Awaited<ReturnType<typeof detectSite>>} det
231
251
  */
232
252
  export function describeDetection(det) {
@@ -7,23 +7,21 @@ import { STAGEPASS_PACKAGES_VERSION } from './versions.js';
7
7
  * @returns {string}
8
8
  */
9
9
  export function sanitizeSnippetVersion(version) {
10
- const value = String(version == null ? '' : version).trim();
11
- // Allow optional ^/~ range prefixes used in package.json; reject quotes and HTML.
12
- if (!/^[~^]?[0-9A-Za-z][0-9A-Za-z._+-]*$/.test(value)) {
10
+ const value = String(version == null ? '' : version);
11
+ // Exact stable X.Y.Z only (no prerelease, build metadata, or ranges).
12
+ if (!/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(value)) {
13
13
  throw new Error(
14
- 'Invalid version for Webflow snippets (use a semver or npm dist-tag).'
14
+ 'Invalid version for Webflow snippets (use a stable X.Y.Z semver).'
15
15
  );
16
16
  }
17
17
  return value;
18
18
  }
19
19
 
20
20
  /**
21
- * Build recommended Webflow Custom Code snippets (jsDelivr major pin @2).
22
- *
23
21
  * @param {object} options
24
- * @param {string} options.version Exact package version for data-stagepass-version / docs
25
- * @param {boolean} [options.modules] Legacy: true = inject + cookies tags
26
- * @param {string[]} [options.moduleList] Declared modules (wins over `modules`)
22
+ * @param {string} options.version
23
+ * @param {boolean} [options.modules]
24
+ * @param {string[]} [options.moduleList]
27
25
  * @returns {{ head: string, footer: string, majorPin: string, exactPin: string }}
28
26
  */
29
27
  export function buildWebflowSnippets(options) {
@@ -79,8 +77,7 @@ export function buildWebflowSnippets(options) {
79
77
  }
80
78
 
81
79
  /**
82
- * Print head/footer snippets with section labels.
83
- * @param {{ head: string, footer: string }} snippets
80
+ * @param {{ head: string, footer: string, exactPin?: string }} snippets
84
81
  * @param {(msg: string) => void} [log]
85
82
  */
86
83
  export function printWebflowSnippets(snippets, log = console.log) {
@@ -89,6 +86,6 @@ export function printWebflowSnippets(snippets, log = console.log) {
89
86
  log('\nWebflow Custom Code (Footer):');
90
87
  log(snippets.footer);
91
88
  log(
92
- `\nOptional exact pin example (instead of @2): replace @2 with the exact version (e.g. @${STAGEPASS_PACKAGES_VERSION}).`
89
+ `\nOptional exact pin example (instead of @2): replace @2 with the exact version (e.g. ${snippets.exactPin || `@${STAGEPASS_PACKAGES_VERSION}`}).`
93
90
  );
94
91
  }