@pwaos.net/runtime-client-api 0.2.4 → 0.2.5

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": "@pwaos.net/runtime-client-api",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
4
4
  "type": "module",
5
5
  "description": "Node.js native addon for the PwaOS RuntimeClient API. Automatically resolves the matching Runtime SDK for your platform.",
6
6
  "engines": {
@@ -1,11 +1,15 @@
1
1
  'use strict';
2
2
  /**
3
- * resolve-sdk.js - locate the pwaos SDK (headers + client lib) and the
3
+ * resolve-sdk.cjs - locate the pwaos SDK (headers + client lib) and the
4
4
  * runtime bundle for this package.
5
5
  *
6
- * Shared by scripts/sdk-dir.js (build time) and test code. Sources, in order:
6
+ * Shared by scripts/sdk-dir.cjs (build time) and test code. The runtime
7
+ * DIR always lives at <platform package>/runtime, so runtime resolution
8
+ * delegates to scripts/runtime-resolver.cjs (the same candidate list and
9
+ * node_modules walk the shipped client uses). SDK sources, in order:
7
10
  *
8
- * 1. $PWAOS_SDK_DIR (an explicit SDK root, validated)
11
+ * 1. $PWAOS_SDK_DIR (an explicit SDK root, validated; build-time
12
+ * headers/lib override only - it never affects runtimeDir)
9
13
  * 2. the installed @pwaos.net/runtime-<platform>-<arch> package
10
14
  * (include/ + lib/<os>/ + runtime/ ship inside that package; this
11
15
  * is what makes `npm install @pwaos.net/runtime` self-contained - the
@@ -19,30 +23,21 @@
19
23
  * this one (optionalDependencies of @pwaos.net/runtime), so the require.resolve
20
24
  * walk below finds it.
21
25
  *
22
- * Runtime validity: the runtime dir is the platform package's runtime/
23
- * subdir and is only reported when runtime/pwaos_server exists and is NOT
24
- * an un-smudged git-lfs pointer (starts with the LFS version url).
26
+ * Runtime validity (runtime/pwaos_server exists) is checked by
27
+ * runtime-resolver.cjs.
25
28
  */
26
29
 
27
30
  const fs = require('fs');
28
31
  const path = require('path');
29
32
 
30
- // Installed platform subpackage that carries the SDK consumer files
31
- // (include/ + lib/<os>/). Written as a function so tests can stub it.
32
- function platformPackageName() {
33
- if (process.platform === 'linux') return '@pwaos.net/runtime-linux-x64';
34
- if (process.platform === 'win32') return '@pwaos.net/runtime-win32-x86';
35
- return null;
36
- }
33
+ const runtimeResolver = require('./runtime-resolver.cjs');
34
+ const { getPlatformPackageCandidates } = runtimeResolver;
37
35
 
38
36
  const HEADER_NAME = 'runtime_client_api.h';
39
37
  const LIB_SRC = {
40
38
  linux: 'lib/linux/libpwaos_runtime_api.so',
41
39
  win: 'lib/win/pwaos_runtime_api.dll',
42
40
  };
43
- const SERVER_BASENAME = process.platform === 'win32'
44
- ? 'pwaos_server.exe' : 'pwaos_server';
45
- const LFS_POINTER_MAGIC = 'version https://git-lfs';
46
41
 
47
42
  // Platform -> LIB_SRC key.
48
43
  function sdkOs() {
@@ -58,48 +53,27 @@ function dirHasSdkFiles(dir, osName) {
58
53
  );
59
54
  }
60
55
 
61
- /** True when the file exists but is an un-smudged git-lfs pointer. */
62
- function isLfsPointer(file) {
63
- try {
64
- const st = fs.statSync(file);
65
- if (st.size >= 512) return false; // pointers are ~130 bytes
66
- const head = fs.readFileSync(file, 'utf8');
67
- return head.startsWith(LFS_POINTER_MAGIC);
68
- } catch (_) {
69
- return false;
70
- }
71
- }
72
-
73
- /** The runtime subdir of an SDK dir, or null when it has no usable server. */
74
- function runtimeDirOf(sdkDir) {
75
- const rt = path.join(sdkDir, 'runtime');
76
- const server = path.join(rt, SERVER_BASENAME);
77
- try {
78
- if (!fs.statSync(server).isFile()) return null;
79
- } catch (_) {
80
- return null;
81
- }
82
- if (isLfsPointer(server)) return null;
83
- return rt;
84
- }
85
-
86
56
  /**
87
- * The SDK root of the installed platform subpackage, or null.
88
- * require.resolve is used from THIS file's directory so the same
89
- * node_modules walk applies (the client's own node_modules or any
90
- * ancestor's - matching how npm hoists optionalDependencies).
91
- * On failure every error is swallowed: "not installed" is normal.
57
+ * The SDK root of the first installed platform subpackage that carries
58
+ * include/ + lib/<os>/, or null. Uses the shared candidate list from
59
+ * runtime-resolver.cjs (same platform/arch derivation and win32 fallback
60
+ * order as the shipped client's runtime resolution). require.resolve is
61
+ * used from THIS file's directory so the same node_modules walk applies
62
+ * (the client's own node_modules or any ancestor's - matching how npm
63
+ * hoists optionalDependencies). On failure every error is swallowed:
64
+ * "not installed" is normal.
92
65
  */
93
66
  function installedSdkDir(osName) {
94
- const pkg = platformPackageName();
95
- if (!pkg) return null;
96
- let pkgRoot;
97
- try {
98
- pkgRoot = path.dirname(require.resolve(`${pkg}/package.json`));
99
- } catch (_) {
100
- return null;
67
+ for (const pkg of getPlatformPackageCandidates()) {
68
+ let pkgRoot;
69
+ try {
70
+ pkgRoot = path.dirname(require.resolve(`${pkg}/package.json`));
71
+ } catch (_) {
72
+ continue; // not installed - try the next candidate
73
+ }
74
+ if (dirHasSdkFiles(pkgRoot, osName)) return pkgRoot;
101
75
  }
102
- return dirHasSdkFiles(pkgRoot, osName) ? pkgRoot : null;
76
+ return null;
103
77
  }
104
78
 
105
79
  function resolveSdkDir(osName) {
@@ -112,18 +86,35 @@ function resolveSdkDir(osName) {
112
86
  return installedSdkDir(osName);
113
87
  }
114
88
 
89
+ /**
90
+ * The runtime DIR: always <installed platform package>/runtime, resolved
91
+ * by runtime-resolver.cjs (same candidate list and node_modules walk the
92
+ * shipped client uses, so build-time and run-time resolution can never
93
+ * drift). Returns null when no usable runtime is installed. Independent
94
+ * of PWAOS_SDK_DIR: that env var is a build-time headers/lib override and
95
+ * must not redirect the runtime lookup at a possibly older tree.
96
+ */
97
+ function resolveRuntimeDir() {
98
+ const osName = sdkOs();
99
+ if (!osName) return null;
100
+ try {
101
+ return runtimeResolver.resolveRuntimePath();
102
+ } catch (_) {
103
+ return null;
104
+ }
105
+ }
106
+
115
107
  /** Resolve {sdkDir, runtimeDir} per the documented order; either may be null. */
116
108
  function resolve() {
117
109
  const osName = sdkOs();
118
110
  if (!osName) return { sdkDir: null, runtimeDir: null };
119
- const sdkDir = resolveSdkDir(osName);
120
- return { sdkDir, runtimeDir: sdkDir ? runtimeDirOf(sdkDir) : null };
111
+ return {
112
+ sdkDir: resolveSdkDir(osName),
113
+ runtimeDir: resolveRuntimeDir(),
114
+ };
121
115
  }
122
116
 
123
117
  module.exports = {
124
118
  resolve,
125
- runtimeDirOf,
126
- isLfsPointer,
127
119
  installedSdkDir,
128
- SERVER_BASENAME,
129
120
  };
@@ -1,161 +0,0 @@
1
- 'use strict';
2
-
3
- const fs = require('fs');
4
- const os = require('os');
5
- const path = require('path');
6
- const https = require('https');
7
- const { execFileSync } = require('child_process');
8
-
9
- const ROOT = path.resolve(__dirname, '..');
10
- const SDK_DIR = path.join(ROOT, 'third_party', 'pwaos_sdk');
11
- const MARKER = path.join(SDK_DIR, '.installed');
12
-
13
- const VERSION = '0.2.a';
14
- const RELEASE_TAG = `v${VERSION}`;
15
-
16
- // 所有日志走 stderr,避免污染 gyp 读取的 stdout
17
- function log(...args) {
18
- process.stderr.write('[pwaos-sdk] ' + args.join(' ') + '\n');
19
- }
20
-
21
- function getPlatformInfo() {
22
- switch (process.platform) {
23
- case 'win32':
24
- return {
25
- name: 'win-x86',
26
- url: `https://github.com/daqingzd/pwaos/releases/download/${RELEASE_TAG}/pwaos_sdk-win-x86-v${VERSION}.0.7z`,
27
- };
28
- case 'linux':
29
- return {
30
- name: 'linux-x64',
31
- url: `https://github.com/daqingzd/pwaos/releases/download/${RELEASE_TAG}/pwaos_sdk-linux-x64-v${VERSION}.0.7z`,
32
- };
33
- default:
34
- throw new Error(`Unsupported platform: ${process.platform}`);
35
- }
36
- }
37
-
38
- function download(url, dest) {
39
- return new Promise((resolve, reject) => {
40
- log(`Downloading ${url}`);
41
- const file = fs.createWriteStream(dest);
42
-
43
- const request = (u, depth) => {
44
- if (depth > 5) {
45
- reject(new Error('Too many redirects'));
46
- return;
47
- }
48
- https
49
- .get(u, (res) => {
50
- if (
51
- res.statusCode >= 300 &&
52
- res.statusCode < 400 &&
53
- res.headers.location
54
- ) {
55
- res.resume();
56
- request(res.headers.location, depth + 1);
57
- return;
58
- }
59
- if (res.statusCode !== 200) {
60
- res.resume();
61
- reject(new Error(`HTTP ${res.statusCode} for ${u}`));
62
- return;
63
- }
64
- res.pipe(file);
65
- file.on('finish', () => file.close(() => resolve()));
66
- })
67
- .on('error', (err) => {
68
- file.close(() => {
69
- try { fs.unlinkSync(dest); } catch (_) {}
70
- reject(err);
71
- });
72
- });
73
- };
74
-
75
- request(url, 0);
76
- });
77
- }
78
-
79
- function extract7z(archive, destDir) {
80
- let sevenZip;
81
- try {
82
- sevenZip = require('7zip-bin').path7za;
83
- } catch (_) {
84
- throw new Error(
85
- 'Missing "7zip-bin" dependency. Run: npm install --save-dev 7zip-bin'
86
- );
87
- }
88
-
89
- log(`Extracting to ${destDir}`);
90
- fs.mkdirSync(destDir, { recursive: true });
91
- execFileSync(sevenZip, ['x', archive, `-o${destDir}`, '-y'], {
92
- stdio: ['ignore', 'ignore', 'inherit'],
93
- });
94
- }
95
-
96
- // 在解压目录中寻找包含 include/ 的 SDK 根目录
97
- function findSdkRoot(dir) {
98
- if (fs.existsSync(path.join(dir, 'include'))) return dir;
99
-
100
- for (const entry of fs.readdirSync(dir)) {
101
- const full = path.join(dir, entry);
102
- if (
103
- fs.statSync(full).isDirectory() &&
104
- fs.existsSync(path.join(full, 'include'))
105
- ) {
106
- return full;
107
- }
108
- }
109
- return null;
110
- }
111
-
112
- async function main() {
113
- if (fs.existsSync(MARKER)) {
114
- process.stdout.write(SDK_DIR.replace(/\\/g, '/'));
115
- return;
116
- }
117
-
118
- const info = getPlatformInfo();
119
- log(`Platform: ${info.name}`);
120
-
121
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pwaos-sdk-'));
122
- const archivePath = path.join(tmpDir, 'pwaos_sdk.7z');
123
- const extractDir = path.join(tmpDir, 'extracted');
124
-
125
- try {
126
- await download(info.url, archivePath);
127
- extract7z(archivePath, extractDir);
128
-
129
- const root = findSdkRoot(extractDir);
130
- if (!root) {
131
- throw new Error(
132
- 'Downloaded archive does not contain an "include" directory'
133
- );
134
- }
135
-
136
- // 清理旧的 SDK 目录,把新内容放进最终位置
137
- if (fs.existsSync(SDK_DIR)) {
138
- fs.rmSync(SDK_DIR, { recursive: true, force: true });
139
- }
140
- fs.mkdirSync(path.dirname(SDK_DIR), { recursive: true });
141
- fs.cpSync(root, SDK_DIR, { recursive: true });
142
-
143
- // 写标记文件,避免下次重复下载
144
- fs.writeFileSync(MARKER, new Date().toISOString());
145
-
146
- // 验证结果
147
- if (!fs.existsSync(path.join(SDK_DIR, 'include'))) {
148
- throw new Error('SDK install failed: include/ not found');
149
- }
150
-
151
- // 把 SDK 路径输出到 stdout,供 binding.gyp 使用
152
- process.stdout.write(SDK_DIR.replace(/\\/g, '/'));
153
- } finally {
154
- fs.rmSync(tmpDir, { recursive: true, force: true });
155
- }
156
- }
157
-
158
- main().catch((err) => {
159
- process.stderr.write(`[pwaos-sdk] ERROR: ${err.message}\n`);
160
- process.exit(1);
161
- });