@primate/python 0.6.0 → 0.8.0

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.
@@ -1,36 +1,55 @@
1
1
  import E from "#errors";
2
2
  import module from "#module";
3
- import log from "@primate/core/log";
4
3
  import server from "@primate/core/server";
5
4
  import assert from "@rcompat/assert";
6
5
  import fs from "@rcompat/fs";
7
6
  import io from "@rcompat/io";
8
7
  const PACKAGE = "primate-run";
9
8
  const [MAJOR, MINOR] = server.TAG.split(".").map(Number);
10
- async function show_package() {
11
- const str0 = () => "";
12
- let out = await io.run(`pip show ${PACKAGE} 2>/dev/null`).catch(str0);
13
- if (out.trim().length > 0)
9
+ async function show_package(app) {
10
+ function run(command) {
11
+ return io.run(command, { cwd: app.root.path })
12
+ .then(out => out.trim())
13
+ .catch(() => "");
14
+ }
15
+ let out = await run(`pip show ${PACKAGE} 2>/dev/null`);
16
+ if (out.length > 0)
14
17
  return out;
15
- out = await io.run(`uv pip show ${PACKAGE} 2>/dev/null`).catch(str0);
16
- if (out.trim().length > 0)
18
+ out = await run(`uv pip show ${PACKAGE} 2>/dev/null`);
19
+ if (out.length > 0)
17
20
  return out;
18
- out = await io.run(`python -m pip show ${PACKAGE} 2>/dev/null`).catch(str0);
19
- if (out.trim().length > 0)
21
+ out = await run(`python -m pip show ${PACKAGE} 2>/dev/null`);
22
+ if (out.length > 0)
20
23
  return out;
21
24
  return null;
22
25
  }
23
- async function check_version() {
24
- const output = await show_package();
26
+ async function check_version(app) {
27
+ const output = await show_package(app);
25
28
  if (output === null)
26
- throw E.package_not_found();
29
+ throw E.pkg_not_found();
27
30
  const version_match = output.match(/Version:\s*(\d+)\.(\d+)\.(\d+)/);
28
31
  if (version_match === null)
29
- throw E.package_not_found();
32
+ throw E.pkg_not_found();
30
33
  const [major, minor] = version_match.slice(1).map(Number);
31
34
  if (major !== MAJOR || minor !== MINOR)
32
- throw E.package_mismatch(major, minor);
33
- log.info("using {0} package {1}.{2}.x", PACKAGE, major, minor);
35
+ throw E.pkg_mismatch(major, minor);
36
+ app.log.info `using ${PACKAGE} package ${major}.${minor}.x`;
37
+ }
38
+ function wrap(source, id, packages_str, primate_run) {
39
+ return `
40
+ import route from "primate/route";
41
+ import wrapper from "@primate/python/wrapper";
42
+ import app from "$:app";
43
+ import session from "app:config:session";
44
+ const handlers = await wrapper(
45
+ ${JSON.stringify(source)},
46
+ ${packages_str},
47
+ ${JSON.stringify(primate_run)},
48
+ ${JSON.stringify(id)},
49
+ { i18n: app.i18n, session }
50
+ );
51
+ export default route(handlers);
52
+ `;
34
53
  }
35
54
  export default function default_module(input = {}) {
36
55
  const { extension = module.extension } = module.schema.parse(input);
@@ -38,7 +57,7 @@ export default function default_module(input = {}) {
38
57
  name: module.name,
39
58
  setup({ onBuild }) {
40
59
  onBuild(async (app) => {
41
- await check_version();
60
+ await check_version(app);
42
61
  const requirements_txt = app.root.join("requirements.txt");
43
62
  let packages = [];
44
63
  if (await requirements_txt.exists()) {
@@ -53,18 +72,7 @@ export default function default_module(input = {}) {
53
72
  assert.true(context === "routes", E.only_route_files());
54
73
  const relative = file.debase(app.path.routes).path.replace(/^\//, "");
55
74
  const source = await file.text();
56
- return `
57
- import wrapper from "@primate/python/wrapper";
58
- import i18n from "app:config:i18n";
59
- import session from "app:config:session";
60
- await wrapper(
61
- ${JSON.stringify(source)},
62
- ${packages_str},
63
- "${PACKAGE}~=${server.TAG}.0",
64
- "${relative}",
65
- { i18n, session }
66
- );
67
- `;
75
+ return wrap(source, relative, packages_str, `${PACKAGE}~=${server.TAG}.0`);
68
76
  });
69
77
  });
70
78
  },
@@ -1,10 +1,10 @@
1
1
  declare function only_route_files(): import("@rcompat/error").TemplateError;
2
- declare function package_not_found(): import("@rcompat/error").TemplateError;
3
- declare function package_mismatch(major: number, minor: number): import("@rcompat/error").TemplateError;
2
+ declare function pkg_not_found(): import("@rcompat/error").TemplateError;
3
+ declare function pkg_mismatch(major: number, minor: number): import("@rcompat/error").TemplateError;
4
4
  declare const errors: {
5
5
  only_route_files: typeof only_route_files;
6
- package_not_found: typeof package_not_found;
7
- package_mismatch: typeof package_mismatch;
6
+ pkg_not_found: typeof pkg_not_found;
7
+ pkg_mismatch: typeof pkg_mismatch;
8
8
  };
9
9
  export type Code = keyof typeof errors;
10
10
  export declare const Code: { [K in Code]: K; };
@@ -5,19 +5,19 @@ const t = error.template;
5
5
  function only_route_files() {
6
6
  return t `python: only route files are supported`;
7
7
  }
8
- function package_not_found() {
8
+ function pkg_not_found() {
9
9
  const command = `pip install ${PACKAGE}~=${server.TAG}.0`;
10
10
  return t `package not found, run ${command}`;
11
11
  }
12
- function package_mismatch(major, minor) {
12
+ function pkg_mismatch(major, minor) {
13
13
  const range = `~> ${server.TAG}.x`;
14
14
  const version = `${major}.${minor}.x`;
15
15
  return t `${PACKAGE} package version ${version} not in range ${range}`;
16
16
  }
17
17
  const errors = error.coded({
18
18
  only_route_files,
19
- package_not_found,
20
- package_mismatch,
19
+ pkg_not_found,
20
+ pkg_mismatch,
21
21
  });
22
22
  export const Code = Object.fromEntries(Object.keys(errors).map(k => [k, k]));
23
23
  export default errors;
@@ -1,3 +1,3 @@
1
- declare const _default: "__PRMT__";
1
+ declare const _default = "__PRMT__";
2
2
  export default _default;
3
3
  //# sourceMappingURL=handler-property.d.ts.map
@@ -1,5 +1,5 @@
1
1
  declare const _default: {
2
- type(value: unknown): "string" | "boolean" | "array" | "object" | "integer" | "float" | "nil" | undefined;
2
+ type(value: unknown): "array" | "boolean" | "float" | "integer" | "nil" | "object" | "string" | undefined;
3
3
  };
4
4
  export default _default;
5
5
  //# sourceMappingURL=helpers.d.ts.map
@@ -1,7 +1,7 @@
1
1
  declare const module: {
2
2
  schema: import("pema").ObjectType<import("pema").NormalizeSchemaObject<{
3
3
  readonly extension: import("pema").OptionalType<import("pema").StringType>;
4
- }>, {
4
+ }>, undefined, {
5
5
  extension: string | undefined;
6
6
  }>;
7
7
  name: string;
@@ -1,4 +1,4 @@
1
- import type { RequestFacade } from "@primate/core";
1
+ import type { RequestContentType, RequestFacade } from "@primate/core";
2
2
  import type { Dict } from "@rcompat/type";
3
3
  type FileEntry = {
4
4
  bytes: Uint8Array;
@@ -7,35 +7,33 @@ type FileEntry = {
7
7
  size: number;
8
8
  type: string;
9
9
  };
10
- export default function to_request(request: RequestFacade): Promise<{
11
- url: {
12
- href: string;
13
- origin: string;
14
- protocol: string;
15
- username: string;
16
- password: string;
17
- host: string;
18
- hostname: string;
19
- port: string;
20
- pathname: string;
21
- search: string;
22
- hash: string;
23
- };
24
- body: {
25
- text: () => string;
26
- json: () => string;
27
- form: () => Dict<string>;
28
- files: () => FileEntry[];
29
- binary: () => {
30
- buffer: Uint8Array<ArrayBuffer>;
31
- mime: string;
32
- };
33
- none: () => null;
34
- };
35
- path: Dict;
36
- query: Dict;
37
- headers: Dict;
38
- cookies: Dict;
10
+ type BridgedBody = {
11
+ type: "json";
12
+ jsonSync: () => string;
13
+ } | {
14
+ type: "text";
15
+ textSync: () => string;
16
+ } | {
17
+ type: "form";
18
+ formSync: () => string;
19
+ } | {
20
+ type: "multipart";
21
+ formSync: () => string;
22
+ filesSync: () => FileEntry[];
23
+ } | {
24
+ type: "blob";
25
+ blobSync: () => Uint8Array;
26
+ blobTypeSync: () => string;
27
+ } | {
28
+ type: "none";
29
+ };
30
+ export default function to_request(request: RequestFacade, contentType: RequestContentType | ""): Promise<{
31
+ url: URL;
32
+ body: BridgedBody;
33
+ path: Dict<string>;
34
+ query: Dict<string>;
35
+ headers: Dict<string>;
36
+ cookies: Dict<string>;
39
37
  }>;
40
38
  export {};
41
39
  //# sourceMappingURL=to-request.d.ts.map
@@ -1,25 +1,45 @@
1
- function plainUrl(u) {
2
- return {
3
- href: u.href,
4
- origin: u.origin,
5
- protocol: u.protocol,
6
- username: u.username,
7
- password: u.password,
8
- host: u.host,
9
- hostname: u.hostname,
10
- port: u.port,
11
- pathname: u.pathname,
12
- search: u.search,
13
- hash: u.hash,
14
- };
1
+ async function bridge_body(body, contentType) {
2
+ switch (contentType) {
3
+ case "text/plain": {
4
+ const s = await body.text();
5
+ return { type: "text", textSync: () => s };
6
+ }
7
+ case "application/json": {
8
+ const val = await body.json();
9
+ return { type: "json", jsonSync: () => JSON.stringify(val) };
10
+ }
11
+ case "application/x-www-form-urlencoded": {
12
+ const form = await body.form();
13
+ return { type: "form", formSync: () => JSON.stringify(form) };
14
+ }
15
+ case "multipart/form-data": {
16
+ const { form, files } = await body.multipart();
17
+ const pending = [];
18
+ const bridgedFiles = [];
19
+ for (const [field, file] of Object.entries(files)) {
20
+ const name = file.name;
21
+ const type = file.type;
22
+ const size = file.size;
23
+ pending.push(file.arrayBuffer().then(buffer => {
24
+ bridgedFiles.push({ bytes: new Uint8Array(buffer), field, name, size, type });
25
+ }));
26
+ }
27
+ await Promise.all(pending);
28
+ return { type: "multipart", formSync: () => JSON.stringify(form), filesSync: () => bridgedFiles };
29
+ }
30
+ case "application/octet-stream": {
31
+ const blob = await body.blob();
32
+ const buf = new Uint8Array(await blob.arrayBuffer());
33
+ return { type: "blob", blobSync: () => buf, blobTypeSync: () => blob.type || "application/octet-stream" };
34
+ }
35
+ default:
36
+ return { type: "none" };
37
+ }
15
38
  }
16
- function toDict(obj) {
39
+ function to_dict(obj) {
17
40
  const out = Object.create(null);
18
41
  if (obj instanceof URLSearchParams) {
19
- obj.forEach((v, k) => {
20
- if (!(k in out))
21
- out[k] = v ?? "";
22
- });
42
+ obj.forEach((v, k) => { out[k] = v; });
23
43
  }
24
44
  else {
25
45
  for (const [k, v] of Object.entries(obj)) {
@@ -28,71 +48,15 @@ function toDict(obj) {
28
48
  }
29
49
  return out;
30
50
  }
31
- async function bridge_form(body) {
32
- const form = Object.create(null);
33
- const files = [];
34
- const pending = [];
35
- for (const [k, v] of Object.entries(body.form())) {
36
- form[k] = v;
37
- }
38
- for (const [k, v] of Object.entries(body.files())) {
39
- const name = v.name;
40
- const type = v.type;
41
- const size = v.size;
42
- pending.push(v.arrayBuffer().then(buffer => {
43
- files.push({
44
- bytes: new Uint8Array(buffer),
45
- field: k,
46
- name,
47
- size,
48
- type,
49
- });
50
- }));
51
- }
52
- await Promise.all(pending);
53
- return {
54
- form: () => form,
55
- files: () => files,
56
- };
57
- }
58
- async function bridgeBody(body) {
59
- let form, buffer, blob;
60
- if (body.type === "form") {
61
- form = await bridge_form(body);
62
- }
63
- if (body.type === "binary") {
64
- blob = body.binary();
65
- buffer = new Uint8Array(await blob.arrayBuffer());
66
- }
67
- return {
68
- text: () => body.text(),
69
- json: () => {
70
- return JSON.stringify(body.json());
71
- },
72
- form: () => form.form(),
73
- files: () => form.files(),
74
- binary: () => {
75
- const mime = blob.type || "application/octet-stream";
76
- return {
77
- buffer,
78
- mime,
79
- };
80
- },
81
- none: () => null,
82
- };
83
- }
84
- export default async function to_request(request) {
85
- const body = await bridgeBody(request.body);
86
- const cookies = toDict(request.cookies.toJSON());
87
- const headers = toDict(request.headers.toJSON());
88
- const path = toDict(request.path.toJSON());
89
- const query = toDict(request.query.toJSON());
90
- const u = request.url;
91
- const url = plainUrl(new URL(String(u)));
51
+ export default async function to_request(request, contentType) {
52
+ const body = await bridge_body(request.body, contentType);
92
53
  return {
93
- url,
54
+ url: request.url,
94
55
  body,
95
- path, query, headers, cookies,
56
+ path: request.path.toJSON(),
57
+ query: request.query.toJSON(),
58
+ headers: request.headers.toJSON(),
59
+ cookies: request.cookies.toJSON(),
96
60
  };
97
61
  }
98
62
  //# sourceMappingURL=to-request.js.map
@@ -1,6 +1,6 @@
1
- import { type ResponseLike } from "@primate/core/response";
1
+ import type { ResponseLike } from "@primate/core";
2
2
  import type { Dict } from "@rcompat/type";
3
3
  import type { PyProxy } from "pyodide/ffi";
4
- declare const _default: (response: Dict | PyProxy) => ResponseLike;
5
- export default _default;
4
+ declare function to_response(args: Dict | PyProxy | undefined): ResponseLike;
5
+ export default to_response;
6
6
  //# sourceMappingURL=to-response.d.ts.map
@@ -1,26 +1,33 @@
1
1
  import HANDLER_PROPERTY from "#handler-property";
2
2
  import unwrap from "#unwrap";
3
3
  import response from "@primate/core/response";
4
+ import is from "@rcompat/is";
4
5
  const { error, redirect, view } = response;
5
6
  const handlers = { error, redirect, view };
6
- const handle_handler = (handler, response) => {
7
+ const handle_handler = (handler, args) => {
7
8
  if (handler === "view") {
8
- const { name, options, props } = response;
9
+ const { name, options, props } = args;
9
10
  return view(name, props, options);
10
11
  }
11
12
  if (handler === "redirect") {
12
- const { location, status } = response;
13
+ const { location, status } = args;
13
14
  return redirect(location, status);
14
15
  }
15
- const { options } = response;
16
+ const { options } = args;
16
17
  return error(options);
17
18
  };
18
- const is_handler = (handler) => typeof handler === "string" && Object.keys(handlers).includes(handler);
19
- export default (response) => {
20
- const unwrapped = unwrap(response);
19
+ function is_handler(x) {
20
+ return is.string(x) && Object.keys(handlers).includes(x);
21
+ }
22
+ function to_response(args) {
23
+ if (is.undefined(args))
24
+ return null;
25
+ const unwrapped = unwrap(args);
21
26
  const handler = unwrapped[HANDLER_PROPERTY];
22
27
  return is_handler(handler)
23
28
  ? handle_handler(handler, unwrapped)
24
29
  : unwrapped;
25
- };
30
+ }
31
+ ;
32
+ export default to_response;
26
33
  //# sourceMappingURL=to-response.js.map
@@ -1,5 +1,4 @@
1
+ import type { Dict } from "@rcompat/type";
1
2
  import type { PyProxy } from "pyodide/ffi";
2
- export default function unwrap(response: PyProxy): {
3
- [k: string]: unknown;
4
- };
3
+ export default function unwrap(response: PyProxy): Dict;
5
4
  //# sourceMappingURL=unwrap.d.ts.map
@@ -1,5 +1,5 @@
1
1
  export default function wrapper(source: string, packages: string[], primate_run: string, id: string, context?: {
2
2
  i18n?: any;
3
3
  session?: any;
4
- }): Promise<void>;
4
+ }): Promise<Record<string, (request: any) => Promise<any>>>;
5
5
  //# sourceMappingURL=wrapper.d.ts.map
@@ -3,7 +3,6 @@ import helpers from "@primate/python/helpers";
3
3
  import pyodide from "@primate/python/pyodide";
4
4
  import to_request from "@primate/python/to-request";
5
5
  import to_response from "@primate/python/to-response";
6
- import route from "primate/route";
7
6
  const messageCallback = () => { };
8
7
  let _micropip = null;
9
8
  const installed = new Set();
@@ -48,6 +47,16 @@ function wrap_i18n(i18n) {
48
47
  set(locale) { i18n.locale.set(locale); },
49
48
  };
50
49
  }
50
+ async function get_entries(python, route_id) {
51
+ const result = python.runPython(`
52
+ [{"verb": verb, "content_type": entry["content_type"] or ""}
53
+ for verb, entry in Route.registry(${JSON.stringify(route_id)}).items()]
54
+ `).toJs({ dict_converter: Object.fromEntries });
55
+ return result.map((e) => ({
56
+ verb: String(e.verb),
57
+ content_type: String(e.content_type),
58
+ }));
59
+ }
51
60
  export default async function wrapper(source, packages, primate_run, id, context = {}) {
52
61
  const python = await pyodide();
53
62
  const micropip = await load_micropip(python);
@@ -62,24 +71,23 @@ export default async function wrapper(source, packages, primate_run, id, context
62
71
  Route.scope(${route_id})
63
72
  `);
64
73
  await python.runPython(source);
65
- const verbs = python.runPython(`
66
- from primate import Route
67
- list(Route.registry(${route_id}).keys())
68
- `).toJs();
74
+ const entries = await get_entries(python, id);
69
75
  const wrapped_session = wrap_session(context.session);
70
76
  const wrapped_i18n = wrap_i18n(context.i18n);
71
- for (const verb of verbs) {
72
- route[verb.toLowerCase()](async (request) => {
73
- python.globals.set("js_req", await to_request(request));
77
+ return Object.fromEntries(entries.map(({ verb, content_type }) => [
78
+ verb.toLowerCase(),
79
+ async (request) => {
80
+ const jsReq = await to_request(request, content_type);
81
+ python.globals.set("js_req", jsReq);
74
82
  python.globals.set("helpers_obj", helpers);
75
83
  python.globals.set("session_obj", wrapped_session);
76
84
  python.globals.set("i18n_obj", wrapped_i18n);
77
85
  const verb_str = JSON.stringify(verb);
78
86
  try {
79
87
  const result = await python.runPythonAsync(`
80
- from primate import Route
81
- await Route.call_js(${route_id}, ${verb_str}, js_req, helpers_obj, session_obj, i18n_obj)
82
- `);
88
+ from primate import Route
89
+ await Route.call_js(${route_id}, ${verb_str}, js_req, helpers_obj, session_obj, i18n_obj)
90
+ `);
83
91
  return to_response(result);
84
92
  }
85
93
  catch (e) {
@@ -92,7 +100,7 @@ export default async function wrapper(source, packages, primate_run, id, context
92
100
  python.globals.delete("session_obj");
93
101
  python.globals.delete("i18n_obj");
94
102
  }
95
- });
96
- }
103
+ },
104
+ ]));
97
105
  }
98
106
  //# sourceMappingURL=wrapper.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@primate/python",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "description": "Python backend for Primate",
5
5
  "homepage": "https://primate.run/docs/backend/python",
6
6
  "bugs": "https://github.com/primate-run/primate/issues",
@@ -17,19 +17,20 @@
17
17
  "!/**/*.spec.*"
18
18
  ],
19
19
  "dependencies": {
20
- "@rcompat/assert": "^0.8.1",
21
- "@rcompat/error": "^0.3.1",
22
- "@rcompat/fs": "^0.28.1",
23
- "@rcompat/io": "^0.5.1",
24
- "pyodide": "^0.29.3",
25
- "@primate/core": "^0.6.0",
26
- "pema": "^0.6.0"
20
+ "@rcompat/assert": "^0.13.0",
21
+ "@rcompat/error": "^0.8.0",
22
+ "@rcompat/fs": "^0.33.2",
23
+ "@rcompat/io": "^0.10.0",
24
+ "@rcompat/is": "^0.11.0",
25
+ "pyodide": "^0.29.4",
26
+ "pema": "^0.8.0",
27
+ "@primate/core": "^0.8.0"
27
28
  },
28
29
  "devDependencies": {
29
- "@rcompat/type": "^0.11.1"
30
+ "@rcompat/type": "^0.17.0"
30
31
  },
31
32
  "peerDependencies": {
32
- "primate": "^0.37.0"
33
+ "primate": "^0.39.0"
33
34
  },
34
35
  "imports": {
35
36
  "#*": {
@@ -48,9 +49,8 @@
48
49
  }
49
50
  },
50
51
  "scripts": {
51
- "build": "npm run clean && tsc",
52
+ "build": "npm run clean && tsgo",
52
53
  "clean": "rm -rf ./lib",
53
- "lint": "eslint .",
54
- "test": "npx proby"
54
+ "lint": "eslint ."
55
55
  }
56
56
  }