@swipt/cli 0.1.0-nightly.97 → 0.1.0-nightly.99
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/dist/availability.d.ts +3 -1
- package/dist/availability.js +173 -151
- package/dist/availability.js.map +1 -1
- package/dist/cli/cli.js +52 -66
- package/dist/cli/cli.js.map +1 -1
- package/dist/cli/command.d.ts +9 -0
- package/dist/cli/command.js.map +1 -1
- package/dist/cli/commands/data/clear.js +2 -2
- package/dist/cli/commands/data/clear.js.map +1 -1
- package/dist/cli/commands/data/data.js +2 -2
- package/dist/cli/commands/data/data.js.map +1 -1
- package/dist/cli/commands/data/list.js +3 -3
- package/dist/cli/commands/data/list.js.map +1 -1
- package/dist/cli/commands/data/operand.js.map +1 -1
- package/dist/cli/commands/data/read.js +4 -7
- package/dist/cli/commands/data/read.js.map +1 -1
- package/dist/cli/commands/data/remove.js +3 -3
- package/dist/cli/commands/data/remove.js.map +1 -1
- package/dist/cli/commands/data/write.js +2 -2
- package/dist/cli/commands/data/write.js.map +1 -1
- package/dist/cli/commands/device/add.js +2 -2
- package/dist/cli/commands/device/add.js.map +1 -1
- package/dist/cli/commands/device/device.js +2 -2
- package/dist/cli/commands/device/device.js.map +1 -1
- package/dist/cli/commands/device/list.js +2 -2
- package/dist/cli/commands/device/list.js.map +1 -1
- package/dist/cli/commands/device/logs.js +44 -46
- package/dist/cli/commands/device/logs.js.map +1 -1
- package/dist/cli/commands/device/remove.js +2 -2
- package/dist/cli/commands/device/remove.js.map +1 -1
- package/dist/cli/commands/device/stop.js +3 -3
- package/dist/cli/commands/device/stop.js.map +1 -1
- package/dist/cli/commands/driver/driver.js +6 -6
- package/dist/cli/commands/driver/driver.js.map +1 -1
- package/dist/cli/commands/flags.js +9 -9
- package/dist/cli/commands/flags.js.map +1 -1
- package/dist/cli/commands/index.js +2 -2
- package/dist/cli/commands/index.js.map +1 -1
- package/dist/cli/commands/project/build.js +2 -2
- package/dist/cli/commands/project/build.js.map +1 -1
- package/dist/cli/commands/project/create.js +3 -3
- package/dist/cli/commands/project/create.js.map +1 -1
- package/dist/cli/commands/project/deploy.js +2 -2
- package/dist/cli/commands/project/deploy.js.map +1 -1
- package/dist/cli/commands/project/develop.js +19 -19
- package/dist/cli/commands/project/develop.js.map +1 -1
- package/dist/cli/commands/project/project.js +2 -2
- package/dist/cli/commands/project/project.js.map +1 -1
- package/dist/cli/commands/project/source.js +62 -37
- package/dist/cli/commands/project/source.js.map +1 -1
- package/dist/cli/commands/repl/api.js +2 -2
- package/dist/cli/commands/repl/api.js.map +1 -1
- package/dist/cli/commands/repl/repl.js +4 -4
- package/dist/cli/commands/repl/repl.js.map +1 -1
- package/dist/cli/commands/repl/reset.js +2 -2
- package/dist/cli/commands/repl/reset.js.map +1 -1
- package/dist/cli/commands/repl/run.js +5 -5
- package/dist/cli/commands/repl/run.js.map +1 -1
- package/dist/cli/commands/sideload/install.js +4 -4
- package/dist/cli/commands/sideload/install.js.map +1 -1
- package/dist/cli/commands/sideload/setup.js +3 -3
- package/dist/cli/commands/sideload/setup.js.map +1 -1
- package/dist/cli/commands/sideload/sideload.js +2 -2
- package/dist/cli/commands/sideload/sideload.js.map +1 -1
- package/dist/cli/commands/sideload/uninstall.js +2 -2
- package/dist/cli/commands/sideload/uninstall.js.map +1 -1
- package/dist/cli/commands/sideload/update.js +3 -3
- package/dist/cli/commands/sideload/update.js.map +1 -1
- package/dist/cli/commands/swiplet/call.js +6 -6
- package/dist/cli/commands/swiplet/call.js.map +1 -1
- package/dist/cli/commands/swiplet/install.js +3 -3
- package/dist/cli/commands/swiplet/install.js.map +1 -1
- package/dist/cli/commands/swiplet/list.js +8 -8
- package/dist/cli/commands/swiplet/list.js.map +1 -1
- package/dist/cli/commands/swiplet/remove.js +3 -3
- package/dist/cli/commands/swiplet/remove.js.map +1 -1
- package/dist/cli/commands/swiplet/service/disable.js +3 -3
- package/dist/cli/commands/swiplet/service/disable.js.map +1 -1
- package/dist/cli/commands/swiplet/service/enable.js +3 -3
- package/dist/cli/commands/swiplet/service/enable.js.map +1 -1
- package/dist/cli/commands/swiplet/service/service.js +2 -2
- package/dist/cli/commands/swiplet/service/service.js.map +1 -1
- package/dist/cli/commands/swiplet/service/services.js +2 -2
- package/dist/cli/commands/swiplet/service/services.js.map +1 -1
- package/dist/cli/commands/swiplet/service/watch.js +2 -2
- package/dist/cli/commands/swiplet/service/watch.js.map +1 -1
- package/dist/cli/commands/swiplet/show.js +6 -6
- package/dist/cli/commands/swiplet/show.js.map +1 -1
- package/dist/cli/commands/swiplet/swiplet.js +4 -4
- package/dist/cli/commands/swiplet/swiplet.js.map +1 -1
- package/dist/cli/commands/version/version.js +2 -2
- package/dist/cli/commands/version/version.js.map +1 -1
- package/dist/cli/deploy.js +9 -7
- package/dist/cli/deploy.js.map +1 -1
- package/dist/cli/session.js.map +1 -1
- package/dist/client.d.ts +145 -7
- package/dist/client.js +20 -22
- package/dist/client.js.map +1 -1
- package/dist/connection.d.ts +292 -25
- package/dist/connection.js +36 -35
- package/dist/connection.js.map +1 -1
- package/dist/driver.d.ts +62 -23
- package/dist/driver.js +29 -33
- package/dist/driver.js.map +1 -1
- package/dist/i18n.d.ts +2 -5
- package/dist/i18n.js +15 -13
- package/dist/i18n.js.map +1 -1
- package/dist/i18next.d.ts +7 -0
- package/dist/ignore.d.ts +14 -7
- package/dist/ignore.js +13 -14
- package/dist/ignore.js.map +1 -1
- package/dist/mdns.d.ts +2 -2
- package/dist/mdns.js +1 -1
- package/dist/mdns.js.map +1 -1
- package/dist/metro.d.ts +19 -5
- package/dist/metro.js +61 -63
- package/dist/metro.js.map +1 -1
- package/dist/output.d.ts +29 -14
- package/dist/output.js +17 -15
- package/dist/output.js.map +1 -1
- package/dist/passcode.d.ts +12 -8
- package/dist/passcode.js +18 -18
- package/dist/passcode.js.map +1 -1
- package/dist/project.d.ts +20 -10
- package/dist/project.js +72 -49
- package/dist/project.js.map +1 -1
- package/dist/proto/common_pb.d.ts +240 -0
- package/dist/proto/common_pb.js +7 -2
- package/dist/proto/common_pb.js.map +1 -1
- package/dist/proto/logs_pb.d.ts +38 -0
- package/dist/proto/repl_pb.d.ts +96 -0
- package/dist/proto/swiplets_pb.d.ts +361 -0
- package/dist/proto/swiplets_pb.js +7 -2
- package/dist/proto/swiplets_pb.js.map +1 -1
- package/dist/proto/system_pb.d.ts +33 -0
- package/dist/resources.d.ts +400 -0
- package/dist/serve.d.ts +9 -1
- package/dist/serve.js +17 -16
- package/dist/serve.js.map +1 -1
- package/dist/sideload.d.ts +27 -14
- package/dist/sideload.js +102 -89
- package/dist/sideload.js.map +1 -1
- package/dist/swipt-app.d.ts +19 -9
- package/dist/swipt-app.js +1 -1
- package/dist/swipt-app.js.map +1 -1
- package/locales/ar/translation.json +413 -0
- package/locales/bg/translation.json +397 -0
- package/locales/bn/translation.json +397 -0
- package/locales/ca/translation.json +401 -0
- package/locales/cs/translation.json +405 -0
- package/locales/da/translation.json +397 -0
- package/locales/de/translation.json +397 -0
- package/locales/el/translation.json +397 -0
- package/locales/en/translation.json +397 -0
- package/locales/es/translation.json +401 -0
- package/locales/es-419/translation.json +401 -0
- package/locales/fi/translation.json +397 -0
- package/locales/fr/translation.json +401 -0
- package/locales/fr-CA/translation.json +401 -0
- package/locales/gu/translation.json +397 -0
- package/locales/he/translation.json +401 -0
- package/locales/hi/translation.json +397 -0
- package/locales/hr/translation.json +401 -0
- package/locales/hu/translation.json +397 -0
- package/locales/id/translation.json +393 -0
- package/locales/it/translation.json +401 -0
- package/locales/ja/translation.json +393 -0
- package/locales/kk/translation.json +397 -0
- package/locales/kn/translation.json +397 -0
- package/locales/ko/translation.json +393 -0
- package/locales/lt/translation.json +405 -0
- package/locales/ml/translation.json +397 -0
- package/locales/mr/translation.json +397 -0
- package/locales/ms/translation.json +393 -0
- package/locales/nb/translation.json +397 -0
- package/locales/nl/translation.json +397 -0
- package/locales/or/translation.json +397 -0
- package/locales/pa/translation.json +397 -0
- package/locales/pl/translation.json +405 -0
- package/locales/pt-BR/translation.json +401 -0
- package/locales/pt-PT/translation.json +401 -0
- package/locales/ro/translation.json +401 -0
- package/locales/ru/translation.json +405 -0
- package/locales/sk/translation.json +405 -0
- package/locales/sl/translation.json +405 -0
- package/locales/sv/translation.json +397 -0
- package/locales/ta/translation.json +397 -0
- package/locales/te/translation.json +397 -0
- package/locales/th/translation.json +393 -0
- package/locales/tr/translation.json +397 -0
- package/locales/uk/translation.json +405 -0
- package/locales/ur/translation.json +397 -0
- package/locales/vi/translation.json +397 -0
- package/locales/zh-HK/translation.json +393 -0
- package/locales/zh-Hans/translation.json +393 -0
- package/locales/zh-Hant/translation.json +393 -0
- package/package.json +14 -9
- package/locales/ar.json +0 -311
- package/locales/bg.json +0 -295
- package/locales/bn.json +0 -295
- package/locales/ca.json +0 -299
- package/locales/cs.json +0 -303
- package/locales/da.json +0 -295
- package/locales/de.json +0 -295
- package/locales/el.json +0 -295
- package/locales/es-419.json +0 -299
- package/locales/es.json +0 -299
- package/locales/fi.json +0 -295
- package/locales/fr-CA.json +0 -299
- package/locales/fr.json +0 -299
- package/locales/gu.json +0 -295
- package/locales/he.json +0 -299
- package/locales/hi.json +0 -295
- package/locales/hr.json +0 -299
- package/locales/hu.json +0 -295
- package/locales/id.json +0 -283
- package/locales/it.json +0 -299
- package/locales/ja.json +0 -283
- package/locales/kk.json +0 -295
- package/locales/kn.json +0 -295
- package/locales/ko.json +0 -283
- package/locales/lt.json +0 -303
- package/locales/ml.json +0 -295
- package/locales/mr.json +0 -295
- package/locales/ms.json +0 -283
- package/locales/nb.json +0 -295
- package/locales/nl.json +0 -295
- package/locales/or.json +0 -295
- package/locales/pa.json +0 -295
- package/locales/pl.json +0 -303
- package/locales/pt-BR.json +0 -299
- package/locales/pt-PT.json +0 -299
- package/locales/ro.json +0 -299
- package/locales/ru.json +0 -303
- package/locales/sk.json +0 -303
- package/locales/sl.json +0 -303
- package/locales/sv.json +0 -295
- package/locales/ta.json +0 -295
- package/locales/te.json +0 -295
- package/locales/th.json +0 -283
- package/locales/tr.json +0 -295
- package/locales/uk.json +0 -303
- package/locales/ur.json +0 -295
- package/locales/vi.json +0 -295
- package/locales/zh-HK.json +0 -283
- package/locales/zh-Hans.json +0 -283
- package/locales/zh-Hant.json +0 -283
package/dist/metro.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t } from "./i18n.js";
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { transformAsync } from "@babel/core";
|
|
6
|
+
import { template, transformAsync, types } from "@babel/core";
|
|
7
7
|
import { loadProjectEnv } from "@expo/env";
|
|
8
8
|
import { imageSize } from "image-size";
|
|
9
9
|
// src/metro.ts
|
|
@@ -97,10 +97,7 @@ const platformSuffixes = [
|
|
|
97
97
|
".ios",
|
|
98
98
|
".native"
|
|
99
99
|
];
|
|
100
|
-
const platformRank =
|
|
101
|
-
ios: 2,
|
|
102
|
-
native: 1
|
|
103
|
-
};
|
|
100
|
+
const platformRank = /* @__PURE__ */ new Map([["ios", 2], ["native", 1]]);
|
|
104
101
|
const posix = (file) => file.split(path.sep).join("/");
|
|
105
102
|
const escape = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
106
103
|
function loadEnvironment(root) {
|
|
@@ -120,57 +117,58 @@ function defaultPreset(root) {
|
|
|
120
117
|
function contextFiles(directory, recursive) {
|
|
121
118
|
if (!fs.existsSync(directory)) return [];
|
|
122
119
|
const extensions = /* @__PURE__ */ new Set([...sourceExtensions, ...assetExtensions]);
|
|
123
|
-
return fs.readdirSync(directory, {
|
|
120
|
+
return fs.readdirSync(directory, {
|
|
121
|
+
encoding: "utf8",
|
|
122
|
+
recursive
|
|
123
|
+
}).map(posix).filter((file) => extensions.has(path.extname(file).slice(1)) && fs.statSync(path.join(directory, file)).isFile()).sort();
|
|
124
124
|
}
|
|
125
|
-
function
|
|
126
|
-
|
|
127
|
-
if (
|
|
128
|
-
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
}));
|
|
137
|
-
};
|
|
138
|
-
const pattern = (call, index) => {
|
|
139
|
-
const node = call.node.arguments[index];
|
|
140
|
-
if (node === void 0) return /^\.\/.*$/;
|
|
141
|
-
if (!t.isRegExpLiteral(node)) throw call.buildCodeFrameError(tr("Argument {index} of require.context must be a regular expression literal.", { index: index + 1 }));
|
|
142
|
-
return new RegExp(node.pattern, node.flags.replace(/[gy]/g, ""));
|
|
143
|
-
};
|
|
144
|
-
return {
|
|
145
|
-
name: "swipt-require-context",
|
|
146
|
-
visitor: { CallExpression(call, state) {
|
|
147
|
-
const { callee } = call.node;
|
|
148
|
-
if (!t.isMemberExpression(callee) || !t.isIdentifier(callee.object, { name: "require" }) || call.scope.hasBinding("require") || !(callee.computed ? t.isStringLiteral(callee.property, { value: "context" }) : t.isIdentifier(callee.property, { name: "context" }))) return;
|
|
149
|
-
const from = path.dirname(state.filename);
|
|
150
|
-
const directory = path.resolve(from, argument(call, 0, void 0, tr("a string"), (value) => typeof value === "string"));
|
|
151
|
-
const recursive = argument(call, 1, true, tr("a Boolean"), (value) => typeof value === "boolean");
|
|
152
|
-
const filter = pattern(call, 2);
|
|
153
|
-
const mode = argument(call, 3, "sync", tr("one of {values}", { values: contextModes.join(", ") }), (value) => contextModes.includes(value));
|
|
154
|
-
const entries = contextFiles(directory, recursive).map((file) => `./${file}`).filter((key) => filter.test(key)).map((key) => {
|
|
155
|
-
const target = posix(path.relative(from, path.join(directory, key)));
|
|
156
|
-
return `${JSON.stringify(key)}: () => require(${JSON.stringify(target.startsWith(".") ? target : `./${target}`)})`;
|
|
157
|
-
});
|
|
158
|
-
call.replaceWith(template.expression.ast(`(() => {
|
|
159
|
-
const modules = { ${entries.join(", ")} };
|
|
160
|
-
const context = key => {
|
|
161
|
-
if (!Object.prototype.hasOwnProperty.call(modules, key)) {
|
|
162
|
-
throw Object.assign(new Error("Cannot find module '" + key + "'"), { code: "MODULE_NOT_FOUND" });
|
|
163
|
-
}
|
|
164
|
-
return ${mode === "sync" ? "modules[key]()" : "Promise.resolve().then(modules[key])"};
|
|
165
|
-
};
|
|
166
|
-
context.keys = () => Object.keys(modules);
|
|
167
|
-
context.resolve = key => key;
|
|
168
|
-
context.id = ${JSON.stringify(posix(path.relative(state.cwd, directory)) || ".")};
|
|
169
|
-
return context;
|
|
170
|
-
})()`));
|
|
171
|
-
} }
|
|
172
|
-
};
|
|
125
|
+
function contextArgument(call, index, fallback, expected, check) {
|
|
126
|
+
if (call.node.arguments[index] === void 0) {
|
|
127
|
+
if (fallback !== void 0) return fallback;
|
|
128
|
+
} else {
|
|
129
|
+
const { confident, value } = call.get("arguments")[index].evaluate();
|
|
130
|
+
if (confident && check(value)) return value;
|
|
131
|
+
}
|
|
132
|
+
throw call.buildCodeFrameError(t("metro.contextArgument", {
|
|
133
|
+
index: index + 1,
|
|
134
|
+
expected
|
|
135
|
+
}));
|
|
173
136
|
}
|
|
137
|
+
function contextPattern(call, index) {
|
|
138
|
+
const node = call.node.arguments[index];
|
|
139
|
+
if (node === void 0) return /^\.\/.*$/;
|
|
140
|
+
if (!types.isRegExpLiteral(node)) throw call.buildCodeFrameError(t("metro.contextRegExp", { index: index + 1 }));
|
|
141
|
+
return new RegExp(node.pattern, node.flags.replace(/[gy]/g, ""));
|
|
142
|
+
}
|
|
143
|
+
const requireContext = {
|
|
144
|
+
name: "swipt-require-context",
|
|
145
|
+
visitor: { CallExpression(call, state) {
|
|
146
|
+
const { callee } = call.node;
|
|
147
|
+
if (state.filename === void 0 || !types.isMemberExpression(callee) || !types.isIdentifier(callee.object, { name: "require" }) || call.scope.hasBinding("require") || !(callee.computed ? types.isStringLiteral(callee.property, { value: "context" }) : types.isIdentifier(callee.property, { name: "context" }))) return;
|
|
148
|
+
const from = path.dirname(state.filename);
|
|
149
|
+
const directory = path.resolve(from, contextArgument(call, 0, void 0, t("metro.string"), (value) => typeof value === "string"));
|
|
150
|
+
const recursive = contextArgument(call, 1, true, t("metro.boolean"), (value) => typeof value === "boolean");
|
|
151
|
+
const filter = contextPattern(call, 2);
|
|
152
|
+
const mode = contextArgument(call, 3, "sync", t("metro.oneOf", { values: contextModes.join(", ") }), (value) => typeof value === "string" && contextModes.includes(value));
|
|
153
|
+
const entries = contextFiles(directory, recursive).map((file) => `./${file}`).filter((key) => filter.test(key)).map((key) => {
|
|
154
|
+
const target = posix(path.relative(from, path.join(directory, key)));
|
|
155
|
+
return `${JSON.stringify(key)}: () => require(${JSON.stringify(target.startsWith(".") ? target : `./${target}`)})`;
|
|
156
|
+
});
|
|
157
|
+
call.replaceWith(template.expression.ast(`(() => {
|
|
158
|
+
const modules = { ${entries.join(", ")} };
|
|
159
|
+
const context = key => {
|
|
160
|
+
if (!Object.prototype.hasOwnProperty.call(modules, key)) {
|
|
161
|
+
throw Object.assign(new Error("Cannot find module '" + key + "'"), { code: "MODULE_NOT_FOUND" });
|
|
162
|
+
}
|
|
163
|
+
return ${mode === "sync" ? "modules[key]()" : "Promise.resolve().then(modules[key])"};
|
|
164
|
+
};
|
|
165
|
+
context.keys = () => Object.keys(modules);
|
|
166
|
+
context.resolve = key => key;
|
|
167
|
+
context.id = ${JSON.stringify(posix(path.relative(state.cwd, directory)) || ".")};
|
|
168
|
+
return context;
|
|
169
|
+
})()`));
|
|
170
|
+
} }
|
|
171
|
+
};
|
|
174
172
|
const loaderOf = (file) => {
|
|
175
173
|
const extension = path.extname(file);
|
|
176
174
|
return extension === ".tsx" ? "tsx" : [
|
|
@@ -199,7 +197,7 @@ function assetVariants(resolved) {
|
|
|
199
197
|
const match = pattern.exec(name);
|
|
200
198
|
if (match === null) continue;
|
|
201
199
|
const scale = match[1] === void 0 ? 1 : Number(match[1]);
|
|
202
|
-
const rank = platformRank
|
|
200
|
+
const rank = platformRank.get(match[2]) ?? 0;
|
|
203
201
|
if (Number.isFinite(scale) && (scales.get(scale)?.rank ?? -1) < rank) scales.set(scale, {
|
|
204
202
|
rank,
|
|
205
203
|
file: path.join(directory, name)
|
|
@@ -236,7 +234,7 @@ function checkWorklets(root) {
|
|
|
236
234
|
}
|
|
237
235
|
const { version } = JSON.parse(fs.readFileSync(path.join(path.dirname(plugin), "..", "package.json"), "utf8"));
|
|
238
236
|
const { version: expected } = require("react-native-worklets/package.json");
|
|
239
|
-
if (version !== expected) throw new Error(
|
|
237
|
+
if (version !== expected) throw new Error(t("metro.workletsMismatch", {
|
|
240
238
|
version,
|
|
241
239
|
expected
|
|
242
240
|
}));
|
|
@@ -312,7 +310,7 @@ function metro(root, { assets, sourcemap }) {
|
|
|
312
310
|
};
|
|
313
311
|
first ??= found;
|
|
314
312
|
}
|
|
315
|
-
return { errors: first
|
|
313
|
+
return { errors: first?.errors };
|
|
316
314
|
});
|
|
317
315
|
build.onLoad({
|
|
318
316
|
filter: /.*/,
|
|
@@ -327,19 +325,19 @@ function metro(root, { assets, sourcemap }) {
|
|
|
327
325
|
filter: /\.[cm]?[jt]sx?$/,
|
|
328
326
|
namespace: "file"
|
|
329
327
|
}, async (args) => {
|
|
330
|
-
const
|
|
328
|
+
const code = (await transformAsync(await fs.promises.readFile(args.path, "utf8"), {
|
|
331
329
|
...babel,
|
|
332
330
|
filename: args.path,
|
|
333
331
|
caller: {
|
|
334
332
|
...caller,
|
|
335
333
|
isNodeModule: args.path.includes("node_modules")
|
|
336
334
|
}
|
|
337
|
-
});
|
|
338
|
-
return
|
|
339
|
-
contents:
|
|
335
|
+
}))?.code;
|
|
336
|
+
return typeof code === "string" ? {
|
|
337
|
+
contents: code,
|
|
340
338
|
loader: loaderOf(args.path),
|
|
341
339
|
resolveDir: path.dirname(args.path)
|
|
342
|
-
};
|
|
340
|
+
} : void 0;
|
|
343
341
|
});
|
|
344
342
|
}
|
|
345
343
|
};
|
package/dist/metro.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"metro.js","names":[],"sources":["../src/metro.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { transformAsync } from \"@babel/core\";\nimport { loadProjectEnv } from \"@expo/env\";\nimport { imageSize } from \"image-size\";\n\nimport { tr } from \"./i18n\";\n\nconst require = createRequire(import.meta.url);\nconst cliDirectory = path.dirname(fileURLToPath(import.meta.url));\n\nconst sourceExtensions = [\"js\", \"jsx\", \"json\", \"ts\", \"tsx\", \"cjs\", \"mjs\"];\nconst assetExtensions = [\n \"bmp\",\n \"gif\",\n \"jpg\",\n \"jpeg\",\n \"png\",\n \"psd\",\n \"svg\",\n \"webp\",\n \"xml\",\n \"m4v\",\n \"mov\",\n \"mp4\",\n \"mpeg\",\n \"mpg\",\n \"webm\",\n \"aac\",\n \"aiff\",\n \"caf\",\n \"m4a\",\n \"mp3\",\n \"wav\",\n \"html\",\n \"pdf\",\n \"yaml\",\n \"yml\",\n \"otf\",\n \"ttf\",\n \"zip\",\n \"db\",\n \"sqlite\",\n \"sqlite3\",\n];\nconst imageExtensions = new Set([\n \"png\",\n \"jpg\",\n \"jpeg\",\n \"bmp\",\n \"gif\",\n \"webp\",\n \"psd\",\n \"svg\",\n \"tiff\",\n \"ktx\",\n]);\nconst babelConfigNames = [\n \".babelrc\",\n \".babelrc.js\",\n \".babelrc.cjs\",\n \".babelrc.mjs\",\n \".babelrc.json\",\n \".babelrc.cts\",\n \"babel.config.js\",\n \"babel.config.cjs\",\n \"babel.config.mjs\",\n \"babel.config.json\",\n \"babel.config.cts\",\n \"babel.config.ts\",\n \"babel.config.mts\",\n];\nconst contextModes = [\"sync\", \"eager\", \"lazy\", \"lazy-once\"];\nconst scaleSuffixes = [\"\", \"@1x\", \"@1.5x\", \"@2x\", \"@3x\", \"@4x\"];\nconst platformSuffixes = [\"\", \".ios\", \".native\"];\nconst platformRank = { ios: 2, native: 1 };\n\nconst posix = (file) => file.split(path.sep).join(\"/\");\nconst escape = (text) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nexport function loadEnvironment(root) {\n loadProjectEnv(root, { mode: \"production\", silent: true });\n process.env.BABEL_ENV ??= \"production\";\n}\n\nfunction defaultPreset(root) {\n try {\n return createRequire(path.join(root, \"package.json\")).resolve(\n \"expo/internal/babel-preset\",\n );\n } catch {\n return require.resolve(\"babel-preset-expo\");\n }\n}\n\nfunction contextFiles(directory, recursive) {\n if (!fs.existsSync(directory)) {\n return [];\n }\n const extensions = new Set([...sourceExtensions, ...assetExtensions]);\n return fs\n .readdirSync(directory, { recursive })\n .map(posix)\n .filter(\n (file) =>\n extensions.has(path.extname(file).slice(1)) &&\n fs.statSync(path.join(directory, file)).isFile(),\n )\n .sort();\n}\n\nfunction requireContext({ types: t, template }) {\n const argument = (call, index, fallback, expected, check) => {\n if (call.node.arguments[index] === undefined) {\n if (fallback !== undefined) {\n return fallback;\n }\n } else {\n const { confident, value } = call.get(`arguments.${index}`).evaluate();\n if (confident && check(value)) {\n return value;\n }\n }\n throw call.buildCodeFrameError(\n tr(\"Argument {index} of require.context must be {expected}\", {\n index: index + 1,\n expected,\n }),\n );\n };\n const pattern = (call, index) => {\n const node = call.node.arguments[index];\n if (node === undefined) {\n return /^\\.\\/.*$/;\n }\n if (!t.isRegExpLiteral(node)) {\n throw call.buildCodeFrameError(\n tr(\n \"Argument {index} of require.context must be a regular expression literal.\",\n { index: index + 1 },\n ),\n );\n }\n return new RegExp(node.pattern, node.flags.replace(/[gy]/g, \"\"));\n };\n return {\n name: \"swipt-require-context\",\n visitor: {\n CallExpression(call, state) {\n const { callee } = call.node;\n if (\n !t.isMemberExpression(callee) ||\n !t.isIdentifier(callee.object, { name: \"require\" }) ||\n call.scope.hasBinding(\"require\") ||\n !(callee.computed\n ? t.isStringLiteral(callee.property, { value: \"context\" })\n : t.isIdentifier(callee.property, { name: \"context\" }))\n ) {\n return;\n }\n const from = path.dirname(state.filename);\n const directory = path.resolve(\n from,\n argument(\n call,\n 0,\n undefined,\n tr(\"a string\"),\n (value) => typeof value === \"string\",\n ),\n );\n const recursive = argument(\n call,\n 1,\n true,\n tr(\"a Boolean\"),\n (value) => typeof value === \"boolean\",\n );\n const filter = pattern(call, 2);\n const mode = argument(\n call,\n 3,\n \"sync\",\n tr(\"one of {values}\", { values: contextModes.join(\", \") }),\n (value) => contextModes.includes(value),\n );\n const entries = contextFiles(directory, recursive)\n .map((file) => `./${file}`)\n .filter((key) => filter.test(key))\n .map((key) => {\n const target = posix(\n path.relative(from, path.join(directory, key)),\n );\n return `${JSON.stringify(key)}: () => require(${JSON.stringify(target.startsWith(\".\") ? target : `./${target}`)})`;\n });\n call.replaceWith(\n template.expression.ast(`(() => {\n const modules = { ${entries.join(\", \")} };\n const context = key => {\n if (!Object.prototype.hasOwnProperty.call(modules, key)) {\n throw Object.assign(new Error(\"Cannot find module '\" + key + \"'\"), { code: \"MODULE_NOT_FOUND\" });\n }\n return ${mode === \"sync\" ? \"modules[key]()\" : \"Promise.resolve().then(modules[key])\"};\n };\n context.keys = () => Object.keys(modules);\n context.resolve = key => key;\n context.id = ${JSON.stringify(posix(path.relative(state.cwd, directory)) || \".\")};\n return context;\n })()`),\n );\n },\n },\n };\n}\n\nconst loaderOf = (file) => {\n const extension = path.extname(file);\n return extension === \".tsx\"\n ? \"tsx\"\n : [\".ts\", \".mts\", \".cts\"].includes(extension)\n ? \"ts\"\n : \"jsx\";\n};\n\nfunction archivedAsset(root, file) {\n const relative = path.relative(root, file).split(path.sep);\n return relative[0] === \"assets\"\n ? { path: relative.slice(1).join(\"/\"), bundled: false }\n : {\n path: relative.map((part) => (part === \"..\" ? \"__\" : part)).join(\"/\"),\n bundled: true,\n };\n}\n\nfunction assetVariants(resolved) {\n const directory = path.dirname(resolved);\n const extension = path.extname(resolved);\n const stem = path\n .basename(resolved, extension)\n .replace(/(\\.(ios|native))$/, \"\")\n .replace(/@[\\d.]+x$/, \"\");\n const pattern = new RegExp(\n `^${escape(stem)}(?:@([\\\\d.]+)x)?(?:\\\\.(ios|native))?${escape(extension)}$`,\n );\n const scales = new Map();\n for (const name of fs.readdirSync(directory)) {\n const match = pattern.exec(name);\n if (match === null) {\n continue;\n }\n const scale = match[1] === undefined ? 1 : Number(match[1]);\n const rank = platformRank[match[2]] ?? 0;\n if (Number.isFinite(scale) && (scales.get(scale)?.rank ?? -1) < rank) {\n scales.set(scale, { rank, file: path.join(directory, name) });\n }\n }\n return [...scales]\n .sort(([a], [b]) => a - b)\n .map(([scale, { file }]) => ({ scale, file }));\n}\n\nfunction assetModule(root, variants, assets) {\n const [first] = variants;\n const extension = path.extname(first.file).slice(1);\n const size = imageExtensions.has(extension)\n ? imageSize(fs.readFileSync(first.file))\n : undefined;\n const files = variants.map(({ scale, file }) => {\n const archived = archivedAsset(root, file);\n if (archived.bundled) {\n assets.set(archived.path, file);\n }\n return [scale, archived.path];\n });\n return `const { PixelRatio } = require(\"react-native\");\nconst { assets } = require(\"@swipt/api/file-system\");\nconst files = ${JSON.stringify(files)};\nconst ratio = PixelRatio.get();\nconst [scale, file] = files.find(([scale]) => scale >= ratio) ?? files[files.length - 1];\nmodule.exports = { uri: assets.file(file).uri, scale${size ? `, width: ${size.width / first.scale}, height: ${size.height / first.scale}` : \"\"} };\n`;\n}\n\nfunction checkWorklets(root) {\n let plugin;\n try {\n plugin = require.resolve(\"react-native-worklets/plugin\", { paths: [root] });\n } catch {\n return;\n }\n const { version } = JSON.parse(\n fs.readFileSync(\n path.join(path.dirname(plugin), \"..\", \"package.json\"),\n \"utf8\",\n ),\n );\n const { version: expected } = require(\"react-native-worklets/package.json\");\n if (version !== expected) {\n throw new Error(\n tr(\n \"The project has react-native-worklets {version}, but Swipt runs {expected}; install react-native-worklets@{expected} or remove it.\",\n { version, expected },\n ),\n );\n }\n}\n\ninterface MetroOptions {\n assets?: Map<string, string>;\n sourcemap?: boolean;\n}\n\nexport function metro(root, { assets, sourcemap }: MetroOptions) {\n checkWorklets(root);\n const configName = babelConfigNames.find((name) =>\n fs.existsSync(path.join(root, name)),\n );\n const babel = {\n cwd: root,\n root,\n babelrc: false,\n configFile: false,\n sourceType: \"unambiguous\",\n envName: \"production\",\n compact: false,\n retainLines: true,\n sourceMaps: sourcemap ? \"inline\" : false,\n ...(configName\n ? { extends: path.join(root, configName) }\n : { presets: [defaultPreset(root)] }),\n plugins: [requireContext],\n };\n const caller = {\n name: \"metro\",\n bundler: \"metro\",\n platform: \"ios\",\n engine: \"hermes\",\n isDev: false,\n isServer: false,\n isReactServer: false,\n baseUrl: \"\",\n routerRoot: \"app\",\n projectRoot: root,\n isHMREnabled: true,\n metroSourceType: \"module\",\n supportsStaticESM: true,\n };\n const internal = Symbol(\"internal\");\n return {\n name: \"swiplet-metro\",\n setup(build) {\n build.onResolve({ filter: /^@babel\\/runtime\\// }, async (args) => {\n if (args.pluginData === internal) {\n return undefined;\n }\n const options = {\n kind: args.kind,\n importer: args.importer,\n pluginData: internal,\n };\n const found = await build.resolve(args.path, {\n ...options,\n resolveDir: args.resolveDir,\n });\n return found.errors.length === 0\n ? found\n : build.resolve(args.path, { ...options, resolveDir: cliDirectory });\n });\n if (assets) {\n build.onResolve(\n { filter: new RegExp(`\\\\.(${assetExtensions.join(\"|\")})$`) },\n async (args) => {\n if (args.pluginData === internal) {\n return undefined;\n }\n const extension = path.extname(args.path);\n const stem = args.path.slice(0, -extension.length);\n let first;\n for (const scale of scaleSuffixes) {\n for (const platform of platformSuffixes) {\n const found = await build.resolve(\n `${stem}${scale}${platform}${extension}`,\n {\n kind: args.kind,\n importer: args.importer,\n resolveDir: args.resolveDir,\n pluginData: internal,\n },\n );\n if (found.errors.length === 0) {\n return {\n path: found.path,\n namespace: \"swiplet-asset\",\n pluginData: assetVariants(found.path),\n };\n }\n first ??= found;\n }\n }\n return { errors: first.errors };\n },\n );\n build.onLoad({ filter: /.*/, namespace: \"swiplet-asset\" }, (args) => ({\n contents: assetModule(root, args.pluginData, assets),\n loader: \"js\",\n resolveDir: root,\n }));\n }\n build.onLoad(\n { filter: /\\.[cm]?[jt]sx?$/, namespace: \"file\" },\n async (args) => {\n const result = await transformAsync(\n await fs.promises.readFile(args.path, \"utf8\"),\n {\n ...babel,\n filename: args.path,\n caller: {\n ...caller,\n isNodeModule: args.path.includes(\"node_modules\"),\n },\n },\n );\n return result === null\n ? undefined\n : {\n contents: result.code,\n loader: loaderOf(args.path),\n resolveDir: path.dirname(args.path),\n };\n },\n );\n },\n };\n}\n"],"mappings":";;;;;;;;;AAWA,MAAM,UAAU,cAAc,YAAY,GAAG;AAC7C,MAAM,eAAe,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC;AAEhE,MAAM,mBAAmB;CAAC;CAAM;CAAO;CAAQ;CAAM;CAAO;CAAO;AAAK;AACxE,MAAM,kBAAkB;CACtB;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;CACA;AACF;AACA,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,eAAe;CAAC;CAAQ;CAAS;CAAQ;AAAW;AAC1D,MAAM,gBAAgB;CAAC;CAAI;CAAO;CAAS;CAAO;CAAO;AAAK;AAC9D,MAAM,mBAAmB;CAAC;CAAI;CAAQ;AAAS;AAC/C,MAAM,eAAe;CAAE,KAAK;CAAG,QAAQ;AAAE;AAEzC,MAAM,SAAS,SAAS,KAAK,MAAM,KAAK,GAAG,CAAC,CAAC,KAAK,GAAG;AACrD,MAAM,UAAU,SAAS,KAAK,QAAQ,uBAAuB,MAAM;AAEnE,SAAgB,gB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MAAM,OAAO,KAAK,KAAK,MAAM,GAAG,CAAC,UAAU,MAAM;KACjD,IAAI;KACJ,KAAK,MAAM,SAAS,eAClB,KAAK,MAAM,YAAY,kBAAkB;MACvC,MAAM,QAAQ,MAAM,MAAM,QACxB,GAAG,OAAO,QAAQ,WAAW,aAC7B;OACE,MAAM,KAAK;OACX,UAAU,KAAK;OACf,YAAY,KAAK;OACjB,YAAY;MACd,CACF;MACA,IAAI,MAAM,OAAO,WAAW,GAC1B,OAAO;OACL,MAAM,MAAM;OACZ,WAAW;OACX,YAAY,cAAc,MAAM,IAAI;MACtC;MAEF,UAAU;KACZ;KAEF,OAAO,EAAE,QAAQ,MAAM,OAAO;IAChC,CACF;IACA,MAAM,OAAO;KAAE,QAAQ;KAAM,WAAW;IAAgB,IAAI,UAAU;KACpE,UAAU,YAAY,MAAM,KAAK,YAAY,MAAM;KACnD,QAAQ;KACR,YAAY;IACd,EAAE;GACJ;GACA,MAAM,OACJ;IAAE,QAAQ;IAAmB,WAAW;GAAO,GAC/C,OAAO,SAAS;IACd,MAAM,SAAS,MAAM,eACnB,MAAM,GAAG,SAAS,SAAS,KAAK,MAAM,MAAM,GAC5C;KACE,GAAG;KACH,UAAU,KAAK;KACf,QAAQ;MACN,GAAG;MACH,cAAc,KAAK,KAAK,SAAS,cAAc;KACjD;IACF,CACF;IACA,OAAO,WAAW,OACd,KAAA,IACA;KACE,UAAU,OAAO;KACjB,QAAQ,SAAS,KAAK,IAAI;KAC1B,YAAY,KAAK,QAAQ,KAAK,IAAI;IACpC;GACN,CACF;EACF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"metro.js","names":[],"sources":["../src/metro.ts"],"sourcesContent":["import fs from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport {\n type NodePath,\n type PluginObj,\n type TransformCaller,\n type TransformOptions,\n template,\n transformAsync,\n types,\n} from \"@babel/core\";\nimport { loadProjectEnv } from \"@expo/env\";\nimport type { Plugin, ResolveResult } from \"esbuild\";\nimport { imageSize } from \"image-size\";\n\nimport { t } from \"./i18n\";\n\ndeclare module \"@babel/core\" {\n interface TransformCaller {\n bundler?: string;\n platform?: string;\n engine?: string;\n isDev?: boolean;\n isServer?: boolean;\n isReactServer?: boolean;\n baseUrl?: string;\n routerRoot?: string;\n projectRoot?: string;\n isHMREnabled?: boolean;\n metroSourceType?: \"script\" | \"module\" | \"asset\";\n isNodeModule?: boolean;\n }\n}\n\nconst require = createRequire(import.meta.url);\nconst cliDirectory = path.dirname(fileURLToPath(import.meta.url));\n\nconst sourceExtensions = [\"js\", \"jsx\", \"json\", \"ts\", \"tsx\", \"cjs\", \"mjs\"];\nconst assetExtensions = [\n \"bmp\",\n \"gif\",\n \"jpg\",\n \"jpeg\",\n \"png\",\n \"psd\",\n \"svg\",\n \"webp\",\n \"xml\",\n \"m4v\",\n \"mov\",\n \"mp4\",\n \"mpeg\",\n \"mpg\",\n \"webm\",\n \"aac\",\n \"aiff\",\n \"caf\",\n \"m4a\",\n \"mp3\",\n \"wav\",\n \"html\",\n \"pdf\",\n \"yaml\",\n \"yml\",\n \"otf\",\n \"ttf\",\n \"zip\",\n \"db\",\n \"sqlite\",\n \"sqlite3\",\n];\nconst imageExtensions = new Set([\n \"png\",\n \"jpg\",\n \"jpeg\",\n \"bmp\",\n \"gif\",\n \"webp\",\n \"psd\",\n \"svg\",\n \"tiff\",\n \"ktx\",\n]);\nconst babelConfigNames = [\n \".babelrc\",\n \".babelrc.js\",\n \".babelrc.cjs\",\n \".babelrc.mjs\",\n \".babelrc.json\",\n \".babelrc.cts\",\n \"babel.config.js\",\n \"babel.config.cjs\",\n \"babel.config.mjs\",\n \"babel.config.json\",\n \"babel.config.cts\",\n \"babel.config.ts\",\n \"babel.config.mts\",\n];\nconst contextModes = [\"sync\", \"eager\", \"lazy\", \"lazy-once\"];\nconst scaleSuffixes = [\"\", \"@1x\", \"@1.5x\", \"@2x\", \"@3x\", \"@4x\"];\nconst platformSuffixes = [\"\", \".ios\", \".native\"];\nconst platformRank = new Map([\n [\"ios\", 2],\n [\"native\", 1],\n]);\n\nconst posix = (file: string) => file.split(path.sep).join(\"/\");\nconst escape = (text: string) => text.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\nexport function loadEnvironment(root: string) {\n loadProjectEnv(root, { mode: \"production\", silent: true });\n process.env.BABEL_ENV ??= \"production\";\n}\n\nfunction defaultPreset(root: string) {\n try {\n return createRequire(path.join(root, \"package.json\")).resolve(\n \"expo/internal/babel-preset\",\n );\n } catch {\n return require.resolve(\"babel-preset-expo\");\n }\n}\n\nfunction contextFiles(directory: string, recursive: boolean) {\n if (!fs.existsSync(directory)) {\n return [];\n }\n const extensions = new Set([...sourceExtensions, ...assetExtensions]);\n return fs\n .readdirSync(directory, { encoding: \"utf8\", recursive })\n .map(posix)\n .filter(\n (file) =>\n extensions.has(path.extname(file).slice(1)) &&\n fs.statSync(path.join(directory, file)).isFile(),\n )\n .sort();\n}\n\nfunction contextArgument<T>(\n call: NodePath<types.CallExpression>,\n index: number,\n fallback: T | undefined,\n expected: string,\n check: (value: unknown) => value is T,\n): T {\n if (call.node.arguments[index] === undefined) {\n if (fallback !== undefined) {\n return fallback;\n }\n } else {\n const { confident, value } = call.get(\"arguments\")[index].evaluate();\n if (confident && check(value)) {\n return value;\n }\n }\n throw call.buildCodeFrameError(\n t(\"metro.contextArgument\", {\n index: index + 1,\n expected,\n }),\n );\n}\n\nfunction contextPattern(call: NodePath<types.CallExpression>, index: number) {\n const node = call.node.arguments[index];\n if (node === undefined) {\n return /^\\.\\/.*$/;\n }\n if (!types.isRegExpLiteral(node)) {\n throw call.buildCodeFrameError(\n t(\"metro.contextRegExp\", { index: index + 1 }),\n );\n }\n return new RegExp(node.pattern, node.flags.replace(/[gy]/g, \"\"));\n}\n\nconst requireContext: PluginObj = {\n name: \"swipt-require-context\",\n visitor: {\n CallExpression(call, state) {\n const { callee } = call.node;\n if (\n state.filename === undefined ||\n !types.isMemberExpression(callee) ||\n !types.isIdentifier(callee.object, { name: \"require\" }) ||\n call.scope.hasBinding(\"require\") ||\n !(callee.computed\n ? types.isStringLiteral(callee.property, { value: \"context\" })\n : types.isIdentifier(callee.property, { name: \"context\" }))\n ) {\n return;\n }\n const from = path.dirname(state.filename);\n const directory = path.resolve(\n from,\n contextArgument(\n call,\n 0,\n undefined,\n t(\"metro.string\"),\n (value) => typeof value === \"string\",\n ),\n );\n const recursive = contextArgument(\n call,\n 1,\n true,\n t(\"metro.boolean\"),\n (value) => typeof value === \"boolean\",\n );\n const filter = contextPattern(call, 2);\n const mode = contextArgument(\n call,\n 3,\n \"sync\",\n t(\"metro.oneOf\", { values: contextModes.join(\", \") }),\n (value): value is string =>\n typeof value === \"string\" && contextModes.includes(value),\n );\n const entries = contextFiles(directory, recursive)\n .map((file) => `./${file}`)\n .filter((key) => filter.test(key))\n .map((key) => {\n const target = posix(path.relative(from, path.join(directory, key)));\n return `${JSON.stringify(key)}: () => require(${JSON.stringify(target.startsWith(\".\") ? target : `./${target}`)})`;\n });\n call.replaceWith(\n template.expression.ast(`(() => {\n const modules = { ${entries.join(\", \")} };\n const context = key => {\n if (!Object.prototype.hasOwnProperty.call(modules, key)) {\n throw Object.assign(new Error(\"Cannot find module '\" + key + \"'\"), { code: \"MODULE_NOT_FOUND\" });\n }\n return ${mode === \"sync\" ? \"modules[key]()\" : \"Promise.resolve().then(modules[key])\"};\n };\n context.keys = () => Object.keys(modules);\n context.resolve = key => key;\n context.id = ${JSON.stringify(posix(path.relative(state.cwd, directory)) || \".\")};\n return context;\n })()`),\n );\n },\n },\n};\n\nconst loaderOf = (file: string) => {\n const extension = path.extname(file);\n return extension === \".tsx\"\n ? \"tsx\"\n : [\".ts\", \".mts\", \".cts\"].includes(extension)\n ? \"ts\"\n : \"jsx\";\n};\n\nfunction archivedAsset(root: string, file: string) {\n const relative = path.relative(root, file).split(path.sep);\n return relative[0] === \"assets\"\n ? { path: relative.slice(1).join(\"/\"), bundled: false }\n : {\n path: relative.map((part) => (part === \"..\" ? \"__\" : part)).join(\"/\"),\n bundled: true,\n };\n}\n\ninterface AssetVariant {\n scale: number;\n file: string;\n}\n\nfunction assetVariants(resolved: string): AssetVariant[] {\n const directory = path.dirname(resolved);\n const extension = path.extname(resolved);\n const stem = path\n .basename(resolved, extension)\n .replace(/(\\.(ios|native))$/, \"\")\n .replace(/@[\\d.]+x$/, \"\");\n const pattern = new RegExp(\n `^${escape(stem)}(?:@([\\\\d.]+)x)?(?:\\\\.(ios|native))?${escape(extension)}$`,\n );\n const scales = new Map<number, { rank: number; file: string }>();\n for (const name of fs.readdirSync(directory)) {\n const match = pattern.exec(name);\n if (match === null) {\n continue;\n }\n const scale = match[1] === undefined ? 1 : Number(match[1]);\n const rank = platformRank.get(match[2]) ?? 0;\n if (Number.isFinite(scale) && (scales.get(scale)?.rank ?? -1) < rank) {\n scales.set(scale, { rank, file: path.join(directory, name) });\n }\n }\n return [...scales]\n .sort(([a], [b]) => a - b)\n .map(([scale, { file }]) => ({ scale, file }));\n}\n\nfunction assetModule(\n root: string,\n variants: AssetVariant[],\n assets: Map<string, string>,\n) {\n const [first] = variants;\n const extension = path.extname(first.file).slice(1);\n const size = imageExtensions.has(extension)\n ? imageSize(fs.readFileSync(first.file))\n : undefined;\n const files = variants.map(({ scale, file }) => {\n const archived = archivedAsset(root, file);\n if (archived.bundled) {\n assets.set(archived.path, file);\n }\n return [scale, archived.path];\n });\n return `const { PixelRatio } = require(\"react-native\");\nconst { assets } = require(\"@swipt/api/file-system\");\nconst files = ${JSON.stringify(files)};\nconst ratio = PixelRatio.get();\nconst [scale, file] = files.find(([scale]) => scale >= ratio) ?? files[files.length - 1];\nmodule.exports = { uri: assets.file(file).uri, scale${size ? `, width: ${size.width / first.scale}, height: ${size.height / first.scale}` : \"\"} };\n`;\n}\n\nfunction checkWorklets(root: string) {\n let plugin;\n try {\n plugin = require.resolve(\"react-native-worklets/plugin\", { paths: [root] });\n } catch {\n return;\n }\n const { version } = JSON.parse(\n fs.readFileSync(\n path.join(path.dirname(plugin), \"..\", \"package.json\"),\n \"utf8\",\n ),\n );\n const { version: expected } = require(\"react-native-worklets/package.json\");\n if (version !== expected) {\n throw new Error(t(\"metro.workletsMismatch\", { version, expected }));\n }\n}\n\ninterface MetroOptions {\n assets?: Map<string, string>;\n sourcemap?: boolean;\n}\n\nexport function metro(\n root: string,\n { assets, sourcemap }: MetroOptions,\n): Plugin {\n checkWorklets(root);\n const configName = babelConfigNames.find((name) =>\n fs.existsSync(path.join(root, name)),\n );\n const babel: TransformOptions = {\n cwd: root,\n root,\n babelrc: false,\n configFile: false,\n sourceType: \"unambiguous\",\n envName: \"production\",\n compact: false,\n retainLines: true,\n sourceMaps: sourcemap ? \"inline\" : false,\n ...(configName\n ? { extends: path.join(root, configName) }\n : { presets: [defaultPreset(root)] }),\n plugins: [requireContext],\n };\n const caller: TransformCaller = {\n name: \"metro\",\n bundler: \"metro\",\n platform: \"ios\",\n engine: \"hermes\",\n isDev: false,\n isServer: false,\n isReactServer: false,\n baseUrl: \"\",\n routerRoot: \"app\",\n projectRoot: root,\n isHMREnabled: true,\n metroSourceType: \"module\",\n supportsStaticESM: true,\n };\n const internal = Symbol(\"internal\");\n return {\n name: \"swiplet-metro\",\n setup(build) {\n build.onResolve({ filter: /^@babel\\/runtime\\// }, async (args) => {\n if (args.pluginData === internal) {\n return undefined;\n }\n const options = {\n kind: args.kind,\n importer: args.importer,\n pluginData: internal,\n };\n const found = await build.resolve(args.path, {\n ...options,\n resolveDir: args.resolveDir,\n });\n return found.errors.length === 0\n ? found\n : build.resolve(args.path, { ...options, resolveDir: cliDirectory });\n });\n if (assets) {\n build.onResolve(\n { filter: new RegExp(`\\\\.(${assetExtensions.join(\"|\")})$`) },\n async (args) => {\n if (args.pluginData === internal) {\n return undefined;\n }\n const extension = path.extname(args.path);\n const stem = args.path.slice(0, -extension.length);\n let first: ResolveResult | undefined;\n for (const scale of scaleSuffixes) {\n for (const platform of platformSuffixes) {\n const found = await build.resolve(\n `${stem}${scale}${platform}${extension}`,\n {\n kind: args.kind,\n importer: args.importer,\n resolveDir: args.resolveDir,\n pluginData: internal,\n },\n );\n if (found.errors.length === 0) {\n return {\n path: found.path,\n namespace: \"swiplet-asset\",\n pluginData: assetVariants(found.path),\n };\n }\n first ??= found;\n }\n }\n return { errors: first?.errors };\n },\n );\n build.onLoad({ filter: /.*/, namespace: \"swiplet-asset\" }, (args) => ({\n contents: assetModule(root, args.pluginData, assets),\n loader: \"js\",\n resolveDir: root,\n }));\n }\n build.onLoad(\n { filter: /\\.[cm]?[jt]sx?$/, namespace: \"file\" },\n async (args) => {\n const result = await transformAsync(\n await fs.promises.readFile(args.path, \"utf8\"),\n {\n ...babel,\n filename: args.path,\n caller: {\n ...caller,\n isNodeModule: args.path.includes(\"node_modules\"),\n },\n },\n );\n const code = result?.code;\n return typeof code === \"string\"\n ? {\n contents: code,\n loader: loaderOf(args.path),\n resolveDir: path.dirname(args.path),\n }\n : undefined;\n },\n );\n },\n };\n}\n"],"mappings":";;;;;;;;;AAqCA,MAAM,UAAU,cAAc,YAAY,GAAG;AAC7C,MAAM,eAAe,KAAK,QAAQ,cAAc,YAAY,GAAG,CAAC;AAEhE,MAAM,mBAAmB;CAAC;CAAM;CAAO;CAAQ;CAAM;CAAO;CAAO;AAAK;AACxE,MAAM,kBAAkB;CACtB;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;CACA;AACF;AACA,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AACD,MAAM,mBAAmB;CACvB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AACA,MAAM,eAAe;CAAC;CAAQ;CAAS;C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EACqB;IACrB,OAAO,OAAO,SAAS,WACnB;KACE,UAAU;KACV,QAAQ,SAAS,KAAK,IAAI;KAC1B,YAAY,KAAK,QAAQ,KAAK,IAAI;IACpC,IACA,KAAA;GACN,CACF;EACF;CACF;AACF"}
|
package/dist/output.d.ts
CHANGED
|
@@ -1,20 +1,35 @@
|
|
|
1
|
+
import { LogEntry, ScriptError } from "./proto/common_pb.js";
|
|
2
|
+
import { ServiceState, ServiceStatus } from "./proto/swiplets_pb.js";
|
|
3
|
+
import { Timestamp } from "@bufbuild/protobuf/wkt";
|
|
1
4
|
export declare class FalseResult extends Error {}
|
|
5
|
+
export declare const errorMessage: (error: unknown) => string;
|
|
2
6
|
export declare const selectTheme: {
|
|
3
7
|
style: {
|
|
4
8
|
keysHelpTip: () => string;
|
|
5
9
|
};
|
|
6
10
|
};
|
|
7
|
-
export
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
export declare
|
|
15
|
-
export declare
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
export declare function
|
|
11
|
+
export interface PromptContext {
|
|
12
|
+
options: {
|
|
13
|
+
device?: string;
|
|
14
|
+
team?: string;
|
|
15
|
+
};
|
|
16
|
+
signal: AbortSignal;
|
|
17
|
+
}
|
|
18
|
+
export declare const interactive: (context: Pick<PromptContext, "options">) => boolean;
|
|
19
|
+
export declare function choose<Value>(context: PromptContext, message: string, choices: {
|
|
20
|
+
name: string;
|
|
21
|
+
short?: string;
|
|
22
|
+
value: Value;
|
|
23
|
+
}[], failure: Error): Promise<Value>;
|
|
24
|
+
export declare function step<Result>(label: string, run: (detail: (text: string) => void) => Result | Promise<Result>, { transient }?: {
|
|
25
|
+
transient?: boolean | undefined;
|
|
26
|
+
}): Promise<Result>;
|
|
27
|
+
export declare function clockTime(timestamp: Timestamp | undefined): string;
|
|
28
|
+
export declare function dateTime(timestamp: Timestamp | undefined): string;
|
|
29
|
+
export declare function columns(rows: string[][]): string;
|
|
30
|
+
export declare const failureText: (failure: ScriptError) => string;
|
|
31
|
+
export declare function printScriptError(failure: ScriptError): FalseResult;
|
|
32
|
+
export declare function printLog(entry: LogEntry, toStdout: boolean): void;
|
|
33
|
+
export declare const serviceEnabledText: (enabled: boolean | undefined) => "turned off" | "turned on";
|
|
34
|
+
export declare const serviceStatusText: (status: ServiceStatus) => "failed" | "running" | "starting" | "stopped";
|
|
35
|
+
export declare function serviceText(state: ServiceState | undefined): string;
|
package/dist/output.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { t } from "./i18n.js";
|
|
2
2
|
import { LogLevelSchema } from "./proto/common_pb.js";
|
|
3
3
|
import "./proto/swiplets_pb.js";
|
|
4
4
|
import { timestampDate } from "@bufbuild/protobuf/wkt";
|
|
@@ -7,7 +7,8 @@ import select from "@inquirer/select";
|
|
|
7
7
|
import stringWidth from "string-width";
|
|
8
8
|
// src/output.ts
|
|
9
9
|
var FalseResult = class extends Error {};
|
|
10
|
-
const
|
|
10
|
+
const errorMessage = (error) => error instanceof Error ? error.message : String(error);
|
|
11
|
+
const selectTheme = { style: { keysHelpTip: () => [[`↑↓`, t("output.navigate")], [`⏎`, t("output.select")]].map(([key, action]) => `${styleText("bold", key)} ${styleText("dim", action)}`).join(styleText("dim", " • ")) } };
|
|
11
12
|
const interactive = (context) => context.options.device === void 0 && context.options.team === void 0 && process.stdin.isTTY && process.stderr.isTTY;
|
|
12
13
|
function choose(context, message, choices, failure) {
|
|
13
14
|
if (!interactive(context)) throw failure;
|
|
@@ -60,12 +61,13 @@ async function step(label, run, { transient = false } = {}) {
|
|
|
60
61
|
}
|
|
61
62
|
const levelName = (level) => level === 0 ? "info" : LogLevelSchema.value[level].name.slice(10).toLowerCase();
|
|
62
63
|
const pad = (value, width) => String(value).padStart(width, "0");
|
|
64
|
+
const dateOf = (timestamp) => timestamp ? timestampDate(timestamp) : /* @__PURE__ */ new Date(0);
|
|
63
65
|
function clockTime(timestamp) {
|
|
64
|
-
const at =
|
|
66
|
+
const at = dateOf(timestamp);
|
|
65
67
|
return `${pad(at.getHours(), 2)}:${pad(at.getMinutes(), 2)}:${pad(at.getSeconds(), 2)}.${pad(at.getMilliseconds(), 3)}`;
|
|
66
68
|
}
|
|
67
69
|
function dateTime(timestamp) {
|
|
68
|
-
const at =
|
|
70
|
+
const at = dateOf(timestamp);
|
|
69
71
|
return `${at.getFullYear()}-${pad(at.getMonth() + 1, 2)}-${pad(at.getDate(), 2)} ${pad(at.getHours(), 2)}:${pad(at.getMinutes(), 2)}:${pad(at.getSeconds(), 2)}`;
|
|
70
72
|
}
|
|
71
73
|
function columns(rows) {
|
|
@@ -81,7 +83,7 @@ const frameText = (frame) => {
|
|
|
81
83
|
};
|
|
82
84
|
const failureText = (failure) => [`${failure.name}: ${failure.message}`, ...failure.stack.map((frame) => ` at ${frameText(frame)}`)].join("\n");
|
|
83
85
|
function printScriptError(failure) {
|
|
84
|
-
console.error(
|
|
86
|
+
console.error(t("error", { message: failureText(failure) }));
|
|
85
87
|
return new FalseResult();
|
|
86
88
|
}
|
|
87
89
|
function printLog(entry, toStdout) {
|
|
@@ -89,28 +91,28 @@ function printLog(entry, toStdout) {
|
|
|
89
91
|
(toStdout ? console.log : console.error)(clockTime(entry.time), levelName(entry.level).toUpperCase(), message);
|
|
90
92
|
}
|
|
91
93
|
const serviceStatuses = {
|
|
92
|
-
[0]:
|
|
93
|
-
[1]:
|
|
94
|
-
[2]:
|
|
95
|
-
[3]:
|
|
96
|
-
[4]:
|
|
94
|
+
[0]: t("output.serviceStatus.stopped"),
|
|
95
|
+
[1]: t("output.serviceStatus.stopped"),
|
|
96
|
+
[2]: t("output.serviceStatus.starting"),
|
|
97
|
+
[3]: t("output.serviceStatus.running"),
|
|
98
|
+
[4]: t("output.serviceStatus.failed")
|
|
97
99
|
};
|
|
98
|
-
const serviceEnabledText = (enabled) => enabled ?
|
|
100
|
+
const serviceEnabledText = (enabled) => enabled ? t("output.serviceStatus.turnedOn") : t("output.serviceStatus.turnedOff");
|
|
99
101
|
const serviceStatusText = (status) => serviceStatuses[status];
|
|
100
|
-
function serviceText(
|
|
102
|
+
function serviceText(state) {
|
|
101
103
|
const enabled = serviceEnabledText(state?.enabled);
|
|
102
104
|
const status = serviceStatuses[state?.status ?? 0];
|
|
103
|
-
let text = state?.since ?
|
|
105
|
+
let text = state?.since ? t("output.serviceSince", {
|
|
104
106
|
enabled,
|
|
105
107
|
status,
|
|
106
108
|
time: clockTime(state.since)
|
|
107
|
-
}) :
|
|
109
|
+
}) : t("output.service", {
|
|
108
110
|
enabled,
|
|
109
111
|
status
|
|
110
112
|
});
|
|
111
113
|
if (state?.error) text += `: ${failureText(state.error)}`;
|
|
112
114
|
return text;
|
|
113
115
|
}
|
|
114
|
-
export { FalseResult, choose, clockTime, columns, dateTime, failureText, interactive, printLog, printScriptError, selectTheme, serviceEnabledText, serviceStatusText, serviceText, step };
|
|
116
|
+
export { FalseResult, choose, clockTime, columns, dateTime, errorMessage, failureText, interactive, printLog, printScriptError, selectTheme, serviceEnabledText, serviceStatusText, serviceText, step };
|
|
115
117
|
|
|
116
118
|
//# sourceMappingURL=output.js.map
|
package/dist/output.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output.js","names":[],"sources":["../src/output.ts"],"sourcesContent":["import { styleText } from \"node:util\";\n\nimport { timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport select from \"@inquirer/select\";\nimport stringWidth from \"string-width\";\n\nimport { tr } from \"./i18n\";\nimport { LogLevel, LogLevelSchema } from \"./proto/common_pb\";\nimport { ServiceStatus } from \"./proto/swiplets_pb\";\n\nexport class FalseResult extends Error {}\n\nexport const selectTheme = {\n style: {\n keysHelpTip: () =>\n [\n [`↑↓`, tr(\"navigate\")],\n [`⏎`, tr(\"select\")],\n ]\n .map(\n ([key, action]) =>\n `${styleText(\"bold\", key)} ${styleText(\"dim\", action)}`,\n )\n .join(styleText(\"dim\", \" • \")),\n },\n};\n\nexport const interactive = (context) =>\n context.options.device === undefined &&\n context.options.team === undefined &&\n process.stdin.isTTY &&\n process.stderr.isTTY;\n\nexport function choose(context, message, choices, failure) {\n if (!interactive(context)) {\n throw failure;\n }\n return select(\n { message, choices, theme: selectTheme },\n { output: process.stderr, signal: context.signal },\n );\n}\n\nconst spinner = \"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏\";\n\nexport async function step(label, run, { transient = false } = {}) {\n const stream = process.stderr;\n if (!stream.isTTY) {\n console.error(label);\n return run(() => {});\n }\n const style = (format, text) => styleText(format, text, { stream });\n const started = Date.now();\n const elapsed = () => {\n const seconds = Math.floor((Date.now() - started) / 1000);\n return seconds > 0 ? style(\"dim\", ` ${seconds}s`) : \"\";\n };\n const draw = (line) => stream.write(`\\r\\x1b[?7l\\x1b[2K${line}\\x1b[?7h`);\n let detail = \"\";\n let frame = 0;\n const render = () => {\n frame = (frame + 1) % spinner.length;\n draw(\n `${style(\"cyan\", spinner[frame])} ${label}${detail && style(\"dim\", ` ${detail}`)}${elapsed()}`,\n );\n };\n stream.write(\"\\x1b[?25l\");\n render();\n const timer = setInterval(render, 80);\n try {\n const result = await run((text) => {\n detail = text;\n });\n clearInterval(timer);\n draw(transient ? \"\" : `${style(\"green\", \"✔\")} ${label}${elapsed()}\\n`);\n return result;\n } catch (error) {\n clearInterval(timer);\n draw(`${style(\"red\", \"✖\")} ${label}${elapsed()}\\n`);\n throw error;\n } finally {\n stream.write(\"\\x1b[?25h\");\n }\n}\n\nconst levelName = (level) =>\n level === LogLevel.UNSPECIFIED\n ? \"info\"\n : LogLevelSchema.value[level].name.slice(\"LOG_LEVEL_\".length).toLowerCase();\n\nconst pad = (value, width) => String(value).padStart(width, \"0\");\n\nexport function clockTime(timestamp) {\n const at = timestampDate(timestamp);\n return `${pad(at.getHours(), 2)}:${pad(at.getMinutes(), 2)}:${pad(at.getSeconds(), 2)}.${pad(at.getMilliseconds(), 3)}`;\n}\n\nexport function dateTime(timestamp) {\n const at = timestampDate(timestamp);\n return `${at.getFullYear()}-${pad(at.getMonth() + 1, 2)}-${pad(at.getDate(), 2)} ${pad(at.getHours(), 2)}:${pad(at.getMinutes(), 2)}:${pad(at.getSeconds(), 2)}`;\n}\n\nexport function columns(rows) {\n const widths = [];\n for (const row of rows) {\n row.forEach((cell, index) => {\n widths[index] = Math.max(widths[index] ?? 0, stringWidth(cell));\n });\n }\n return rows\n .map((row) =>\n row\n .map((cell, index) =>\n index === row.length - 1\n ? cell\n : cell + \" \".repeat(widths[index] + 2 - stringWidth(cell)),\n )\n .join(\"\")\n .trimEnd(),\n )\n .join(\"\\n\");\n}\n\nconst frameText = (frame) => {\n const position = `${frame.file}:${frame.line}:${frame.column}`;\n return frame.function === \"\" ? position : `${frame.function} (${position})`;\n};\n\nexport const failureText = (failure) =>\n [\n `${failure.name}: ${failure.message}`,\n ...failure.stack.map((frame) => ` at ${frameText(frame)}`),\n ].join(\"\\n\");\n\nexport function printScriptError(failure) {\n console.error(tr(\"error: {message}\", { message: failureText(failure) }));\n return new FalseResult();\n}\n\nexport function printLog(entry, toStdout) {\n const message =\n entry.tag === \"\" ? entry.message : `${entry.tag}: ${entry.message}`;\n (toStdout ? console.log : console.error)(\n clockTime(entry.time),\n levelName(entry.level).toUpperCase(),\n message,\n );\n}\n\nconst serviceStatuses = {\n [ServiceStatus.UNSPECIFIED]: tr(\"stopped\", {}, \"service\"),\n [ServiceStatus.STOPPED]: tr(\"stopped\", {}, \"service\"),\n [ServiceStatus.STARTING]: tr(\"starting\", {}, \"service\"),\n [ServiceStatus.RUNNING]: tr(\"running\", {}, \"service\"),\n [ServiceStatus.FAILED]: tr(\"failed\", {}, \"service\"),\n};\n\nexport const serviceEnabledText = (enabled) =>\n enabled ? tr(\"turned on\", {}, \"service\") : tr(\"turned off\", {}, \"service\");\n\nexport const serviceStatusText = (status) => serviceStatuses[status];\n\nexport function serviceText(_id, state) {\n const enabled = serviceEnabledText(state?.enabled);\n const status = serviceStatuses[state?.status ?? ServiceStatus.UNSPECIFIED];\n let text = state?.since\n ? tr(\"{enabled}, {status} since {time}\", {\n enabled,\n status,\n time: clockTime(state.since),\n })\n : tr(\"{enabled}, {status}\", { enabled, status });\n if (state?.error) {\n text += `: ${failureText(state.error)}`;\n }\n return text;\n}\n"],"mappings":";;;;;;;;AAUA,IAAa,cAAb,cAAiC,MAAM,CAAC;AAExC,MAAa,cAAc,EACzB,OAAO,EACL,mBACE,CACE,CAAC,MAAM,GAAG,UAAU,CAAC,GACrB,CAAC,KAAK,GAAG,QAAQ,CAAC,CACpB,CAAC,CACE,KACE,CAAC,KAAK,YACL,GAAG,UAAU,QAAQ,GAAG,EAAE,GAAG,UAAU,OAAO,MAAM,GACxD,CAAC,CACA,KAAK,UAAU,OAAO,KAAK,CAAC,EACnC,EACF;AAEA,MAAa,eAAe,YAC1B,QAAQ,QAAQ,WAAW,KAAA,KAC3B,QAAQ,QAAQ,SAAS,KAAA,KACzB,QAAQ,MAAM,SACd,QAAQ,OAAO;AAEjB,SAAgB,OAAO,SAAS,SAAS,SAAS,SAAS;CACzD,IAAI,CAAC,YAAY,OAAO,GACtB,MAAM;CAER,OAAO,OACL;EAAE;EAAS;EAAS,OAAO;CAAY,GACvC;EAAE,QAAQ,QAAQ;EAAQ,QAAQ,QAAQ;CAAO,CACnD;AACF;AAEA,MAAM,UAAU;AAEhB,eAAsB,KAAK,OAAO,KAAK,EAAE,YAAY,UAAU,CAAC,GAAG;CACjE,MAAM,SAAS,QAAQ;CACvB,IAAI,CAAC,OAAO,OAAO;EACjB,QAAQ,MAAM,KAAK;EACnB,OAAO,UAAU,CAAC,CAAC;CACrB;CACA,MAAM,SAAS,QAAQ,SAAS,UAAU,QAAQ,MAAM,EAAE,OAAO,CAAC;CAClE,MAAM,UAAU,KAAK,IAAI;CACzB,MAAM,gBAAgB;EACpB,MAAM,UAAU,KAAK,OAAO,KAAK,IAAI,IAAI,WAAW,G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Q,MAAM,QAAQ,MAAA,CAChC,UAAU,MAAM,IAAI,GACpB,UAAU,MAAM,KAAK,CAAC,CAAC,YAAY,GACnC,OACF;AACF;AAEA,MAAM,kBAAkB;EACO,IAAA,GAAG,WAAW,CAAC,GAAG,SAAS;EAC/B,IAAA,GAAG,WAAW,CAAC,GAAG,SAAS;EAC1B,IAAA,GAAG,YAAY,CAAC,GAAG,SAAS;EAC7B,IAAA,GAAG,WAAW,CAAC,GAAG,SAAS;EAC5B,IAAA,GAAG,UAAU,CAAC,GAAG,SAAS;AACpD;AAEA,MAAa,sBAAsB,YACjC,UAAU,GAAG,aAAa,CAAC,GAAG,SAAS,IAAI,GAAG,cAAc,CAAC,GAAG,SAAS;AAE3E,MAAa,qBAAqB,WAAW,gBAAgB;AAE7D,SAAgB,YAAY,KAAK,OAAO;CACtC,MAAM,UAAU,mBAAmB,OAAO,OAAO;CACjD,MAAM,SAAS,gBAAgB,OAAO,UAAA;CACtC,IAAI,OAAO,OAAO,QACd,GAAG,oCAAoC;EACrC;EACA;EACA,MAAM,UAAU,MAAM,KAAK;CAC7B,CAAC,IACD,GAAG,uBAAuB;EAAE;EAAS;CAAO,CAAC;CACjD,IAAI,OAAO,OACT,QAAQ,KAAK,YAAY,MAAM,KAAK;CAEtC,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"output.js","names":[],"sources":["../src/output.ts"],"sourcesContent":["import { styleText } from \"node:util\";\n\nimport { type Timestamp, timestampDate } from \"@bufbuild/protobuf/wkt\";\nimport select from \"@inquirer/select\";\nimport stringWidth from \"string-width\";\n\nimport { t } from \"./i18n\";\nimport {\n type LogEntry,\n LogLevel,\n LogLevelSchema,\n type ScriptError,\n type StackFrame,\n} from \"./proto/common_pb\";\nimport { type ServiceState, ServiceStatus } from \"./proto/swiplets_pb\";\n\nexport class FalseResult extends Error {}\n\nexport const errorMessage = (error: unknown) =>\n error instanceof Error ? error.message : String(error);\n\nexport const selectTheme = {\n style: {\n keysHelpTip: () =>\n [\n [`↑↓`, t(\"output.navigate\")],\n [`⏎`, t(\"output.select\")],\n ]\n .map(\n ([key, action]) =>\n `${styleText(\"bold\", key)} ${styleText(\"dim\", action)}`,\n )\n .join(styleText(\"dim\", \" • \")),\n },\n};\n\nexport interface PromptContext {\n options: { device?: string; team?: string };\n signal: AbortSignal;\n}\n\nexport const interactive = (context: Pick<PromptContext, \"options\">) =>\n context.options.device === undefined &&\n context.options.team === undefined &&\n process.stdin.isTTY &&\n process.stderr.isTTY;\n\nexport function choose<Value>(\n context: PromptContext,\n message: string,\n choices: { name: string; short?: string; value: Value }[],\n failure: Error,\n) {\n if (!interactive(context)) {\n throw failure;\n }\n return select(\n { message, choices, theme: selectTheme },\n { output: process.stderr, signal: context.signal },\n );\n}\n\nconst spinner = \"⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏\";\n\nexport async function step<Result>(\n label: string,\n run: (detail: (text: string) => void) => Result | Promise<Result>,\n { transient = false } = {},\n) {\n const stream = process.stderr;\n if (!stream.isTTY) {\n console.error(label);\n return run(() => {});\n }\n const style = (format: Parameters<typeof styleText>[0], text: string) =>\n styleText(format, text, { stream });\n const started = Date.now();\n const elapsed = () => {\n const seconds = Math.floor((Date.now() - started) / 1000);\n return seconds > 0 ? style(\"dim\", ` ${seconds}s`) : \"\";\n };\n const draw = (line: string) =>\n stream.write(`\\r\\x1b[?7l\\x1b[2K${line}\\x1b[?7h`);\n let detail = \"\";\n let frame = 0;\n const render = () => {\n frame = (frame + 1) % spinner.length;\n draw(\n `${style(\"cyan\", spinner[frame])} ${label}${detail && style(\"dim\", ` ${detail}`)}${elapsed()}`,\n );\n };\n stream.write(\"\\x1b[?25l\");\n render();\n const timer = setInterval(render, 80);\n try {\n const result = await run((text) => {\n detail = text;\n });\n clearInterval(timer);\n draw(transient ? \"\" : `${style(\"green\", \"✔\")} ${label}${elapsed()}\\n`);\n return result;\n } catch (error) {\n clearInterval(timer);\n draw(`${style(\"red\", \"✖\")} ${label}${elapsed()}\\n`);\n throw error;\n } finally {\n stream.write(\"\\x1b[?25h\");\n }\n}\n\nconst levelName = (level: LogLevel) =>\n level === LogLevel.UNSPECIFIED\n ? \"info\"\n : LogLevelSchema.value[level].name.slice(\"LOG_LEVEL_\".length).toLowerCase();\n\nconst pad = (value: number, width: number) =>\n String(value).padStart(width, \"0\");\n\nconst dateOf = (timestamp: Timestamp | undefined) =>\n timestamp ? timestampDate(timestamp) : new Date(0);\n\nexport function clockTime(timestamp: Timestamp | undefined) {\n const at = dateOf(timestamp);\n return `${pad(at.getHours(), 2)}:${pad(at.getMinutes(), 2)}:${pad(at.getSeconds(), 2)}.${pad(at.getMilliseconds(), 3)}`;\n}\n\nexport function dateTime(timestamp: Timestamp | undefined) {\n const at = dateOf(timestamp);\n return `${at.getFullYear()}-${pad(at.getMonth() + 1, 2)}-${pad(at.getDate(), 2)} ${pad(at.getHours(), 2)}:${pad(at.getMinutes(), 2)}:${pad(at.getSeconds(), 2)}`;\n}\n\nexport function columns(rows: string[][]) {\n const widths: number[] = [];\n for (const row of rows) {\n row.forEach((cell, index) => {\n widths[index] = Math.max(widths[index] ?? 0, stringWidth(cell));\n });\n }\n return rows\n .map((row) =>\n row\n .map((cell, index) =>\n index === row.length - 1\n ? cell\n : cell + \" \".repeat(widths[index] + 2 - stringWidth(cell)),\n )\n .join(\"\")\n .trimEnd(),\n )\n .join(\"\\n\");\n}\n\nconst frameText = (frame: StackFrame) => {\n const position = `${frame.file}:${frame.line}:${frame.column}`;\n return frame.function === \"\" ? position : `${frame.function} (${position})`;\n};\n\nexport const failureText = (failure: ScriptError) =>\n [\n `${failure.name}: ${failure.message}`,\n ...failure.stack.map((frame) => ` at ${frameText(frame)}`),\n ].join(\"\\n\");\n\nexport function printScriptError(failure: ScriptError) {\n console.error(t(\"error\", { message: failureText(failure) }));\n return new FalseResult();\n}\n\nexport function printLog(entry: LogEntry, toStdout: boolean) {\n const message =\n entry.tag === \"\" ? entry.message : `${entry.tag}: ${entry.message}`;\n (toStdout ? console.log : console.error)(\n clockTime(entry.time),\n levelName(entry.level).toUpperCase(),\n message,\n );\n}\n\nconst serviceStatuses = {\n [ServiceStatus.UNSPECIFIED]: t(\"output.serviceStatus.stopped\"),\n [ServiceStatus.STOPPED]: t(\"output.serviceStatus.stopped\"),\n [ServiceStatus.STARTING]: t(\"output.serviceStatus.starting\"),\n [ServiceStatus.RUNNING]: t(\"output.serviceStatus.running\"),\n [ServiceStatus.FAILED]: t(\"output.serviceStatus.failed\"),\n};\n\nexport const serviceEnabledText = (enabled: boolean | undefined) =>\n enabled\n ? t(\"output.serviceStatus.turnedOn\")\n : t(\"output.serviceStatus.turnedOff\");\n\nexport const serviceStatusText = (status: ServiceStatus) =>\n serviceStatuses[status];\n\nexport function serviceText(state: ServiceState | undefined) {\n const enabled = serviceEnabledText(state?.enabled);\n const status = serviceStatuses[state?.status ?? ServiceStatus.UNSPECIFIED];\n let text = state?.since\n ? t(\"output.serviceSince\", {\n enabled,\n status,\n time: clockTime(state.since),\n })\n : t(\"output.service\", { enabled, status });\n if (state?.error) {\n text += `: ${failureText(state.error)}`;\n }\n return text;\n}\n"],"mappings":";;;;;;;;AAgBA,IAAa,cAAb,cAAiC,MAAM,CAAC;AAExC,MAAa,gBAAgB,UAC3B,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAEvD,MAAa,cAAc,EACzB,OAAO,EACL,mBACE,CACE,CAAC,MAAM,EAAE,iBAAiB,CAAC,GAC3B,CAAC,KAAK,EAAE,eAAe,CAAC,CAC1B,CAAC,CACE,KACE,CAAC,KAAK,YACL,GAAG,UAAU,QAAQ,GAAG,EAAE,GAAG,UAAU,OAAO,MAAM,GACxD,CAAC,CACA,KAAK,UAAU,OAAO,KAAK,CAAC,EACnC,EACF;AAOA,MAAa,eAAe,YAC1B,QAAQ,QAAQ,WAAW,KAAA,KAC3B,QAAQ,QAAQ,SAAS,KAAA,KACzB,QAAQ,MAAM,SACd,QAAQ,OAAO;AAEjB,SAAgB,OACd,SACA,SACA,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AAO,OACT,QAAQ,KAAK,YAAY,MAAM,KAAK;CAEtC,OAAO;AACT"}
|
package/dist/passcode.d.ts
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
1
|
export declare const passcodeTypes: string[];
|
|
2
|
-
export
|
|
3
|
-
passcode:
|
|
4
|
-
type:
|
|
5
|
-
}
|
|
6
|
-
export
|
|
7
|
-
passcode
|
|
8
|
-
type
|
|
9
|
-
}
|
|
2
|
+
export interface Passcode {
|
|
3
|
+
passcode: string;
|
|
4
|
+
type: string;
|
|
5
|
+
}
|
|
6
|
+
export interface PasscodeOptions {
|
|
7
|
+
passcode?: string;
|
|
8
|
+
"passcode-type"?: string;
|
|
9
|
+
}
|
|
10
|
+
export declare function passcodeOf(options: PasscodeOptions): Passcode | undefined;
|
|
11
|
+
export declare function askPasscode(context: {
|
|
12
|
+
signal: AbortSignal;
|
|
13
|
+
}): Promise<Passcode | undefined>;
|
package/dist/passcode.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { UsageError } from "./client.js";
|
|
2
|
-
import {
|
|
3
|
-
import { selectTheme } from "./output.js";
|
|
2
|
+
import { t } from "./i18n.js";
|
|
3
|
+
import { errorMessage, selectTheme } from "./output.js";
|
|
4
4
|
import select from "@inquirer/select";
|
|
5
5
|
import password from "@inquirer/password";
|
|
6
6
|
// src/passcode.ts
|
|
@@ -11,16 +11,16 @@ const passcodeTypes = [
|
|
|
11
11
|
];
|
|
12
12
|
function passcodeOf(options) {
|
|
13
13
|
const type = options["passcode-type"] ?? "pin";
|
|
14
|
-
if (!passcodeTypes.includes(type)) throw new UsageError(
|
|
14
|
+
if (!passcodeTypes.includes(type)) throw new UsageError(t("passcode.invalidType", {
|
|
15
15
|
value: JSON.stringify(type),
|
|
16
16
|
types: passcodeTypes.join(", ")
|
|
17
17
|
}));
|
|
18
18
|
const passcode = options.passcode;
|
|
19
19
|
if (!passcode) return;
|
|
20
20
|
const digits = /^\d+$/.test(passcode);
|
|
21
|
-
if (type === "pin" && !(digits && [4, 6].includes(passcode.length))) throw new UsageError(
|
|
22
|
-
if (type === "numeric" && !digits) throw new UsageError(
|
|
23
|
-
if (!/^[\x20-\x7e]{1,64}$/.test(passcode)) throw new UsageError(
|
|
21
|
+
if (type === "pin" && !(digits && [4, 6].includes(passcode.length))) throw new UsageError(t("passcode.invalidPin"));
|
|
22
|
+
if (type === "numeric" && !digits) throw new UsageError(t("passcode.invalidNumeric"));
|
|
23
|
+
if (!/^[\x20-\x7e]{1,64}$/.test(passcode)) throw new UsageError(t("passcode.invalidAlphanumeric"));
|
|
24
24
|
return {
|
|
25
25
|
passcode,
|
|
26
26
|
type
|
|
@@ -28,26 +28,26 @@ function passcodeOf(options) {
|
|
|
28
28
|
}
|
|
29
29
|
async function askPasscode(context) {
|
|
30
30
|
const type = await select({
|
|
31
|
-
message:
|
|
31
|
+
message: t("passcode.setUp"),
|
|
32
32
|
theme: selectTheme,
|
|
33
33
|
choices: [
|
|
34
34
|
{
|
|
35
|
-
name:
|
|
36
|
-
short:
|
|
35
|
+
name: t("passcode.pin"),
|
|
36
|
+
short: t("passcode.pinDetail"),
|
|
37
37
|
value: "pin"
|
|
38
38
|
},
|
|
39
39
|
{
|
|
40
|
-
name:
|
|
41
|
-
short:
|
|
40
|
+
name: t("passcode.numeric"),
|
|
41
|
+
short: t("passcode.numericDetail"),
|
|
42
42
|
value: "numeric"
|
|
43
43
|
},
|
|
44
44
|
{
|
|
45
|
-
name:
|
|
46
|
-
short:
|
|
45
|
+
name: t("passcode.alphanumeric"),
|
|
46
|
+
short: t("passcode.alphanumericDetail"),
|
|
47
47
|
value: "alphanumeric"
|
|
48
48
|
},
|
|
49
49
|
{
|
|
50
|
-
name:
|
|
50
|
+
name: t("noThanks"),
|
|
51
51
|
value: null
|
|
52
52
|
}
|
|
53
53
|
]
|
|
@@ -61,14 +61,14 @@ async function askPasscode(context) {
|
|
|
61
61
|
"passcode-type": type
|
|
62
62
|
});
|
|
63
63
|
return passcodeOf(options(await password({
|
|
64
|
-
message:
|
|
65
|
-
theme: {
|
|
64
|
+
message: t("passcode.prompt"),
|
|
65
|
+
theme: { style: { maskedText: t("passcode.masked") } },
|
|
66
66
|
validate(passcode) {
|
|
67
67
|
try {
|
|
68
68
|
passcodeOf(options(passcode));
|
|
69
|
-
return passcode !== "" ||
|
|
69
|
+
return passcode !== "" || t("passcode.empty");
|
|
70
70
|
} catch (error) {
|
|
71
|
-
return error
|
|
71
|
+
return errorMessage(error);
|
|
72
72
|
}
|
|
73
73
|
}
|
|
74
74
|
}, {
|
package/dist/passcode.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"passcode.js","names":[],"sources":["../src/passcode.ts"],"sourcesContent":["import password from \"@inquirer/password\";\nimport select from \"@inquirer/select\";\n\nimport { UsageError } from \"./client\";\nimport {
|
|
1
|
+
{"version":3,"file":"passcode.js","names":[],"sources":["../src/passcode.ts"],"sourcesContent":["import password from \"@inquirer/password\";\nimport select from \"@inquirer/select\";\n\nimport { UsageError } from \"./client\";\nimport { t } from \"./i18n\";\nimport { errorMessage, selectTheme } from \"./output\";\n\nexport const passcodeTypes = [\"pin\", \"numeric\", \"alphanumeric\"];\n\nexport interface Passcode {\n passcode: string;\n type: string;\n}\n\nexport interface PasscodeOptions {\n passcode?: string;\n \"passcode-type\"?: string;\n}\n\nexport function passcodeOf(options: PasscodeOptions): Passcode | undefined {\n const type = options[\"passcode-type\"] ?? \"pin\";\n if (!passcodeTypes.includes(type)) {\n throw new UsageError(\n t(\"passcode.invalidType\", {\n value: JSON.stringify(type),\n types: passcodeTypes.join(\", \"),\n }),\n );\n }\n const passcode = options.passcode;\n if (!passcode) {\n return undefined;\n }\n const digits = /^\\d+$/.test(passcode);\n if (type === \"pin\" && !(digits && [4, 6].includes(passcode.length))) {\n throw new UsageError(t(\"passcode.invalidPin\"));\n }\n if (type === \"numeric\" && !digits) {\n throw new UsageError(t(\"passcode.invalidNumeric\"));\n }\n if (!/^[\\x20-\\x7e]{1,64}$/.test(passcode)) {\n throw new UsageError(t(\"passcode.invalidAlphanumeric\"));\n }\n return { passcode, type };\n}\n\nexport async function askPasscode(context: { signal: AbortSignal }) {\n const type = await select<string | null>(\n {\n message: t(\"passcode.setUp\"),\n theme: selectTheme,\n choices: [\n {\n name: t(\"passcode.pin\"),\n short: t(\"passcode.pinDetail\"),\n value: \"pin\",\n },\n {\n name: t(\"passcode.numeric\"),\n short: t(\"passcode.numericDetail\"),\n value: \"numeric\",\n },\n {\n name: t(\"passcode.alphanumeric\"),\n short: t(\"passcode.alphanumericDetail\"),\n value: \"alphanumeric\",\n },\n { name: t(\"noThanks\"), value: null },\n ],\n },\n { output: process.stderr, signal: context.signal },\n );\n if (type === null) {\n return undefined;\n }\n const options = (passcode: string) => ({ passcode, \"passcode-type\": type });\n return passcodeOf(\n options(\n await password(\n {\n message: t(\"passcode.prompt\"),\n theme: { style: { maskedText: t(\"passcode.masked\") } },\n validate(passcode) {\n try {\n passcodeOf(options(passcode));\n return passcode !== \"\" || t(\"passcode.empty\");\n } catch (error) {\n return errorMessage(error);\n }\n },\n },\n { output: process.stderr, signal: context.signal },\n ),\n ),\n );\n}\n"],"mappings":";;;;;;AAOA,MAAa,gBAAgB;CAAC;CAAO;CAAW;AAAc;AAY9D,SAAgB,WAAW,SAAgD;CACzE,MAAM,OAAO,QAAQ,oBAAoB;CACzC,IAAI,CAAC,cAAc,SAAS,IAAI,GAC9B,MAAM,IAAI,WACR,EAAE,wBAAwB;EACxB,OAAO,KAAK,UAAU,IAAI;EAC1B,OAAO,cAAc,KAAK,IAAI;CAChC,CAAC,CACH;CAEF,MAAM,WAAW,QAAQ;CACzB,IAAI,CAAC,UACH;CAEF,MAAM,SAAS,QAAQ,KAAK,QAAQ;CACpC,IAAI,SAAS,SAAS,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,SAAS,MAAM,IAC/D,MAAM,IAAI,WAAW,EAAE,qBAAqB,CAAC;CAE/C,IAAI,S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